Count Number of Distinct Integers After Reverse Operations - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,5,1,3]
Output: 4
💡 Note: Original: [2,5,1,3]. After adding reverses: [2,5,1,3,2,5,1,3]. Distinct values: {1,2,3,5} = 4 unique numbers.
Example 2 — Some Different Reverses
$ Input: nums = [13,32,13]
Output: 4
💡 Note: Original: [13,32,13]. Reverses: reverse(13)=31, reverse(32)=23, reverse(13)=31. Final array: [13,32,13,31,23,31]. Distinct values: {13,32,31,23} = 4 unique numbers.
Example 3 — All Same Digits
$ Input: nums = [1,13,10,12,31]
Output: 6
💡 Note: Original: [1,13,10,12,31]. Reverses: reverse(1)=1, reverse(13)=31, reverse(10)=1, reverse(12)=21, reverse(31)=13. Final: [1,13,10,12,31,1,31,1,21,13]. Distinct: {1,13,10,12,31,21} = 6 unique numbers.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Distinct Integers After Reverse INPUT Original Array: nums 2 5 1 3 [0] [1] [2] [3] Reversed Values: 2 5 1 3 rev(2)=2, rev(5)=5 rev(1)=1, rev(3)=3 Combined: [2,5,1,3,2,5,1,3] Length: 8 elements ALGORITHM STEPS 1 Initialize HashSet Create empty set to store unique integers 2 Add Original Numbers Insert each num from nums into the set 3 Reverse & Add For each num, reverse digits and add to set 4 Return Set Size Count unique values in the HashSet HashSet Contents: {1, 2, 3, 5} Duplicates auto-removed FINAL RESULT Distinct Integers Found: 6 Unique values in set: 1 2 3 5 ... Original: 2,5,1,3 Reversed: 2,5,1,3 (same single digits) OK - Answer: 6 All duplicates removed Key Insight: Using a HashSet automatically handles duplicate detection. For single-digit numbers (1-9), the reversed number equals the original. The set stores each unique integer only once, making the solution O(n) time complexity with O(n) space for the set. TutorialsPoint - Count Number of Distinct Integers After Reverse Operations | Hash Set Approach
Asked in
Amazon 15 Google 10 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
285 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