#1805

Number of Different Integers in a String

Easy
Hash TableStringHash 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 unique integers directly while processing the string. This avoids the need for nested comparisons and efficiently handles leading zeros.

⚙️

Algorithm

4 steps
  1. 1Step 1: Replace all non-digit characters with spaces.
  2. 2Step 2: Split the string into parts based on spaces.
  3. 3Step 3: Convert each part to an integer (this removes leading zeros) and add it to a set to ensure uniqueness.
  4. 4Step 4: Return the size of the set as the result.
solution.py5 lines
1# Full working Python code
2word = 'a123bc34d8ef34'
3modified = ''.join(c if c.isdigit() else ' ' for c in word)
4unique_integers = set(int(i) for i in modified.split() if i)
5result = len(unique_integers)

Complexity note: The time complexity is O(n) because we traverse the string once and use a set to store unique integers, which allows for efficient lookups.

  • 1Leading zeros are ignored when converting strings to integers.
  • 2Using a set automatically handles uniqueness.

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