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: nums = [1,13,10,12,31]
should return 6. The resulting array after reversal is [1,13,10,12,31,1,31,1,21,13]
, with distinct integers 1, 10, 12, 13, 21, and 31. Example 2: nums = [2,2,2]
should return 1. The resulting array after reversal is [2,2,2,2,2,2]
, with distinct integer 2.
## Problem: Distinct Integers After Reversing Digits
Given an array `nums` of positive integers, reverse the digits of each integer and add it to the end of the array. Return the number of distinct integers in the final array.
**Example:**
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 number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).
## Naive Solution
A straightforward approach is to iterate through the original array, reverse each number, add it to the array, and then count the distinct elements. This involves converting integers to strings for reversal and using a set to track distinct values.
```python
def distinct_integers_naive(nums):
reversed_nums = []
for num in nums:
reversed_num = int(str(num)[::-1])
reversed_nums.append(reversed_num)
combined_nums = nums + reversed_nums
return len(set(combined_nums))
This solution improves the time complexity by reversing integers directly without string conversions. We'll still use a set to efficiently determine distinct numbers.
def reverse_integer(n):
reversed_n = 0
while n > 0:
reversed_n = reversed_n * 10 + n % 10
n //= 10
return reversed_n
def distinct_integers_optimal(nums):
reversed_nums = [reverse_integer(num) for num in nums]
combined_nums = nums + reversed_nums
return len(set(combined_nums))
reverse_integer
function iterates through the digits of each number. In the worst case, a number can have at most log10(n)
digits. Since we do this for n
numbers, the time complexity is O(N * log(M)), where N is the number of elements in nums
and M is the maximum value in nums
Therefore, the overall time complexity is O(N * log(M))
Therefore, the overall space complexity is O(N).
# Example Usage:
nums1 = [1, 13, 10, 12, 31]
print(f"Distinct integers: {distinct_integers_optimal(nums1)}") # Output: 6
nums2 = [2, 2, 2]
print(f"Distinct integers: {distinct_integers_optimal(nums2)}") # Output: 1
nums3 = []
print(f"Distinct integers: {distinct_integers_optimal(nums3)}") # Output: 0