Count Number of Distinct Integers After Reverse Operations - Hashset [JS]

Description 

Solution: Hashset

Add all numbers and reversed numbers to a hashset and return the size.
Reversing a number costs O(log(n)).

Time Complexity: O(n log(n)) 243ms
Space Complexity: O(n) 78.3MB

var countDistinctIntegers = function(nums) {
  let set = new Set(nums);
  for (let num of nums) {
    set.add(reverse(num));
  }
  return set.size;
};

function reverse(num) {
  let reversed = 0;
  while (num > 0) {
    let digit = num % 10;
    reversed = reversed * 10 + digit;
    num = Math.floor(num / 10);
  }
  return reversed;
}  

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]