Ride-hailing app~25 min2s · 256 MBtarget O(length) time, O(length) spacedp
A ride-hailing app builds a shift pattern for each driver. A pattern is a row of slots, and each slot is 1 for a busy slot or 0 for a rest slot. A safety rule forbids two busy slots side by side.
The app lists every allowed pattern in dictionary order, and the support screen shows one by its position.
Your team lead says: Given the number of slots and a position k, return the pattern at that position. Never build the whole list.
Write kth_code(length, k).
length characters, each 0 or 1, with no two 1 characters side by side.0 comes before 1. The first code is at position 0.k.k smaller than the number of codes.Input: length = 4, k = 5
Output: "1000"The codes of 4 slots are 0000, 0001, 0010, 0100, 0101, 1000, 1001 and 1010. There are 8 of them, so position 5 is 1000.
| Slot | Codes that put 0 here | k | Choice |
|---|---|---|---|
| 1 | 5 | 5 | k is not below 5, so take 1 and set k to 0 |
| 2 | forced | 0 | a 1 must be followed by 0 |
| 3 | 2 | 0 | k is below 2, so take 0 |
| 4 | 1 | 0 | k is below 1, so take 0 |
The code at position 5 is 1000.
Input: length = 5, k = 12
Output: "10101"The codes of 5 slots number 13. The last one, at position 12, is 10101: a busy slot on every other slot.
Input: length = 1, k = 1
Output: "1"With 1 slot the codes are 0 and 1. Position 1 is 1.
1 ≤ length ≤ 600 ≤ k < number of codes, and the number of codes for 60 slots is 4,052,739,537,881With 60 slots there are 1,152,921,504,606,846,976 strings of 0 and 1, and 4,052,739,537,881 of them are codes. Building every code is not possible, and k can be above 2^32, so read it as a 64-bit integer. The count of completions for a pair of values is asked for many times, so a cache keeps the work to 117 entries.