Solution 1
- TimeO(log n)
- SpaceO(1)
where, n is the length of letters
Solved in 13 min 24 secs, all by yourself! Good Job!
Python · 2026-01-31
class Solution:
'''
Time Complexity: O(log n)
Space Complexity: O(1)
where, n is the length of letters
Solved in 13 min 24 secs, all by yourself! Good Job!
'''
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
l, r = 0, len(letters)-1
while l < r:
m = (l+r)//2
if letters[m] <= target:
l = m+1
else:
r = m
if letters[l] <= target and l == len(letters)-1:
return letters[0]
return letters[l]Solution 2
- TimeO(log n)
- SpaceO(1)
where, n is the length of letters
Cleaner code!
Python · 2026-01-31
from bisect import bisect
class Solution:
'''
Time Complexity: O(log n)
Space Complexity: O(1)
where, n is the length of letters
Cleaner code!
'''
def nextGreatestLetter(self, letters: List[str], target: str) -> str:
i = bisect(letters, target)
if i == len(letters):
return letters[0]
return letters[i]