Number of Different Integers in a String - Problem

You're given a string word that contains a mix of digits and lowercase English letters. Your task is to extract all the integers from this string and count how many unique integers there are.

Here's how it works:

  • Replace every non-digit character with a space
  • This creates a sequence of integers separated by spaces
  • Count the number of different integers (ignoring leading zeros)

Example: "a123bc34d8ef34" becomes " 123 34 8 34"

The extracted integers are: 123, 34, 8, and 34. Since 34 appears twice, we have 3 unique integers.

Note: Leading zeros are ignored when comparing integers. For example, "01" and "1" represent the same integer.

Input & Output

example_1.py โ€” Basic Mixed String
$ Input: word = "a123bc34d8ef34"
โ€บ Output: 3
๐Ÿ’ก Note: After replacing non-digits with spaces, we get " 123 34 8 34". The unique integers are 123, 34, and 8. Note that 34 appears twice but is counted only once.
example_2.py โ€” Leading Zeros
$ Input: word = "leet1234code234"
โ€บ Output: 2
๐Ÿ’ก Note: After processing, we get " 1234 234". The unique integers are 1234 and 234, so the answer is 2.
example_3.py โ€” Leading Zeros Edge Case
$ Input: word = "a1b01c001"
โ€บ Output: 1
๐Ÿ’ก Note: After processing, we get " 1 01 001". When we remove leading zeros, all three become "1", so there's only 1 unique integer.

Visualization

Tap to expand
Smart Integer Extraction ProcessInput String: "a123bc34d8ef34"a123bc34Extraction Process1. Build "123" from digits2. Hit 'b' โ†’ save "123"3. Build "34" from digits4. Continue pattern...Hash Set (Auto-Deduplication)Step 1: Add "123"123Step 2: Add "34"12334Step 3: Add "8"123348Step 4: Try "34" againAlready exists - ignored!Final Count: 3Set.size() = 3Time: O(n)Space: O(k)
Understanding the Visualization
1
Scan Characters
Read each character, building integers when we see digits
2
Normalize Numbers
Remove leading zeros by converting to integer and back to string
3
Add to Set
Hash set automatically prevents duplicates
4
Count Result
Set size equals number of unique integers
Key Takeaway
๐ŸŽฏ Key Insight: Hash sets provide automatic deduplication - just normalize integers (remove leading zeros) and let the set handle uniqueness checking for you!

Time & Space Complexity

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

Single pass through the string of length n, hash set operations are O(1) average

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

Space for storing k unique integers in the hash set

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค word.length โ‰ค 1000
  • word consists of digits and lowercase English letters
  • Leading zeros are ignored when comparing integers
Asked in
Amazon 35 Microsoft 28 Google 22 Meta 18
28.5K Views
Medium Frequency
~15 min Avg. Time
890 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