Ride-hailing app~25 min2s · 256 MBtarget O(q × log V) time, O(q) spaceclassic twin: lc-201bit-manipulation
A ride-hailing app gives each vehicle a numeric id. The bits of an id are flags: an electric drivetrain, a child seat, a wheelchair ramp, and so on. Ids are handed out in order, so a block of consecutive ids is a batch of vehicles added together.
An analyst asks which flags every vehicle in a block has. That is the bitwise AND of all the ids in the block. The fleet has up to a billion ids, and there are many questions.
Write shared_flags(los, his).
i is the block of ids from los[i] to his[i], both included, with los[i] <= his[i].Input: los = [5, 12, 9], his = [7, 15, 9]
Output: [4, 12, 9]Take the first block, 5 to 7. Drop the lowest bit of both ends until they are equal, and count the drops.
| Step | lo |
hi |
Drops |
|---|---|---|---|
| Start | 5 (101) | 7 (111) | 0 |
| [2] | 2 (10) | 3 (11) | 1 |
| [2] | 1 (1) | 1 (1) | 2 |
| [3] | 1 << 2 = 4 |
The ids 5, 6 and 7 are 101, 110 and 111, and their AND is 100, which is 4. The other blocks give 12 and 9 in the same way.
Input: los = [96], his = [100]
Output: [96]The ids 96 to 100 share the long prefix 11000 of their binary form, so the answer is 96.
Input: los = [7], his = [8]
Output: [0]The ids 7 and 8 are 0111 and 1000. They have no bit in common.
1 ≤ len(los) = len(his) ≤ 100,0000 ≤ los[i] ≤ his[i] ≤ 10^9One block can hold a billion ids, so taking the AND of every id one by one costs up to a billion steps for one question. With 100,000 questions that is out of the question.
An id below 10^9 has at most 30 bits, so any method that costs about one step per bit finishes in a few dozen steps per question.