Skip to main content

Find Smallest Letter Greater Than Target

Question

Given a list of lowercase letters, find the smallest letter in the list that is larger than a given target letter.

Example 1
Input: letters = ["c", "f", "j"], target = "a"
Output: "c"

Solution

all//Find Smallest Letter Greater Than Target.py


def findSmallestLetterGreaterThanTarget(letters, target):
for letter in letters:
if letter > target:
return letter
return letters[0]

# test
letters = ['a', 'b', 'c', 'd', 'e']
target = 'c'

smallestLetter = findSmallestLetterGreaterThanTarget(letters, target)
print(smallestLetter) # d