Check if Numbers Are Ascending in a Sentence - Problem

Imagine you're reading a sentence and need to verify that any numbers mentioned are in strictly ascending order from left to right. This is exactly what this problem asks you to do!

Given a string s representing a sentence, you need to check if all the numbers in the sentence are strictly increasing from left to right. A sentence consists of tokens separated by single spaces, where each token is either:

  • A positive number (digits 0-9, no leading zeros)
  • A word (lowercase English letters)

Example: In the sentence "a puppy has 2 eyes 4 legs", we have numbers 2 and 4. Since 2 < 4, the numbers are in ascending order, so we return true.

Goal: Return true if all numbers in the sentence are in strictly ascending order, false otherwise. If there's only one number or no numbers, return true.

Input & Output

example_1.py โ€” Basic Ascending
$ Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"
โ€บ Output: true
๐Ÿ’ก Note: The numbers are 1, 3, 4, 6, 12 which are in strictly ascending order: 1 < 3 < 4 < 6 < 12
example_2.py โ€” Not Ascending
$ Input: s = "hello world 5 x 1"
โ€บ Output: false
๐Ÿ’ก Note: The numbers are 5 and 1. Since 5 > 1, they are not in ascending order
example_3.py โ€” No Numbers
$ Input: s = "sunset is at seven forty five pm"
โ€บ Output: true
๐Ÿ’ก Note: There are no numeric tokens in this sentence, so we return true by default

Constraints

  • 3 โ‰ค s.length โ‰ค 200
  • s consists of lowercase English letters, spaces, and digits from 0 to 9
  • The number of tokens in s is between 2 and 100
  • The tokens are separated by a single space
  • No leading or trailing spaces
  • Numbers have no leading zeros

Visualization

Tap to expand
Timeline Validation Analogy"Born in 1990, graduated in 2012, married in 2018, retired in 2055"19902012201820551990 < 2012 โœ“2012 < 2018 โœ“2018 < 2055 โœ“Valid Timeline!All years in ascending orderAlgorithm InsightWe only need to remember the last year (number) seen!Compare each new year with the previous one - O(1) space!
Understanding the Visualization
1
Start Scanning
Begin with last_number = -1 and scan tokens left to right
2
Find Number
When a numeric token is found, compare it with the last seen number
3
Validate Order
If current โ‰ค last, return false immediately; otherwise update last number
4
Continue or Return
Continue scanning or return true if all numbers are processed
Key Takeaway
๐ŸŽฏ Key Insight: We only need O(1) space by tracking just the last number seen, not storing all numbers!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
24.5K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen