Check if Numbers Are Ascending in a Sentence - Problem

A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.

For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" are numbers and the other tokens such as "puppy" are words.

Given a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).

Return true if so, or false otherwise.

Input & Output

Example 1 — Numbers in Ascending Order
$ 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 increasing order: 1 < 3 < 4 < 6 < 12
Example 2 — Numbers Not in Ascending Order
$ Input: s = "hello world 5 x 1"
Output: false
💡 Note: The numbers are 5, 1 which are not in strictly increasing order since 5 > 1
Example 3 — Equal Numbers
$ Input: s = "sunset is at 7 7 pm"
Output: false
💡 Note: The numbers are 7, 7 which are not strictly increasing since 7 = 7 (not strictly greater)

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

Visualization

Tap to expand
Check Numbers Ascending in SentenceInput: "1 box has 3 blue 4 red 6 green and 12 yellow marbles"1boxhas3blue4red6Extract Numbers: [1, 3, 4, 6, 12]1346121 < 33 < 44 < 66 < 12All numbers are strictly increasing → true
Understanding the Visualization
1
Parse Sentence
Split into tokens and identify numbers
2
Check Order
Compare each number with the previous
3
Return Result
True if ascending, false otherwise
Key Takeaway
🎯 Key Insight: Only need to track the last number seen while scanning left to right
Asked in
Amazon 15 Microsoft 8 Google 5
21.8K Views
Medium Frequency
~10 min Avg. Time
750 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