Talentd
FleetCode
Make and follow sheets.Sign in

Check if Numbers Are Ascending in a Sentence solution and explanation

EasyString6 min read73.6% acceptanceUpdated 9 Apr 2026
2042. Check if Numbers Are Ascending in a Sentence (Leetcode Easy)Programming Live with Larry · 4:41 · 647 viewsWatch on YouTube
9 more videos on this problem
  1. 2042. Check if Numbers Are Ascending in a Sentence (Leetcode Easy)Programming Live with Larry · 4:41 · 647 views
  2. 2042. Check if Numbers Are Ascending in a Sentence | LEETCODE EASYcode Explainer · 9:22 · 634 views
  3. Leetcode 2042 Check if Numbers Are Ascending in a Sentence Java Clean Solution ExplainedAlgorithmicIQ · 6:01 · 626 views
  4. Leetcode Solution - 2042 Check if Numbers Are Ascending in a SentenceJohn Leonardo · 5:38 · 493 views
  5. Check if Numbers Are Ascending in a Sentence || WC 263 || O(1) SpaceAyush Yadav · 15:33 · 447 views
  6. 2042. Check if Numbers Are Ascending in a Sentence with Python | Leetcode with Python #youtubeArsalan Ahmed · 7:53 · 171 views
  7. 2042. Check if Numbers Are Ascending in a Sentence #java #javainterviewquestions #leetcodeBuild Lead and Innovate · 1:29 · 152 views
  8. leetcode 2042  Check if Numbers Are Ascending in a SentenceMath Geeks · 2:21 · 118 views
  9. Day 667: LeetCode Problem 2042. Check if Numbers Are Ascending in a Sentence - SwiftiOSxBank · 8:53 · 29 views
  10. 2042. Check if Numbers Are Ascending in a Sentence - Javascript - Time: O(n) Space: O(n) - LeetcodeAaron Sadino Coding · 42:59 · 27 views

The 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.

Example 1:

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.

Example 2:

Input: s = "hello world 5 x 5"
Output: false
Explanation: The numbers in s are: 5, 5. They are not strictly increasing.

Example 3:

example-3
Input: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"
Output: false
Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.

Constraints:

  • 3 <= s.length <= 200
  • s consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive.
  • The number of tokens in s is between 2 and 100, inclusive.
  • The tokens in s are separated by a single space.
  • There are at least two numbers in s.
  • Each number in s is a positive number less than 100, with no leading zeros.
  • s contains no leading or trailing spaces.

Approach overview

Problem Overview: Given a sentence containing words and integers separated by spaces, verify that every number appears in strictly increasing order from left to right. You only compare the numbers that appear in the sentence while ignoring the words.

Approach 1: Simple Iteration with Integer Conversion (O(n) time, O(1) space)

Scan the sentence token by token and extract numbers as you encounter them. Split the string by spaces, then check each token using isdigit() (or equivalent). Convert numeric tokens to integers and compare them with the previous number seen. If the current number is less than or equal to the previous one, the sequence is not strictly increasing and you return false. This approach performs a single pass through the sentence, making it the most straightforward solution for string parsing problems.

The key insight is that you do not need to store all numbers. Track only the last seen number and compare as you iterate. Each token check and conversion happens once, giving linear time complexity O(n) where n is the length of the sentence, and constant extra space O(1). This method works in every language and is typically the first implementation developers write during interviews.

Approach 2: Regular Expression Filtering (O(n) time, O(k) space)

Instead of checking every token manually, use a regular expression to extract only the numeric substrings. A pattern like \d+ captures all integer values in the sentence. After collecting these matches, convert them to integers and iterate through the list to verify that each number is strictly larger than the previous one.

This approach separates extraction and validation. The regex engine scans the entire string once to produce k numbers, then a second pass verifies ordering. Time complexity remains O(n), but space becomes O(k) because all extracted numbers are stored before comparison. Regex-based parsing is common in problems involving regular expressions and structured string processing.

Recommended for interviews: The simple iteration approach is what interviewers usually expect. It demonstrates that you can parse a sentence, detect numeric tokens, and maintain a running comparison in a single pass. The regex approach is concise and readable but relies on library utilities, while the iteration method shows stronger understanding of basic string processing and space optimization.

Approach 1: Simple Iteration with Integer Conversion

In this approach, the goal is to parse through the sentence to extract the numbers, convert them to integers, and check if they are in strictly increasing order. This is achieved by splitting the input string into tokens and identifying the numerical tokens based on we can convert them to integers. Then we iterate over these integers and ensure each is greater than its predecessor.

def are_numbers_ascending(s: str) -> bool:
    prev = -1
    for token in s.split():
        if token.isdigit():
            num = int(token)
            if num <= prev:
                return False
            prev = num
    return True

s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"
print(are_numbers_ascending(s))
public class Solution {
    public static boolean areNumbersAscending(String s) {
        String[] tokens = s.split(" ");
        int prev = -1;
        for (String token : tokens) {
            if (Character.isDigit(token.charAt(0))) {
                int num = Integer.parseInt(token);
                if (num <= prev) {
                    return false;
                }
                prev = num;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles";
        System.out.println(areNumbersAscending(s));
    }
}
#include <iostream>
#include <sstream>
#include <string>

bool areNumbersStrictlyIncreasing(const std::string& s) {
    std::istringstream stream(s);
    std::string token;
    int prev = -1;
    while (stream >> token) {
        if (isdigit(token[0])) {
            int num = std::stoi(token);
            if (num <= prev) {
                return false;
            }
            prev = num;
        }
    }
    return true;
}

int main() {
    std::string s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles";
    std::cout << areNumbersStrictlyIncreasing(s) << std::endl;
    return 0;
}
function areNumbersAscending(s) {
    let tokens = s.split(' ');
    let prev = -1;
    for (let token of tokens) {
        if (!isNaN(token)) {
            let num = parseInt(token);
            if (num <= prev) {
                return false;
            }
            prev = num;
        }
    }
    return true;
}

let s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles";
console.log(areNumbersAscending(s));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int areNumbersAscending(char* s) {
    int prev = -1;
    char* token = strtok(s, " ");
    while (token) {
        if (isdigit(token[0])) {
            int num = atoi(token);
            if (num <= prev) {
                return 0;
            }
            prev = num;
        }
        token = strtok(NULL, " ");
    }
    return 1;
}

int main() {
    char s[] = "1 box has 3 blue 4 red 6 green and 12 yellow marbles";
    printf("%d\n", areNumbersAscending(s));
    return 0;
}
using System;

public class Solution {
    public bool AreNumbersAscending(string s) {
        var parts = s.Split(' ');
        int prev = -1;
        foreach (var part in parts) {
            if (char.IsDigit(part[0])) {
                int num = int.Parse(part);
                if (num <= prev) {
                    return false;
                }
                prev = num;
            }
        }
        return true;
    }

    public static void Main(string[] args) {
        string s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles";
        Solution sol = new Solution();
        Console.WriteLine(sol.AreNumbersAscending(s));
    }
}

This Python function splits the input string into parts using the split method. With isdigit, it identifies numerical tokens, converts them to integers, and ensures that each number is greater than the last one seen, maintaining a strictly increasing order.

Complexity

Time Complexity: O(n), where n is the number of characters in the string.
Space Complexity: O(1), since space does not scale with input size.

Try this approach in the editor

Approach 2: Regular Expression Filtering

This approach uses regular expressions to directly extract numbers from the input string. This method isolates the process of filtering out numbers, allowing the rest of the logic to focus on verifying the numbers are in strictly increasing order by comparing each to the previous number registered.

import re

def are_numbers_ascending(s: str) -> bool:
    numbers = list(map(int, re.findall(r'\b\d+\b', s)))
    return all(earlier < later for earlier, later in zip(numbers, numbers[1:]))

s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"
print(are_numbers_ascending(s))
#include <iostream>
#include <regex>

bool areNumbersAscending(const std::string& s) {
    std::regex number_regex("\\b\\d+\\b");
    auto numbers_begin = std::sregex_iterator(s.begin(), s.end(), number_regex);
    auto numbers_end = std::sregex_iterator();

    int prev = -1;
    for (std::sregex_iterator i = numbers_begin; i != numbers_end; ++i) {
        int num = std::stoi(i->str());
        if (num <= prev) {
            return false;
        }
        prev = num;
    }
    return true;
}

int main() {
    std::string s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles";
    std::cout << areNumbersAscending(s) << std::endl;
    return 0;
}

This Python solution leverages the re module to find all number sequences in the string. The expression `\b\d+\b` is used to match complete numbers. The numbers are converted to integers and validated to be in increasing order through a parallel iteration using `zip`.

Complexity

Time Complexity: O(n), where n is the length of the string because regex searches through the string a single time.
Space Complexity: O(m), where m is the number of numeric tokens extracted.

Try this approach in the editor

Approach 3: Simulation

We can split the string s into several words by spaces. Then, for each word, check if it is a number. If it is a number, convert it to an integer, compare it with the previous number. If it is not strictly increasing, return false. Otherwise, assign the current number to the previous number and continue the traversal.

If the traversal ends, it means that the numbers in the string are strictly increasing, so return true.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the string s.

function areNumbersAscending(s: string): boolean {
    let pre = -1;
    for (const cur of s.split(' ')) {
        if (cur[0] <= '9') {
            const num = Number(cur);
            if (num <= pre) {
                return false;
            }
            pre = num;
        }
    }
    return true;
}
func areNumbersAscending(s string) bool {
	pre := 0
	for _, t := range strings.Split(s, " ") {
		if t[0] <= '9' {
			cur, _ := strconv.Atoi(t)
			if pre >= cur {
				return false
			}
			pre = cur
		}
	}
	return true
}
impl Solution {
    pub fn are_numbers_ascending(s: String) -> bool {
        let mut pre = -1;
        for cur in s.split(' ') {
            if cur.as_bytes()[0] <= b'9' {
                let num = cur.parse::<i32>().unwrap();
                if num <= pre {
                    return false;
                }
                pre = num;
            }
        }
        true
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Simple Iteration with Integer Conversion

Time Complexity: O(n), where n is the number of characters in the string.
Space Complexity: O(1), since space does not scale with input size.

Regular Expression Filtering

Time Complexity: O(n), where n is the length of the string because regex searches through the string a single time.
Space Complexity: O(m), where m is the number of numeric tokens extracted.

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Simple Iteration with Integer ConversionO(n)O(1)Best general solution. One pass through the sentence with minimal memory.
Regular Expression FilteringO(n)O(k)Useful when regex utilities are available and extracting numbers is easier than manual parsing.

Frequently asked questions

Is Check if Numbers Are Ascending in a Sentence easy or hard?

Check if Numbers Are Ascending in a Sentence is classified as an Easy problem. It focuses on basic string processing, integer parsing, and maintaining a running comparison, making it a common warm-up problem in coding interviews.

Check if Numbers Are Ascending in a Sentence Python/Java solution

In Python or Java, split the sentence into tokens and check each token to see if it is numeric. Convert numeric tokens using int parsing and maintain a previous value variable. If the current value is less than or equal to the previous one, return false; otherwise continue until the sentence ends.

How to solve Check if Numbers Are Ascending in a Sentence in O(n)?

Traverse the sentence once and process tokens separated by spaces. Whenever a token represents a number, convert it to an integer and compare it with the previous numeric value. If the current number is not strictly greater, return false immediately. Finishing the scan without violations confirms the numbers are strictly increasing.

What is the best approach for Check if Numbers Are Ascending in a Sentence?

The best approach is a single-pass iteration through the sentence. Split the string by spaces, detect numeric tokens, convert them to integers, and compare each with the previous number. This runs in O(n) time and O(1) space because you only track the last number seen.

Is Check if Numbers Are Ascending in a Sentence asked at Google/Amazon/Meta?

Problems like this appear in screening rounds at large companies because they test basic string parsing and logical validation. Variations involving token parsing or number extraction from strings have been reported in interviews at companies such as Amazon and Google.

What data structure is used in Check if Numbers Are Ascending in a Sentence?

The optimal solution does not require complex data structures. A single integer variable stores the previously seen number while scanning the string. If using the regex approach, a temporary list or array stores the extracted numbers before validation.

What is the time complexity of Check if Numbers Are Ascending in a Sentence?

The optimal solution runs in O(n) time where n is the length of the sentence. Each token or character is processed once to identify numbers and compare them with the previously seen value. Space complexity can be O(1) with streaming comparison or O(k) if you store all extracted numbers.

Comments

Now write it yourselfClose this page and solve Check if Numbers Are Ascending in a Sentence in the editor, without looking.
Practise Check if Numbers Are Ascending in a Sentence