Find Smallest Letter Greater Than Target

  • For example, if target == 'z' and letters == ['a', 'b'], the answer is 'a'.
Input: letters = ["c","f","j"], target = "a"
Output: "c"
Input: letters = ["c","f","j"], target = "c"
Output: "f"
Input: letters = ["c","f","j"], target = "d"
Output: "f"
Input: letters = ["c","f","j"], target = "g"
Output: "j"
Input: letters = ["c","f","j"], target = "j"
Output: "c"

for i in letters:
if(i>target):
found i
break the loop

if not found
found letters[0]
 low=0
high=len(letters)-1
res=letters[0]
while(low<=high):
mid=(low+high)//2
if(ord(letters[mid])<=ord(target)):
low=mid+1
elif(ord(letters[mid])>ord(target)):
res=letters[mid]
high=mid-1
print res

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.