Skip to content

744. Find Smallest Letter Greater Than Target

744. Find Smallest Letter Greater Than Target

Companies: LinkedIn
Date: September 7, 2021
Difficulty: Easy
LeetCode link: https://leetcode.com/problems/find-smallest-letter-greater-than-target/
Review Date: October 3, 2021
Status: Done
Tags: Binary Search

class Solution:
    def nextGreatestLetter(self, letters: List[str], target: str) -> str:
        # working simple solution

        # for letter in letters:
        #     if letter > target:
        #         return letter
        # return letters[0]


        # elegant solution
        indexToInsertToKeepLettersSorted = bisect.bisect(letters, target)

        # if asked to insert at the last position,
        # we should return the first char in letters as it is cyclically next
        # if indexToInsertToKeepLettersSorted >= len(letters):
        #     return letters[0]
        # else:
        #     return letters[indexToInsertToKeepLettersSorted]

        # trick to do the if-else logic above in one math operation
        return letters[indexToInsertToKeepLettersSorted % len(letters)]

The bisect.bisect() algorithm is here. Make sure you know this as interviewer might ask to not use the STL.

cpython/bisect.py at 3.9 · python/cpython


Last update : 25 mai 2024
Created : 25 mai 2024