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
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
โ Linear Growth
Space Complexity
O(k)
Space for storing k unique integers in the hash set
โ Linear Space
Constraints
- 1 โค word.length โค 1000
- word consists of digits and lowercase English letters
- Leading zeros are ignored when comparing integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code