Ride-hailing app~30 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-41hashing
A ride-hailing app numbers its trips 1, 2, 3 and so on. A nightly job receives a list of trip ids that were reported by drivers. The list is unordered, can repeat an id, and can hold bad values such as 0 or negative numbers.
Operations needs the smallest positive trip number that is missing from the list, so that the next audit starts there.
The list holds up to 100,000 ids. The job runs on a small device, so it may use only a copy of the list and a few extra numbers.
Write first_missing(ids).
ids[i] is a reported trip id. It can be zero, negative, repeated or very large.ids.Input: ids = [3, 4, -1, 1]
Output: 2There are 4 ids, so the answer is between 1 and 5. Each step sends values from 1 to 4 to their own place. The table shows the copy after each place is settled.
| Place | Copy after the place is settled |
|---|---|
| 0 | [-1, 4, 3, 1] |
| 1 | [1, -1, 3, 4] |
| 2 | [1, -1, 3, 4] |
| 3 | [1, -1, 3, 4] |
Place 1 holds -1 instead of 2, so 2 is the smallest missing id.
Input: ids = [1, 2, 0]
Output: 3The ids 1 and 2 are present and 0 does not count, so 3 is the first missing id.
Input: ids = [7, 8, 9, 11, 12]
Output: 1The number 1 does not appear, and every value is too large to matter.
1 ≤ ids.length ≤ 100,000 (reported trips)-1,000,000,000 ≤ ids[i] ≤ 1,000,000,000 (reported trip id)With n ids, the answer is at most n + 1. If 1 to n are all present, n + 1 is missing. Otherwise some number up to n is missing, so other values never matter.
Trying 1, 2, 3 and so on with a scan each costs 5,000,150,000 steps when the ids are 1 to 100,000 in order. Use each id's own value as the place it belongs to.