algoadvance

Leetcode 1805. Number of Different Integers in a String

Problem Statement:

Given a string word composed of digits and lowercase English letters, you need to find the number of different integers in the string. An integer is a contiguous sequence of digits, which may not have leading zeros.

Example:

Clarifying Questions:

  1. Should numbers be considered only if they are contiguous?
    • Yes, only contiguous sequences of digits should be considered as integers.
  2. Can leading zeros be disregarded when comparing two numbers?
    • Yes, leading zeros should be ignored when determining if two numbers are the same.
  3. Are there any constraints on the string length?
    • Yes, according to LeetCode’s typical constraints, the string length should be manageable within usual competitive programming limits (up to (10^5) characters).

Strategy:

  1. Traverse the string to extract all contiguous subsequences of digits.
  2. Use a set to store these integers in string form (while stripping leading zeros).
  3. The size of the set at the end will represent the number of distinct integers.

Code Implementation:

#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;

int numDifferentIntegers(string word) {
    unordered_set<string> uniqueIntegers;
    int n = word.length();
    string currentNumber = "";

    for (int i = 0; i < n; ++i) {
        if (isdigit(word[i])) {
            currentNumber += word[i];
        } else {
            if (!currentNumber.empty()) {
                // Remove leading zeros
                int index = 0;
                while (index < currentNumber.length() && currentNumber[index] == '0') {
                    ++index;
                }
                string cleanNumber = currentNumber.substr(index);
                if (cleanNumber.empty()) {
                    cleanNumber = "0";
                }
                uniqueIntegers.insert(cleanNumber);
                currentNumber = "";
            }
        }
    }
    
    // Check if there's a number left at the end of the string
    if (!currentNumber.empty()) {
        int index = 0;
        while (index < currentNumber.length() && currentNumber[index] == '0') {
            ++index;
        }
        string cleanNumber = currentNumber.substr(index);
        if (cleanNumber.empty()) {
            cleanNumber = "0";
        }
        uniqueIntegers.insert(cleanNumber);
    }
    
    return uniqueIntegers.size();
}

int main() {
    string word;
    cin >> word;
    cout << numDifferentIntegers(word) << endl;
    return 0;
}

Time Complexity:

This solution efficiently identifies and counts the distinct integers within the input string.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI