Skip to content

Instantly share code, notes, and snippets.

@torressam333
Created December 16, 2022 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torressam333/731fa15526e99ed7d996ebaf7bd28fc7 to your computer and use it in GitHub Desktop.
Save torressam333/731fa15526e99ed7d996ebaf7bd28fc7 to your computer and use it in GitHub Desktop.
Solved same frequency challenge using JavsScript
/**
* Write a function called sameFrequency. Given two positive integers, find out if the two numbers have the same frequency of digits.
The solution MUST have the following complexities:
Time: O(N)
Sample Input:
sameFrequency(182,281) // true
sameFrequency(34,14) // false
sameFrequency(3589578, 5879385) // true
sameFrequency(22,222) // false
*/
const sameFrequency = (num1, num2) => {
if (!num1 || !num2) return false;
if (num1 === num2) return true;
let store1 = {};
let store2 = {};
let num1Arr = num1.toString().split("");
let num2Arr = num2.toString().split("");
for (let num of num1Arr) {
store1[num] = (store1[num] || 0) + 1;
}
for (let num of num2Arr) {
store2[num] = (store2[num] || 0) + 1;
}
for (let key in store1) {
if (!(key in store2)) return false;
if (store1[key] !== store2[key]) return false;
}
return true;
};
console.log(sameFrequency(34, 14)); // false
console.log(sameFrequency(182, 281)); // true
console.log(sameFrequency(3589578, 5879385)); // true
console.log(sameFrequency(22, 222)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment