Pankaj Tanwar
Published on

# Check if Numbers Are Ascending in a Sentence.

––– views

Problem of the day - Check if Numbers Are Ascending in a Sentence

Tag - Easy

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.

Example 1:

Input: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles" Output: true Explanation: The numbers in s are: 1, 3, 4, 6, 12. They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.

I hate these kind of problems. Ugly challenges, long writeups with pretty simple algorithm.

Ahh, can't help it. Anyway, let's solve it.

So, after splitting the string by space, for each sub string, if it's a valid digit, I need to check with the previous and return false if it's not strictly greater than it else return true.

I know, it's not as simple as it sounds.

Here is my solution

class Solution {public:    bool areNumbersAscending(string s) {        int prev_num = -1;        int curr_sum = 0;        bool is_digit = true;                for(char c: s) {            if(c == ' ') {                if(is_digit) {                    if(curr_sum <= prev_num) return false;                    prev_num = curr_sum;                    curr_sum = 0;                }                is_digit = true;            } else {                if(is_digit && (c - '0' >= 0 && c - '0' <= 9)) {                    curr_sum = curr_sum * 10 + (c - '0');                } else {                    is_digit = false;                }            }        }        if(is_digit && curr_sum <= prev_num) return false;        return true;    }};

Umm, not-so-good problem. See you guys tomorrow!

I welcome your suggestions to improve it further!

Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.

You might like previous editions of my coding diary