Ride-hailing app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-448traversal
A ride-hailing app gives each driver on a shift an id from 1 to n. At the end of the shift it has a list of n check-in records, and each record holds one driver id from 1 to n.
Some drivers checked in more than once, so some ids never appear. Find them. The reporting job runs on a small device, so it should keep no table of seen ids.
Write missing_ids(roster).
roster[i] is the driver id in the i-th check-in record, and every id is between 1 and roster.length.roster.length that do not appear in roster, smallest first.Input: roster = [4, 3, 2, 7, 8, 2, 3, 1]
Output: [5, 6]Use the sign of roster[id - 1] as a mark that the id appears. Read each record, and make the number at place id - 1 negative.
| After step | The list |
|---|---|
| before | [4, 3, 2, 7, 8, 2, 3, 1] |
| all records read | [-4, -3, -2, -7, 8, 2, -3, -1] |
Places 4 and 5 are still positive, so the ids 5 and 6 never appeared.
Input: roster = [1]
Output: []The only id, 1, appears.
Input: roster = [2, 2]
Output: [1]Id 2 checked in twice, and id 1 never did.
1 ≤ roster.length ≤ 100,000 (check-in records and drivers)1 ≤ roster[i] ≤ roster.length (driver ids)Searching the list for each id from 1 to n costs about n × n steps, which is 10^10 at n = 100,000. A table of seen ids costs O(n) memory. Because the ids are exactly the places of the list, the list itself can hold the marks, and one pass is enough.