Online store~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-203linked-lists
An online store keeps each cart as a chain of nodes, one node for each line. A line holds a product id.
When a product is discontinued, every line with that id must leave every cart. The same product can appear many times in a cart, and it can be the first line, so the head of the chain may change.
Write remove_line_items(head, target).
head is the first node of the cart, or null when the cart is empty. Each node's val is a product id.target is the id of the discontinued product.val equals target, keep the other nodes in their order, and return the new head. The result is null when every node was removed.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [4, 7, 7, 2, 7], target = 7
Output: [4, 2]| Step | prev | curr | What happens | Chain so far |
|---|---|---|---|---|
| [1] | placeholder | 4 | the placeholder points at the head | 4 → 7 → 7 → 2 → 7 |
| [3] | placeholder | 4 | 4 is kept, so prev moves to it | 4 |
| [3] | 4 | 7 | 7 matches, so prev.next skips it | 4 |
| [3] | 4 | 7 | 7 matches, so prev.next skips it | 4 |
| [3] | 4 | 2 | 2 is kept, so prev moves to it | 4 → 2 |
| [3] | 2 | 7 | 7 matches, so prev.next skips it | 4 → 2 |
| [4] | null | the walk ends: return placeholder.next | 4 → 2 |
Three nodes leave, and one of them was the last. A placeholder node in front of the head means the first line needs no special rule.
Input: head = [3, 3, 3], target = 3
Output: []Every line matches, the head included, so the cart ends empty.
Input: head = [1, 2], target = 9
Output: [1, 2]No line matches, so nothing changes.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^61 ≤ target ≤ 10^6Starting again from the head after every removal costs up to one walk for each match. With 10^5 nodes and half of them matching at the far end, that is about 2.5 × 10^9 hops.
One walk that removes matches as it meets them costs 10^5 hops.