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

Check if Numbers Are Ascending in a Sentence

Number: 2168

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a sentence where each token is either a positive number (with no leading zeros) or a lowercase word, determine if all the numbers in the sentence are strictly increasing from left to right.


Key Insights

  • Split the sentence into tokens using space as the delimiter.
  • Identify if a token is a number by checking if the token consists entirely of digits.
  • Convert numeric tokens into integers and compare to ensure that each number is strictly greater than the previous one.
  • Non-numeric tokens (words) can be ignored during the comparison.

Space and Time Complexity

Time Complexity: O(n) where n is the number of tokens (or the length of the sentence), since each token is processed once. Space Complexity: O(n) due to the storage of tokens from the sentence split.


Solution

We split the sentence into individual tokens. Then, we iterate over these tokens, ignoring the words and converting the numeric tokens to integers. As we iterate, we maintain a variable to store the previous number encountered. For each numeric token, if its integer value is not strictly greater than the previous number, we return false. If all numeric tokens pass this check, we return true. This approach makes a single pass through the list of tokens and uses simple integer comparisons.


Code Solutions

def areNumbersAscending(s):
    # Split the sentence into tokens
    tokens = s.split(" ")
    prev_number = -1  # initialize previous number to a value lower than any positive number
    
    # Iterate through each token
    for token in tokens:
        # Check if the token is a number using str.isdigit()
        if token.isdigit():
            curr_number = int(token)  # Convert token string to integer
            # Verify that the current number is strictly greater than the previous number
            if curr_number <= prev_number:
                return False
            # Update previous number
            prev_number = curr_number
    return True

# Example usage:
s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"
print(areNumbersAscending(s))  # Expected output: True
← Back to All Questions