|
| 1 | +# [Problem 744: Find Smallest Letter Greater Than Target](https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +The array is sorted and we need the smallest letter strictly greater than target. Sounds like binary search for the first element > target. Because letters wrap around (if none greater, return letters[0]), we should handle that by returning the first element when the binary search reaches the end. A linear scan would work but is O(n); binary search gives O(log n). Need to be careful about duplicates (many equal letters) — we want strictly greater so when letters[mid] <= target move right. |
| 5 | + |
| 6 | +## Refining the problem, round 2 thoughts |
| 7 | +- Use binary search to find the first index where letters[idx] > target. |
| 8 | +- Typical pattern: lo = 0, hi = n (notice hi = n allows us to detect "not found" when lo == n), while lo < hi: mid = (lo + hi)//2; if letters[mid] > target: hi = mid else lo = mid + 1. After loop, if lo == n then wrap to letters[0], else letters[lo]. |
| 9 | +- Alternatively, Python's bisect module (bisect_right) could be used: idx = bisect_right(letters, target); return letters[idx % n]. |
| 10 | +- Time complexity O(log n), space O(1). |
| 11 | +- Edge cases: all letters <= target (wrap), duplicates of letters equal to target. |
| 12 | + |
| 13 | +## Attempted solution(s) |
| 14 | +```python |
| 15 | +from typing import List |
| 16 | + |
| 17 | +class Solution: |
| 18 | + def nextGreatestLetter(self, letters: List[str], target: str) -> str: |
| 19 | + n = len(letters) |
| 20 | + lo, hi = 0, n # hi is n to allow detecting wrap-around when lo == n |
| 21 | + while lo < hi: |
| 22 | + mid = (lo + hi) // 2 |
| 23 | + if letters[mid] > target: |
| 24 | + hi = mid |
| 25 | + else: |
| 26 | + lo = mid + 1 |
| 27 | + # if lo == n, no letter > target found -> wrap to first element |
| 28 | + return letters[lo] if lo < n else letters[0] |
| 29 | +``` |
| 30 | +- Notes: |
| 31 | + - Approach: binary search for the first index with letters[idx] > target. |
| 32 | + - Time complexity: O(log n) where n = len(letters). |
| 33 | + - Space complexity: O(1). |
| 34 | + - Implementation detail: using hi = n and returning letters[0] when lo == n handles the wrap-around requirement. |
0 commit comments