Python 2042.py
class Solution:
def areNumbersAscending(self, s: str) -> bool:
nums = [ int(w) for w in s.split(" ") if w.isnumeric() ]
return all(nums[i] > nums[i - 1] for i in range(1, len(nums)))
Difficulty
and has an acceptance rate of about 74% (100k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method areNumbersAscending. The method receives a string that may contain words and numeric tokens separated by spaces. Its purpose is to determine whether the numeric tokens, when extracted in order of appearance, form a strictly increasing sequence. The result is a Boolean value indicating the outcome.
Key Steps
Parsing the Input
nums = [int(w) for w in s.split(" ") if w.isnumeric()]
The method first splits the input string on space characters, producing a list of substrings. A list comprehension filters this list, retaining only those substrings that consist solely of decimal digits (w.isnumeric()). Each retained substring is converted to an integer with int(w). The resulting list nums contains all numeric values in the order they appeared in the original string.
Verifying Strictly Increasing Order
return all(nums[i] > nums[i - 1] for i in range(1, len(nums)))
The second step evaluates whether each element in nums is greater than its immediate predecessor. A generator expression iterates over the index range starting from 1 up to the length of nums. For each index i, it yields the Boolean expression nums[i] > nums[i - 1]. The built-in all function consumes this generator and returns True only if every comparison evaluates to True; otherwise it returns False. If nums contains zero or one element, the generator produces no items, and all consequently returns True, reflecting the vacuous truth of an empty or singleton sequence being strictly increasing.
Edge Cases Handled
When the input string contains no numeric tokens, the list comprehension yields an empty list. The subsequent all call receives an empty generator, which by definition returns True. This correctly treats the absence of numbers as satisfying the ascending condition.
If the string includes a single numeric token, the range for the generator expression is empty, leading again to an immediate True result, which aligns with the expectation that a solitary number cannot violate a strict ordering constraint.
The use of str.isnumeric() ensures that tokens containing any non-digit characters, such as alphabetic letters, punctuation, or mixed alphanumeric strings, are excluded from nums. Consequently, the method gracefully ignores non-numeric words without raising errors.
Leading zeros in numeric tokens are accepted because int(w) parses them as the corresponding integer value, and the comparison logic operates on these integer representations, making the presence of leading zeros irrelevant to the ordering check.
Performance Optimizations
The implementation leverages a list comprehension for the extraction and conversion of numeric tokens, which is executed in a single pass over the split substrings. This avoids multiple traversals of the input data.
The ordering verification employs a generator expression inside all. This design enables short-circuit evaluation: as soon as a pair of adjacent numbers fails the > test, the generator stops producing further values and all returns False immediately. This prevents unnecessary comparisons once a violation is detected.
By converting tokens to integers only once during the list comprehension, the code avoids repeated parsing during the comparison phase, reducing overhead.
Overall, the combination of a single pass for token extraction and a short-circuiting comparison loop yields an efficient solution for the problem at hand.
ELI5 - Simplified Explanation
Imagine a long piece of paper with a sentence written on it. The sentence has both letters and secret numbers hidden inside. The first part of this code looks through the sentence, picks out all those hidden numbers one by one, and puts them into a little basket. Once all the numbers are safely in the basket, the code looks at them from left to right. It checks to see if each number is bigger than the one that came just before it. If every number is bigger than the last one, it confirms that the numbers are climbing up like stairs. If any number is the same or smaller than the one before it, the climbing rule is broken.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | C | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1859: Sorting the Sentence
- problem 2124: Check if All A's Appears Before All B's
Solved On The Same Day
- problem 1779: Find Nearest Point That Has the Same X or Y Coordinate
- problem 1991: Find the Middle Index in Array
- problem 2062: Count Vowel Substrings of a String
- problem 1780: Check if Number is a Sum of Powers of Three
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality