Given 2 postive integers, write a function to determine if they have the same number of repeated / non-repeated elements.
Thoughts:
- Since this question uses numbers instead of string it is possible to employ some JS tricks to get the individual digits
- we could stringify first and get the character in each position
- OR we could use mathematical formula to get the same result
- The mathematical method employs the same trick as in Radix Sort
- Employ the same mathematical tactic to practice since it is the more difficult solution
- Stringify method is simpler but is hard to translate over to other languages as a solution
function getNumOfDigits(num) { if (num === 0) return 1; return Math.floor(Math.log10(num)) + 1; } function getDigitByPos(num, pos) { if (num === 0) return 0; return Math.floor(num / Math.pow(10, pos)) % 10; } function ValidNumericAnagram(numX, numY) { if (getNumOfDigits(numX) !== getNumOfDigits(numY)) return false; let digitCounter = {}; let limit = getNumOfDigits(numX); for (let i=0; i<limit; i++) { const digit = getDigitByPos(numX, i); if (digitCounter[digit] === undefined) { digitCounter[digit] = 0 } digitCounter[digit]++; } for (let i=0; i<limit; i++) { const digit = getDigitByPos(numY, i); if (digitCounter[digit] === undefined) { return false; } digitCounter[digit]--; } return true; }
Top comments (0)