|
| 1 | +--- |
| 2 | +title: 268. Missing Number |
| 3 | +author: nguyentp |
| 4 | +date: 2024-07-27 |
| 5 | +tags: [leetcode] |
| 6 | +render_with_liquid: false |
| 7 | +--- |
| 8 | + |
| 9 | +# [Problem understanding](https://leetcode.com/problems/missing-number/description/) |
| 10 | + |
| 11 | +`` |
| 12 | +Input: nums = [3,0,1] |
| 13 | +Output: 2 |
| 14 | +``` |
| 15 | +
|
| 16 | +- `N = 3`, then valid number should be `0, 1, 2, 3`. 2 is the missing number. |
| 17 | +- Base on the constraint, smallest number is 0 and largest is N. Smallest input is single element. In that case, `[0] or [1]`. |
| 18 | +
|
| 19 | +# Edge case |
| 20 | +
|
| 21 | +- `[0]`: return 1 |
| 22 | +- `[1]`: return 0 |
| 23 | +- `0, 1, 2`: All number are in order, return 3 |
| 24 | +- `1, 2, 3`: return 0 |
| 25 | +- `3, 2, 1`: return 0 |
| 26 | +
|
| 27 | +# Solution |
| 28 | +
|
| 29 | +1. Go through each number, check if that number is NOT in the all valid numbers. We use a hash table to store all valid numbers to speed up the checking. Time: N b/c loop through the input, Space: N to store all valid numbers. |
| 30 | +2. Hint: `distinct numbers in the range [0, n]`, For list [3,0,1], if we put number to its correct index, each number will have its place in the list. E.g. `3, 0, 1`, 0 will be at index 0, 1 is at index 1, 3 is at index 2 (3 is special case). So at the index 2, the value is 3, so the missing number is 2. We go through each number, if current number is not standing in its correct index, swap it to correct index. |
| 31 | +
|
| 32 | +- For example: `3, 0, 1` |
| 33 | +
|
| 34 | +``` |
| 35 | +[3, 0, 1] |
| 36 | + i -> skip, as we cannot swap 3 to index 3 |
| 37 | + |
| 38 | + [3, 0, 1] |
| 39 | + i -> swap 0 to index 0 |
| 40 | + |
| 41 | + [0, 3, 1] |
| 42 | + i -> skip, as we cannot swap 3 to index 3 |
| 43 | + |
| 44 | + [0, 3, 1] |
| 45 | + i -> swap 1 to index 1 |
| 46 | + |
| 47 | + [0, 1, 3] |
| 48 | + i -> skip, as we cannot swap 3 to index 3 |
| 49 | + |
| 50 | +Finnaly, loop through the list, we see that at index 2, we found a missing number b/c value at index 2 is not 2. 2 is the answer. |
| 51 | +``` |
| 52 | +
|
| 53 | +- Edge case: when input has perfect order, such as `0, 1, 2`, in that case, we will return N. |
| 54 | +
|
| 55 | +# Implement |
| 56 | +
|
| 57 | +``` |
| 58 | +class Solution(object): |
| 59 | + def missingNumber(self, nums): |
| 60 | + """ |
| 61 | + :type nums: List[int] |
| 62 | + :rtype: int |
| 63 | + """ |
| 64 | + n = len(nums) |
| 65 | + i = 0 |
| 66 | + while i < n: |
| 67 | + if nums[i] == n or nums[i] == i: |
| 68 | + i += 1 |
| 69 | + else: |
| 70 | + nums[nums[i]], nums[i] = nums[i], nums[nums[i]] |
| 71 | + |
| 72 | + for i in range(len(nums)): |
| 73 | + if nums[i] != i: |
| 74 | + return i |
| 75 | + return n |
| 76 | +``` |
0 commit comments