Count Number of Distinct Integers After Reverse Operations - Problem

You're given an array nums containing positive integers. Your task is to perform a fascinating transformation: take each integer in the array, reverse its digits, and add these reversed numbers to the end of the array.

For example, if you have [13, 25], you'll reverse 13 to get 31 and 25 to get 52, resulting in the extended array [13, 25, 31, 52].

The challenge? Count how many distinct integers exist in the final array. Some numbers might appear multiple times (like when a number equals its reverse, such as palindromes), but you only count unique values.

Goal: Return the total count of distinct integers in the final transformed array.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 13, 10, 12, 31]
โ€บ Output: 6
๐Ÿ’ก Note: After reversing: 1โ†’1, 13โ†’31, 10โ†’1, 12โ†’21, 31โ†’13. Extended array: [1,13,10,12,31,1,31,1,21,13]. Distinct numbers: {1,10,12,13,21,31} = 6 total.
example_2.py โ€” With Duplicates
$ Input: nums = [2, 2, 2]
โ€บ Output: 1
๐Ÿ’ก Note: All numbers are 2, and reverse of 2 is also 2. Extended array: [2,2,2,2,2,2]. Only one distinct number: {2} = 1 total.
example_3.py โ€” Edge Case
$ Input: nums = [100]
โ€บ Output: 2
๐Ÿ’ก Note: 100 reverses to 1 (leading zeros dropped). Extended array: [100, 1]. Distinct numbers: {1, 100} = 2 total.

Visualization

Tap to expand
๐Ÿชž Magic Mirror Collection VisualizationOriginalCards1325Magic MirrorReverses DigitsMirrorCards3152๐Ÿ”ฎ Magic Deduplication TableCards automatically merge when identicalFinal Distinct Cards132531524Distinct Count
Understanding the Visualization
1
Place Original Cards
Start with cards showing [13, 25] on the magic table
2
Create Mirror Cards
Mirror creates reversed cards: 13โ†’31, 25โ†’52
3
Magic Deduplication
Table now shows {13, 25, 31, 52} - all unique
4
Count Result
Count the cards remaining: 4 distinct numbers
Key Takeaway
๐ŸŽฏ Key Insight: Hash sets provide automatic deduplication - just add both original and reversed numbers, then return the set size!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n * d)

Single pass through array (O(n)) with digit reversal for each number (O(d) where d is average digits)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash set stores at most 2n distinct numbers (worst case when no duplicates)

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 106
  • All integers in nums are positive
  • Leading zeros are dropped when reversing (e.g., 1200 โ†’ 21, not 0021)
Asked in
Amazon 35 Microsoft 28 Google 22 Meta 18
23.2K Views
Medium Frequency
~12 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen