Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created August 5, 2023 13:47
Show Gist options
  • Select an option

  • Save optimistiks/f049122f31cb2b141f31a0f23d8fa1c8 to your computer and use it in GitHub Desktop.

Select an option

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.
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