Check if Numbers Are Ascending in a Sentence
Problem
A sentence is a list of tokens separated by single spaces. A token is either a sequence of letters or a positive integer (no leading zeros). Return true if and only if all numeric tokens, read left to right, are strictly increasing.
s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"truedef are_numbers_ascending(s):
prev = -1
for tok in s.split(' '):
if tok.isdigit():
v = int(tok)
if v <= prev:
return False
prev = v
return True
function areNumbersAscending(s) {
let prev = -1;
for (const tok of s.split(' ')) {
if (/^\d+$/.test(tok)) {
const v = parseInt(tok, 10);
if (v <= prev) return false;
prev = v;
}
}
return true;
}
class Solution {
public boolean areNumbersAscending(String s) {
int prev = -1;
for (String tok : s.split(" ")) {
if (Character.isDigit(tok.charAt(0))) {
int v = Integer.parseInt(tok);
if (v <= prev) return false;
prev = v;
}
}
return true;
}
}
bool areNumbersAscending(string s) {
int prev = -1, i = 0, n = s.size();
while (i < n) {
if (isdigit(s[i])) {
int v = 0;
while (i < n && isdigit(s[i])) v = v * 10 + (s[i++] - '0');
if (v <= prev) return false;
prev = v;
} else {
i++;
}
}
return true;
}
Explanation
We only care about the numbers in the sentence and whether they keep getting bigger. The words in between are noise we can ignore.
We split the sentence on spaces to get a list of tokens, then walk through them keeping a variable prev that remembers the last number we saw. It starts at -1 so the very first number always passes.
For each token we check if it is a number with tok.isdigit(). If it is a word, we skip it. If it is a number v, we compare it to prev: if v <= prev the numbers are not strictly increasing, so we return false immediately. Otherwise we update prev = v and keep going.
If we reach the end without finding a violation, every number was strictly larger than the one before it, so we return true.
Example: "1 box has 3 blue 4 red 6 green and 12 yellow marbles". The numbers in order are 1, 3, 4, 6, 12 — each bigger than the last — so the result is true.