Search~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-80, lc-26read-write-pointers · two-pointers
A search engine keeps a posting list for every term: the ids of the documents that contain the term, sorted from smallest to largest. One document may appear several times in a row, once for each field where the term was found, such as the title or the body.
The index allows up to m copies of each id, one per indexed field. A merge bug repeated some ids far more often than that. The repair job must trim each list in place, keeping the first m copies of every id and dropping the rest, without changing the order.
Write trim_postings(ids, m).
ids is a posting list of document ids, sorted in non-decreasing order. Equal ids sit next to each other.m is the largest number of copies of one id the list may keep.m times, in the same order. Keep the first m copies of an id and drop the later ones.m times, return the list unchanged. m may be larger than the list itself.ids in place with O(1) extra memory, then return the kept prefix. The judge checks only the list you return.Input: ids = [12, 12, 12, 30, 30, 41, 41, 41], m = 2
Output: [12, 12, 30, 30, 41, 41]| read | ids[read] | Check against the kept prefix | Kept? | write after | Kept prefix |
|---|---|---|---|---|---|
| 0 | 12 | write = 0 is less than 2 | yes | 1 | 12 |
| 1 | 12 | write = 1 is less than 2 | yes | 2 | 12, 12 |
| 2 | 12 | ids[0] = 12, the same id | no | 2 | 12, 12 |
| 3 | 30 | ids[0] = 12, a different id | yes | 3 | 12, 12, 30 |
| 4 | 30 | ids[1] = 12, a different id | yes | 4 | 12, 12, 30, 30 |
| 5 | 41 | ids[2] = 30, a different id | yes | 5 | 12, 12, 30, 30, 41 |
| 6 | 41 | ids[3] = 30, a different id | yes | 6 | 12, 12, 30, 30, 41, 41 |
| 7 | 41 | ids[4] = 41, the same id | no | 6 | 12, 12, 30, 30, 41, 41 |
The check looks m places back from write, inside the kept prefix. If that slot holds the same id, m copies of it are already kept.
Input: ids = [5, 5, 6, 8, 8, 8], m = 1
Output: [5, 6, 8]With m = 1, each id is kept once.
Input: ids = [2, 2, 7], m = 3
Output: [2, 2, 7]No id appears more than 3 times, so nothing is removed.
1 ≤ ids.length ≤ 10^51 ≤ ids[i] ≤ 10^9, and ids[i] ≤ ids[i + 1] for every i1 ≤ m ≤ 10^5Deleting each extra copy by shifting every later id one place left costs up to n moves per delete. When most copies are extra, that is about n^2 / 2 moves: about 5 × 10^9 at n = 10^5. Aim for O(n).
The list is sorted, so all copies of an id sit together. That is why one look back into the kept prefix is enough to count them. And m can be larger than the list, so a check that looks m places back must not run before m ids are kept.