We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Different Integers in a String

Number: 1933

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string word consisting of digits and lowercase English letters, replace every non-digit character with a space. Then extract the integers (separated by at least one space) and ignore numbers that are the same after removing any leading zeros. Return the count of unique integers.


Key Insights

  • Replace all non-digit characters in the string with spaces.
  • Split the string using spaces to get the number substrings.
  • Remove leading zeros by converting each substring to an integer.
  • Use a set to track unique integers.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string, due to scanning and processing each character. Space Complexity: O(n), in the worst-case scenario where all characters form unique numbers.


Solution

The solution involves iterating over the input string and converting letters to spaces to isolate numeric sequences. After splitting the modified string into substrings, each substring is normalized by converting to an integer (thereby removing any leading zeros) and converting back to a string. These normalized number strings are stored in a set to ensure uniqueness. Finally, the size of the set, representing the number of unique integers, is returned.


Code Solutions

# Python solution with line-by-line comments:

def numDifferentIntegers(word: str) -> int:
    # Replace non-digit characters with a space
    normalized = ''.join(char if char.isdigit() else ' ' for char in word)
    # Split the normalized string into substrings
    substrings = normalized.split()
    # Use a set to store unique integers after normalization
    unique_integers = set()
    for num_str in substrings:
        # Convert string to integer to remove leading zeros, then back to string
        normalized_num = str(int(num_str))
        unique_integers.add(normalized_num)
    # Return the count of unique integers
    return len(unique_integers)

# Example usage:
print(numDifferentIntegers("a123bc34d8ef34"))  # Expected output: 3
← Back to All Questions