# Find Smallest Letter Greater Than Target in Python

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 −

• l := 0
• r := size of letters - 1
• while l <= r, do
• mid :=(l + r) / 2 as integer
• if letters[mid] > target, then
• r := mid -1
• otherwise,
• l := mid + 1
• return letters[l mod size of letters]

Let us see the following implementation to get better understanding −

## Example

Live Demo

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"))

## Input

["c", "f", "j"], "a"

## Output

c