You are given a string s
consisting of lowercase English letters and digits. In this string, there are some words and some numbers, which are separated by a single space. Your task is to determine if the numbers within the string are in ascending order.
Specifically, you should:
s
and extract only the numbers.def are_numbers_ascending(s: str) -> bool:
# Split the string by spaces
tokens = s.split()
# Extract numbers in integer form
numbers = [int(token) for token in tokens if token.isdigit()]
# Check if numbers are in strictly ascending order
return all(earlier < later for earlier, later in zip(numbers, numbers[1:]))
# Example:
print(are_numbers_ascending("1 box has 3 blue 4 red 6 green and 12 yellow marbles")) # True
print(are_numbers_ascending("hello world 5 x 6")) # True
print(are_numbers_ascending("4 5 11 26 are the numbers")) # True
print(are_numbers_ascending("7 is later than 4 but not 3")) # False
The time complexity of this solution is:
n
is the number of tokens (words + numbers) in the string s
, for splitting and iterating over the tokens.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?