Python 1805.py
class Solution:
def numDifferentIntegers(self, word: str) -> int:
clean = ""
for c in word:
clean += c if c >= "0" and c <= "9" else " "
# note: two consecutive spaces => empty string after split, do not convert to zero
return len(set([ int(n) for n in clean.split(" ") if n != "" ]))
Difficulty
and has an acceptance rate of about 41% (100k+ submissions).
Typical patterns to solve this problem:
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method numDifferentIntegers. The method receives a string that may contain alphabetic characters, digits, and other symbols. Its purpose is to identify every integer that appears in the string, treat numbers with leading zeros as the same value, and return the count of distinct integers.
The algorithm proceeds in three logical phases: normalizing the input to isolate numeric characters, splitting the normalized string into individual numeric tokens, and converting those tokens to integer objects before deduplication with a set. The final result is the size of that set.
Step 1: Normalizing the Input
clean = ""
for c in word:
clean += c if c >= "0" and c <= "9" else " "
In this phase the code iterates over each character c of the original string word. If c falls within the ASCII range for digits ('0' through '9'), it is appended unchanged to the accumulator clean. Otherwise a single space character is appended. The effect is to replace every non-digit with a delimiter while preserving the original order of digits.
Step 2: Tokenizing Numbers
clean.split(" ")
After the loop, clean consists of digit sequences separated by spaces. Calling split(" ") produces a list of substrings. Consecutive spaces generate empty strings in the resulting list, which are later filtered out. This step isolates each contiguous block of digits that represents a candidate integer.
Step 3: Converting and Deduplicating
len(set([ int(n) for n in clean.split(" ") if n != "" ]))
A list comprehension iterates over the split substrings, discarding any empty entry (if n != ""). Each remaining token n is passed to int(), which automatically removes any leading zeros and creates a Python integer object of arbitrary size. The list of integers is then wrapped with set(), which eliminates duplicate values. Finally, len() returns the number of unique integers found.
Edge Cases Handled
The implementation gracefully manages several edge conditions:
- Multiple consecutive non-digit characters: The replacement with spaces yields empty tokens after splitting, which are filtered out by the
if n != ""guard, ensuring they do not contribute spurious zeros. - Leading zeros: Converting each token with
int()strips any leading zeros, so"0012"and"12"are treated as the same integer. - String containing no digits: The split operation yields only empty strings, the list comprehension produces an empty list, the set is empty, and
len()correctly returns0. - Very large numeric values: Python’s
inttype supports arbitrary precision, so numbers that exceed typical 32- or 64-bit limits are handled without overflow. - Trailing or leading non-digit characters: These become leading or trailing spaces in
clean, which again result in empty tokens that are ignored.
Performance Considerations
The algorithm operates in a single pass over the input string to build clean, followed by a split and a single pass over the resulting tokens for conversion and deduplication. The use of a set provides constant-time membership checks for duplicate elimination. By converting each token directly to an integer, the code leverages Python’s built-in parsing, which is highly optimized in C. The overall flow avoids nested loops or repeated scanning of the same data, yielding efficient execution even for long input strings.
ELI5 - Simplified Explanation
Imagine a long string of letters and numbers, like a secret message jumbled together. The code acts like a very smart robot that goes through every single character in that message. The robot looks at each character and decides if it is a number or a letter. If it finds a number, it keeps it, but if it finds a letter, it replaces it with a little space.
After the robot finishes checking every character, the message looks like a bunch of numbers separated by empty spaces. The computer then chops up this message at every space to pull out all the separate number groups it found.
Because the same number might appear more than once in the message, the computer collects all these numbers into a special bag that only keeps one copy of each unique number. Finally, the computer counts how many items are inside that bag to see how many different numbers were in the original message.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | JS | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | JavaScript | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2419: Longest Subarray With Maximum Bitwise AND
Solved On The Same Day
- problem 859: Buddy Strings
- problem 914: X of a Kind in a Deck of Cards
- problem 925: Long Pressed Name
- problem 1346: Check If N and Its Double Exist
- problem 1909: Remove One Element to Make the Array Strictly Increasing
- problem 2047: Number of Valid Words in a Sentence
- problem 2469: Convert the Temperature
- problem 2525: Categorize Box According to Criteria
- problem 2591: Distribute Money to Maximum Children
- problem 2614: Prime In Diagonal
- problem 2660: Determine the Winner of a Bowling Game
- problem 2760: Longest Even Odd Subarray With Threshold
- problem 2765: Longest Alternating Subarray
- problem 1255: Maximum Score Words Formed by Letters
- problem 2251: Number of Flowers in Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality