You get a list of lower-case letters, letters, sorted from a to z (the same letter may repeat), and one letter, target. The list holds at least two different letters.
Return the smallest letter in the list that comes strictly after target in the alphabet. If no letter in the list comes after it, wrap around and return the first letter of the list.
Example 1
Input: letters = ["b", "e", "k", "p"], target = "e" Output: "k" Why: 'e' itself does not count; 'k' is the next one
2 more examples and the constraints
Example 2
Input: letters = ["d", "d", "g", "m"], target = "a" Output: "d" Why: every letter comes after 'a'; 'd' is the smallest
Example 3
Input: letters = ["h", "h", "r"], target = "t" Output: "h" Why: nothing comes after 't', so wrap to the first letter
Constraints
- 2 ≤ length of letters ≤ 10,000
- Every letter, and target, is a lower-case English letter
- letters is sorted and holds at least two different letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Linear scanO(n)
- Binary searchO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 letters | Verdict |
|---|---|---|---|
| Linear scan | O(n) | Fine, but ignores the order | |
| Binary search | O(log n) | Best; about 14 reads |
n = number of letters.
Edge cases to test
- Target is in the list. Equal is not greater: ["b", "e", "k", "p"] with 'e' gives 'k', not 'e'.
- Target after every letter. ["h", "h", "r"] with 't' wraps to 'h'.
- Target equals the last letter. ["a", "c"] with 'c' also wraps, to 'a'.
- Repeated letters. ["c", "c", "c", "f"] with 'c' must skip all three c's and give 'f'.
- Target before every letter. ["d", "d", "g", "m"] with 'a' gives 'd'.
Common mistakes
- Using
>=instead of>, which returns the target itself when it is in the list. - Forgetting the wrap, so the search returns an index one past the end.
- Starting
hiat the last index, which leaves no way to say "no letter is greater".
How to talk through it
- 1Clarify. Strictly greater or greater-or-equal? What happens when nothing is greater? Can letters repeat?
- 2Give the scan. The list is sorted, so the first greater letter is the answer: O(n).
- 3Use the order. The letters split into 'at most target' then 'greater'. Binary search finds the split.
- 4Code the upper bound. Half-open range [lo, hi), hi = mid when mid is greater, then return letters[lo % n].
- 5Test out loud. Run the target-in-list case and the wrap case before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?