Online store~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-83linked-lists
A shop keeps the price history of a product as a chain of nodes, from the oldest price to the newest. Each node holds a price in minor units and a pointer to the next node. The prices never fall, so the chain is sorted from the smallest to the largest.
A repeated import wrote some prices several times. The catalogue team wants each price to appear once. They want the existing chain edited in place, with no new nodes, because the chain can hold 100,000 prices.
Write remove_repeats(head).
head is the first node of a sorted chain, or null when the chain is empty.Input: head = [1, 1, 2, 3, 3]
Output: [1, 2, 3]The trace keeps one cursor curr. When the next node has the same price, the cursor skips it. Otherwise the cursor moves on.
| Step | curr price |
Next price | What happens | Chain after |
|---|---|---|---|---|
| 1 | 1 | 1 | equal: unlink the next node | 1, 2, 3, 3 |
| 2 | 1 | 2 | different: move on | 1, 2, 3, 3 |
| 3 | 2 | 3 | different: move on | 1, 2, 3, 3 |
| 4 | 3 | 3 | equal: unlink the next node | 1, 2, 3 |
| 5 | 3 | none | the end of the chain: stop | 1, 2, 3 |
Input: head = []
Output: []An empty chain stays empty.
Input: head = [4, 4, 4]
Output: [4]Each skip leaves the cursor on the first node, so three equal nodes become one.
0 ≤ number of nodes ≤ 100,0000 ≤ price ≤ 10,000,000, and the chain is sorted from the smallest to the largestChecking each price against all the prices kept so far costs about n × n / 2 = 5 × 10^9 steps for 100,000 nodes. That is far over the budget of about 10^8 a second. Because the chain is sorted, equal prices are neighbours, so one pass that compares each node with the next one is enough.