Bank app~30 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-287cycle-detection · two-pointers
A bank app exports a snapshot of account ids to a read-only audit file. The snapshot holds n + 1 ids, and every id is between 1 and n. So at least one id must appear twice, and the audit says that exactly one id is repeated.
The audit machine has very little memory. It cannot copy the file, sort it or mark the ids it has seen. A snapshot can hold 100,001 ids.
Write find_duplicate_id(ids).
ids holds n + 1 ids, and every id is between 1 and n. Exactly one id appears more than once, and it may appear many times.ids, and use a fixed number of variables: no copy, no set and no sorting.Input: ids = [3, 1, 3, 4, 2]
Output: 3| Phase | Step | slow | fast | What happens |
|---|---|---|---|---|
| 1 | start | 0 | 0 | both walkers stand on slot 0 |
| 1 | 1 | 3 | 4 | slow goes to ids[0] = 3, fast goes to ids[3] = 4 |
| 1 | 2 | 4 | 3 | slow goes to ids[3] = 4, fast goes 4 → 2 → 3 |
| 1 | 3 | 2 | 2 | slow goes to ids[4] = 2, fast goes 3 → 4 → 2: they meet on slot 2 |
| 2 | start | 2 | walker 0 | slow stays on slot 2, and a new walker starts on slot 0 |
| 2 | 1 | 3 | walker 3 | both reach slot 3: return 3 |
Read slot i as a pointer to slot ids[i]. Then the walk from slot 0 is 0 → 3 → 4 → 2 → 3, which loops through 3, 4 and 2. Slot 3 is the one with two pointers into it, because ids[0] and ids[2] are both 3.
Input: ids = [1, 3, 4, 2, 2]
Output: 2Slots 3 and 4 both hold 2. The walk 0 → 1 → 3 → 2 → 4 → 2 enters the loop 2, 4 at slot 2.
Input: ids = [2, 2, 2, 2, 2]
Output: 2One id can fill the whole list. The ids 1, 3 and 4 never appear.
2 ≤ length of ids ≤ 1000011 ≤ ids[i] ≤ length of ids - 1Comparing every id with every id before it makes about n^2 / 2 steps: 5 × 10^9 at this size, which is too slow. Sorting a copy is fast, and so is a hash set, but each holds a whole copy of the list, and the audit machine cannot.
So the answer must come from the structure of the data. Every id is a valid position in the list, so the ids can be read as pointers. That gives O(n) time and O(1) extra memory.
A note on the tests: the judge measures time, not extra memory. So a hash set or a sorted copy passes, and only the scan of earlier ids times out. The read-only, fixed-memory walk is what this problem teaches.