Chat app~12 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-268traversal
A chat app numbers every message of a conversation from 0 upwards. After a network drop, the phone reconnects and receives the messages again, in any order. One message did not arrive.
The conversation has messages numbered 0 to n, so n + 1 numbers in all. The phone holds n of them. Your task is to find the number of the one message that is missing, so the app can ask the server for it.
Write missing_number(numbers).
numbers holds n different whole numbers, all between 0 and n inclusive, in any order.n is missing.Input: numbers = [3, 0, 1]
Output: 2Here n = 3, so the full range is 0, 1, 2, 3.
| Step | Value | Running total of what arrived |
|---|---|---|
| start | 0 | |
| 1 | 3 | 3 |
| 2 | 0 | 3 |
| 3 | 1 | 4 |
The full range adds up to 0 + 1 + 2 + 3 = 6. The difference 6 - 4 = 2 is the missing number.
Input: numbers = [0, 1, 2, 3]
Output: 4The numbers 0 to 3 arrived, so the last number of the range, 4, is the one that is missing.
Input: numbers = [1]
Output: 0Here n = 1, and number 1 arrived. The missing number is 0.
1 ≤ numbers.length ≤ 100,000 (messages received)0 ≤ numbers[i] ≤ 100,000 (message numbers)numbers.length is missing.Looking for each number of the range in the list costs up to n steps, and the range has n + 1 numbers. At n = 100,000 that is about 5 × 10^9 steps. That is too slow. The sum of the range, n(n+1)/2, is 5,000,050,000 here, so it needs a 64-bit integer.