1 minute read

You are given an array nums consisting of positive integers.

You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums.

Return the number of distinct integers in the final array.

Example 1:

Input: nums = [1,13,10,12,31] Output: 6 Explanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13]. The reversed integers that were added to the end of the array are underlined. Note that for the integer 10, after reversing it, it becomes 01 which is just 1. The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31). Example 2:

Input: nums = [2,2,2] Output: 1 Explanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2]. The number of distinct integers in this array is 1 (The number 2).

Constraints:

1 <= nums.length <= 105 1 <= nums[i] <= 106

/**
 * @param {number[]} nums
 * @return {number}
 */
var countDistinctIntegers = function (nums) {
  let resultArray = [...nums];

  for (let num of nums) {
    let n = parseInt(num.toString().split("").reverse().join(""));
    resultArray.push(n);
  }

  let numSet = new Set(resultArray);
  return numSet.size;
};

The time complexity of this solution is O(n) where n is the number of elements in the input array nums. This is because we iterate through each element in the array once to reverse the digits and add them to the resultArray, and then we create a set from the resultArray which has a linear time complexity.

The space complexity is also O(n) because we are creating a new array resultArray that can potentially have the same number of elements as the input array nums, and then creating a set from that array which can also have the same number of elements.

Leave a comment