#2042

Check if Numbers Are Ascending in a Sentence

Easy
StringString ManipulationArray Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution improves efficiency by checking numbers as we extract them, avoiding the need to store all numbers. This allows us to compare each number with the last one directly, reducing the number of comparisons.

⚙️

Algorithm

6 steps
  1. 1Step 1: Split the sentence into tokens using spaces.
  2. 2Step 2: Initialize a variable to keep track of the last number found, starting at -1 (since numbers are positive).
  3. 3Step 3: Iterate through each token, and if it's a number, convert it and compare it with the last number.
  4. 4Step 4: If the current number is not greater than the last number, return false.
  5. 5Step 5: Update the last number to the current number and continue.
  6. 6Step 6: If the loop completes, return true.
solution.py12 lines
1# Full working Python code
2
3def are_numbers_ascending(s):
4    tokens = s.split()
5    last_number = -1
6    for token in tokens:
7        if token.isdigit():
8            current_number = int(token)
9            if current_number <= last_number:
10                return False
11            last_number = current_number
12    return True

Complexity note: The time complexity is O(n) because we only pass through the tokens once. The space complexity is O(1) since we only use a few variables to keep track of the last number.

  • 1Extracting numbers while iterating saves space and time.
  • 2Strictly increasing means no equal numbers are allowed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.