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 if Numbers Are Ascending INPUT Sentence tokens: 1 box has 3 blue 4 red 6 green and 12 yellow marbles = Number = Word Numbers Found: 1 3 4 6 12 1 < 3 3 < 4 4 < 6 6 < 12 Task: Check if all numbers are strictly increasing s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" ALGORITHM STEPS 1 Initialize prev = 0 (track last number) 2 Split & Iterate Split sentence by spaces Loop through each token 3 Check Token If token is a number: - Parse to integer - Compare with prev 4 Validate If current <= prev: Return false Else: prev = current Comparisons: prev=0: 1>0 [OK] prev=1 prev=1: 3>1 [OK] prev=3 prev=3: 4>3 [OK] ... FINAL RESULT All comparisons passed: OK 1 < 3 OK 3 < 4 OK 4 < 6 OK 6 < 12 Number Sequence: 1 < 3 < 4 < 6 < 12 Output: true Strictly Ascending! All numbers in order: 1 --> 3 --> 4 --> 6 --> 12 Key Insight: Use a single pass with O(n) time complexity. Track the previous number and compare each new number found. Skip non-numeric tokens. If any number is not strictly greater than the previous, return false immediately. TutorialsPoint - Check if Numbers Are Ascending in a Sentence | Single Pass with Comparison
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