↓Skip to main content
  1. LeetCode/

LeetCode 744: Find Smallest Letter Greater Than Target

·1 min· ·
LeetCode Easy Array Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-03

  • Submissions: Wrong Answer ×2 → Runtime Error ×2 → Wrong Answer ×5 → Accepted ×2 → Wrong Answer → Time Limit Exceeded ×2 → Accepted

Approach
#

Find the first letter strictly greater than target in the sorted list, the upper bound (Binary Search Template 1), via bisect_right. If every letter is <= target, wrap around to the first, handled with % len.

My Attempts
#

This took 15 submissions. I first handled wrap-around with ord plus 26: add 26 to letters below target and take the minimum, but returned a number (123) or forgot to subtract 26 after chr ('{'), e.g. ['a', 'h'], target = 'j' should be 'a'. After switching to binary search, two versions stopped shrinking the interval (TLE).

Solution
#

class Solution:
    def nextGreatestLetter(self, letters: List[str], target: str) -> str:
        return letters[bisect.bisect_right(letters, target) % len(letters)]

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • Strictly greater, so letters equal to target do not count: bisect_right.
  • Return the letter, not its ord value.

Interview Explanation
#

bisect_right gives the position of the first letter strictly greater than the target, and a modulo wraps around past the end. Time O(log n).

Related

LeetCode 704: Binary Search
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 704 note: a closed interval [l, r] with an integer mid; return on a match, otherwise discard the half that cannot contain the target
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 733: Flood Fill
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 733 note: DFS or BFS from the start, recoloring 4-directional cells that share the start’s original color; return immediately if the colors are equal