#2442

Count Number of Distinct Integers After Reverse Operations

Medium
ArrayHash TableMathCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a set to store the original numbers and their reversed counterparts. This allows us to efficiently track distinct integers without needing to create a combined array.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty set to hold distinct numbers.
  2. 2Step 2: For each number in the input array, add it to the set.
  3. 3Step 3: Reverse the number and add the reversed number to the set.
  4. 4Step 4: Return the size of the set as the count of distinct integers.
solution.py8 lines
1# Full working Python code
2nums = [1, 13, 10, 12, 31]
3distinct_set = set()
4for num in nums:
5    distinct_set.add(num)
6    reversed_num = int(str(num)[::-1])
7    distinct_set.add(reversed_num)
8print(len(distinct_set))

Complexity note: The time complexity is O(n) because we process each number once, and adding to a set is average O(1). The space complexity is O(n) due to the storage of distinct numbers in the set.

  • 1Using a set efficiently tracks distinct elements.
  • 2Reversing digits can be done easily with string manipulation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.