LeetCode 2042: Check if Numbers Are Ascending in a Sentence Solution

Master LeetCode problem 2042 (Check if Numbers Are Ascending in a Sentence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2042. Check if Numbers Are Ascending in a Sentence

Easy

Problem Explanation

Explanation:

To solve this problem, we need to iterate through each word in the sentence, check if it is a number, and then compare it with the previous number if there was one. If the numbers are not strictly increasing, we return false. Otherwise, we return true at the end.

  • We split the input sentence into tokens.
  • We iterate through each token:
    • If the token is a number and not the first number encountered, we compare it with the previous number.
    • If the numbers are not strictly increasing, we return false.
  • If we finish iterating through all tokens without finding any issues, we return true.

Time Complexity: O(N) where N is the length of the input string s. Space Complexity: O(1)

:

Solution Code

class Solution {
    public boolean areNumbersAscending(String s) {
        String[] tokens = s.split(" ");
        int prevNum = -1;

        for (String token : tokens) {
            if (token.matches("\\d+")) {
                int num = Integer.parseInt(token);
                if (num <= prevNum) {
                    return false;
                }
                prevNum = num;
            }
        }

        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2042 (Check if Numbers Are Ascending in a Sentence)?

This page provides optimized solutions for LeetCode problem 2042 (Check if Numbers Are Ascending in a Sentence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2042 (Check if Numbers Are Ascending in a Sentence)?

The time complexity for LeetCode 2042 (Check if Numbers Are Ascending in a Sentence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2042 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2042 in Java, C++, or Python.

Back to LeetCode Solutions