Number of Different Integers in a String - Problem

You are given a string word that consists of digits and lowercase English letters.

You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123 34 8 34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34".

Return the number of different integers after performing the replacement operations on word.

Two integers are considered different if their decimal representations without any leading zeros are different.

Input & Output

Example 1 — Basic Case
$ Input: word = "a123bc34d8ef34"
Output: 3
💡 Note: After replacing letters with spaces: " 123 34 8 34". The unique numbers are: "123", "34", "8". Note that "34" appears twice but counts as one unique number.
Example 2 — Leading Zeros
$ Input: word = "leet1234code234"
Output: 2
💡 Note: After replacement: " 1234 234". The unique numbers are: "1234" and "234".
Example 3 — Leading Zeros Normalization
$ Input: word = "a1b01c001"
Output: 1
💡 Note: After replacement: " 1 01 001". All three numbers normalize to "1" after removing leading zeros, so there's only 1 unique number.

Constraints

  • 1 ≤ word.length ≤ 1000
  • word consists of digits and lowercase English letters.

Visualization

Tap to expand
Number of Different Integers in a String INPUT Original String: a 1 2 3 b c 3 4 d 8 e f 3 4 = Digit = Letter After replacing letters: " 123 34 8 34" Extracted integers: 123 34 8 34 word = "a123bc34d8ef34" ALGORITHM STEPS 1 Replace Letters Replace non-digits with space 2 Split by Spaces Extract integer substrings 3 Remove Leading Zeros Normalize each integer 4 Add to HashSet Duplicates auto-removed HashSet Contents: "123" "34" "8" "34" duplicate - ignored FINAL RESULT Unique Integers Found: 123 #1 34 #2 8 #3 HashSet size = unique count Output: 3 Verification: 123, 34, 8 are unique Second "34" is duplicate Key Insight: HashSet automatically handles duplicates - we just add all extracted integers and the set size gives us the count of unique values. Leading zeros must be stripped before comparison (e.g., "01" and "1" should be treated as same). TutorialsPoint - Number of Different Integers in a String | Split and Hash Set Approach
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~15 min Avg. Time
428 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