Search~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-316monotonic-stack · stacks
A search app lets people add filters to a saved search. Each filter has a numeric id, and the same id can be added several times. The saved search is the list of ids in the order they were added.
To shorten it, the app keeps exactly one copy of every different id, in the same relative order as before. Among all the lists it could keep, it picks the one that comes first when read from left to right: at the first difference, the smaller id wins. A saved search can hold up to 100,000 ids.
Write smallest_filter_list(filters).
filters is a list of whole numbers: the filter ids, in the order they were added.Input: filters = [4, 2, 4, 3, 2, 1, 3]
Output: [2, 4, 1, 3]Read the ids left to right and keep them on a stack, with a note of the last position of every id. A new id removes larger ids from the top, but only those that come again later. An id that is already on the stack is skipped.
| Position | Id read | What happens | Stack after |
|---|---|---|---|
| 0 | 4 | push | 4 |
| 1 | 2 | 4 is larger, and its last copy is at position 2: pop it, push 2 | 2 |
| 2 | 4 | push | 2, 4 |
| 3 | 3 | 4 is larger, but its last copy was at position 2: keep it; push 3 | 2, 4, 3 |
| 4 | 2 | already on the stack: skip | 2, 4, 3 |
| 5 | 1 | 3 is larger and comes again at position 6: pop it. 4 is larger but never comes again: keep it. Push 1 | 2, 4, 1 |
| 6 | 3 | push | 2, 4, 1, 3 |
The stack is the answer: [2, 4, 1, 3].
Input: filters = [5, 5, 5]
Output: [5]Every copy is the same id, so one copy is kept.
Input: filters = [3, 1, 2]
Output: [3, 1, 2]No id appears twice, so the only choice is every id once, in the original order.
1 ≤ number of ids ≤ 10^51 ≤ each id ≤ 10^5A plan that looks at every unchosen id at each step costs up to d steps a step, and there can be d = 100,000 different ids. That is about d^2 / 2 = 5 × 10^9 steps in all. It is too slow.
So the work must be close to n steps in all. Each id should be pushed once and popped at most once.