📘
snesjhon
  • You Should Know
  • Personal
    • Blogs
      • I'll never complain about web tooling again.
      • vscodevim
  • JavaScript
    • Closures
      • Closure Q1
    • Values
      • Primitive vs Reference
      • Accessing by value and reference
    • Function
      • call, apply, bind
      • Pass by value
      • Different types of Scopes
      • Context vs Scope
      • Parse Time Vs Run Time
    • Hosting
      • Are Let & Const Hoisted?
      • Hoisting Q1
      • Hoisting Q2
    • Standard Objects
      • Math
        • Math.log10
        • Math.pow()
    • Array
      • Apply
      • Slice vs Splice vs Split
    • This
      • This - Q1
    • TypeScript
      • as const
    • FAQs
      • Modulo Operator
      • Timeout
      • Declarative vs Imperative
      • ++i vs. i++
    • Interview Questions
  • react
    • FAQs
  • Ruby
    • Debugging
    • Symbols
    • Intro
  • Algorithms
    • Sliding Window
      • minSubArrayLen
      • maxSubArraySum
      • findLongestSubstring
    • Frequency Counter
      • sameFrequency
    • Recursion
      • nestedEvenSum
      • flatten
      • Reverse a String
      • Fibonnacci
    • Searching
      • overlappingIntervals
      • twoStringSearch
      • binarySearch
    • Sort - Elementary
      • Selection Sort
      • Bubble Sort
      • Insertion Sort
      • quickSort
    • Sort - Intermediate
      • Radix Sort
      • Merge Sort
    • FAQs
  • Data Structures
    • Breadth First Search
    • Linked Lists
      • Singly Linked Lists
    • FAQs
  • Code Challenges
    • LeetCode
      • removeDuplicates
    • Hacker Rank
      • twoSums
      • Sock Merchant
    • Hacker Rank - Medium
      • New Year Chaos
  • Databases
    • SQL
Powered by GitBook
On this page
  1. Algorithms
  2. Frequency Counter

sameFrequency

Write a function called sameFrequency Given two positive integers, find out if the two numbers have the same frequency of digits.

Your solution MUST have the following complexities.

Time: O(N)

sameFrequency(182, 281) // true
sameFrequency(34, 14) // false
sameFrequency(3589578, 5879385) // true
sameFrequency(22, 222) // false
function sameFrequency(num1, num2) {
  const arr1 = num1.toString().split("");
  const arr2 = num2.toString().split("");
  if (arr1.length !== arr2.length) return false;

  let freq = {};
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] in freq) {
      freq[arr1[i]] += 1;
    } else {
      freq[arr1[i]] = 1;
    }
  }
  for (let j = 0; j < arr2.length; j++) {
    if (arr2[j] in freq) {
      if (freq[arr2[j]] === 1) {
        delete freq[arr2[j]];
      } else {
        freq[arr2[j]] -= 1;
      }
    } else {
      return false;
    }
  }
  return Object.keys(freq).length === 0 ? true : false;
}

Last updated 4 years ago