Given a string s consisting of only the characters ‘a’ and ‘b’, return True if every ‘a’ in s appears before every ‘b’. Otherwise, return False.
s?Assuming:
s contains only ‘a’ and ‘b’.s.length ≤ 10⁵).To check if all ‘a’s appear before all ‘b’s, we can use a simple scan of the string:
False.True if the condition is satisfied.def checkString(s: str) -> bool:
# Flag to indicate if a 'b' has been seen
b_seen = False
for char in s:
if char == 'b':
b_seen = True
elif char == 'a' and b_seen:
# If 'a' is found after 'b'
return False
return True
The time complexity of this solution is O(n), where n is the length of the string s. The string is traversed exactly once, making this approach efficient even for larger strings.
b_seen to False.b_seen to True.b_seen is True, return False immediately because an ‘a’ has appeared after a ‘b’.True.This solution ensures that the condition of all ‘a’s appearing before ‘b’s is checked efficiently.
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?