Created
August 5, 2023 13:47
-
-
Save optimistiks/f049122f31cb2b141f31a0f23d8fa1c8 to your computer and use it in GitHub Desktop.
Given an array, nums, containing n distinct numbers in the range [0,n], return the only number in the range that is missing from the array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function findMissingNumber(nums) { | |
| let i = 0; | |
| // apply cyclic sort to place values at their indexes (e.g. value 2 goes to index 2) | |
| while (i < nums.length) { | |
| if (nums[i] !== i && nums[nums[i]] != null) { | |
| const tmp = nums[nums[i]]; | |
| nums[nums[i]] = nums[i]; | |
| nums[i] = tmp; | |
| } else { | |
| i += 1; | |
| } | |
| } | |
| // find first index that does not match it's value, it's the missing element | |
| const missing = nums.findIndex((element, index) => element !== index); | |
| return missing; | |
| } | |
| // tc: O(n) | |
| // sc: O(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment