Online store~12 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-35binary-search
An online store's support team keeps ticket rows in a list sorted by ticket id, smallest first. When a customer reopens a ticket, the ticket gets another row with the same id, so an id can appear more than once.
A new row goes in front of the rows that already have its id. If no row has its id, it goes where the ids stay in order.
Before a batch of new rows is inserted, the team wants the position of each one. Each position is worked out against the list as it is now.
Write insertion_points(ids, new_ids).
ids is the sorted list of ticket ids. It can hold repeats. Positions count from 0.x in new_ids, find the position where a row for x would go: the number of ids in ids that are smaller than x.len(ids) means the end of the list.Input: ids = [3, 5, 5, 8, 12, 12, 12, 20], new_ids = [5, 6, 1, 25, 12]
Output: [1, 3, 0, 8, 4]Take the new id 12. The window [lo, hi) holds the positions that might be the answer.
| Step | lo | hi | mid | ids[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 12 | 12 is not below 12, so hi = 4 |
| 2 | 0 | 4 | 2 | 5 | 5 < 12, so lo = 3 |
| 3 | 3 | 4 | 3 | 8 | 8 < 12, so lo = 4 |
| end | 4 | 4 | position 4 |
The id 5 goes to position 1, in front of the two rows that have 5. The id 6 goes to position 3, in front of 8. The id 1 goes to the start, and 25 goes to the end.
Input: ids = [], new_ids = [7, 7]
Output: [0, 0]An empty list has only one position, the start.
Input: ids = [4, 4, 4, 4], new_ids = [3, 4, 5]
Output: [0, 0, 4]A smaller id goes to the start. The id 4 goes in front of all four rows that have it. A larger id goes to the end.
0 ≤ ids.length ≤ 100,000, and ids is sorted from smallest to largest0 ≤ ids[i] ≤ 1,000,000,0000 ≤ new_ids.length ≤ 100,0000 ≤ new_ids[j] ≤ 1,000,000,000Counting the smaller ids for each new id costs up to 10^5 steps, and there can be 10^5 new ids, so about 10^10 steps in all. The list is sorted, so "this id is at least the new id" is false for a while and then true for ever. A binary search needs about 17 checks.