Chat app~15 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-744binary-search
A chat app lets you jump between pinned channels with a one-letter shortcut. The shortcuts are kept in alphabetical order, and two channels can share a letter.
Pressing a key jumps to the first channel whose letter comes strictly after the key. If no letter comes after it, the list wraps around to its first letter.
Write next_letters(letters, keys).
letters is the sorted list of channel letters, as a string.keys, find the smallest letter in letters that is strictly greater than the key. If there is none, the answer is the first letter of letters.keys.Input: letters = "acfjjk", keys = "afkzb"
Output: "cjaac"Take the key f. The window [lo, hi) starts as [0, 6) and looks for the first letter that is greater than f.
| Step | lo | hi | mid | letters[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | j | j is after f, so hi = 3 |
| 2 | 0 | 3 | 1 | c | c is not after f, so lo = 2 |
| 3 | 2 | 3 | 2 | f | f is not after f, so lo = 3 |
| end | 3 | 3 | letters[3] is j |
The key a gets c, and the key b gets c. The key k has no letter after it, so it wraps to a. The key z wraps to a too. The answer is cjaac.
Input: letters = "m", keys = "lmn"
Output: "mmm"With one letter, every key either finds it after the key (l) or wraps to it (m and n).
Input: letters = "az", keys = "zay"
Output: "azz"The key z has nothing after it, so it wraps to a. The key a finds z. The key y finds z.
1 ≤ letters.length ≤ 100,000, only lower-case letters a to z, sorted in alphabetical order, repeats allowed0 ≤ keys.length ≤ 100,000, only lower-case letters a to zScanning the letters from the front for every key costs about n × q steps, which is 10^10 when both are 100,000. The letters are sorted, so a binary search finds the first letter after a key in about 17 steps. Only 26 different letters exist, but the list can repeat each letter thousands of times.