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

Difficulty: Easy


Problem Description

Given a string s representing a sentence, check if all the numbers in s are strictly increasing from left to right.


Key Insights

  • A sentence consists of tokens that can be either positive numbers or words.
  • The numbers must be strictly increasing, meaning each number must be smaller than the subsequent number.
  • The problem can be solved by extracting numbers from the string and verifying their order.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string s, since we need to traverse the string to extract tokens. Space Complexity: O(m), where m is the number of numbers in the string, to store the extracted numbers.


Solution

The solution involves the following steps:

  1. Split the input string into tokens based on spaces.
  2. Extract numbers from the tokens and convert them to integers.
  3. Iterate through the list of numbers and check if each number is less than the next one.
  4. Return true if all numbers are in strictly increasing order; otherwise, return false.

This approach uses a list to store the extracted numbers and a simple loop to verify the order, making it efficient and straightforward.


Code Solutions

def are_numbers_ascending(s: str) -> bool:
    tokens = s.split()  # Split the sentence into tokens
    previous_number = -1  # Initialize the previous number to a value less than any possible valid number

    for token in tokens:
        if token.isdigit():  # Check if the token is a number
            current_number = int(token)  # Convert the token to an integer
            if current_number <= previous_number:  # Check if the current number is not greater than the previous
                return False  # Return false if the order is violated
            previous_number = current_number  # Update the previous number to the current one

    return True  # Return true if all numbers are strictly increasing
← Back to All Questions