Problem 1805

Abstract / Summary

Count how many unique whole numbers appear in a given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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 != "" ]))
8 lines | 342 bytes | submitted October 11, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (100k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 returns 0.
  • Very large numeric values: Python’s int type 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.59 | σ = 1.19

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 16 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

16 solutions   October 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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