Suppose we have a list of sorted characters’ letters. This is containing only lowercase letters, now we have a target letter t, we have to find the smallest element in the list that is larger than the given target.
And letters also wrap around. So, if the target is t = 'z' and letters = ['a', 'b'], the answer is 'a'.
So, if the input is like ["c", "f", "j"], t = 'a', then the output will be 'c'.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def nextGreatestLetter(self, letters, target): l = 0 r = len(letters) - 1 while l <= r: mid = (l + r)//2 if letters[mid] > target: r = mid -1 else: l = mid + 1 return letters[l % len(letters)] ob = Solution() print(ob.nextGreatestLetter(["c", "f", "j"], "a"))
["c", "f", "j"], "a"