Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 4, 2024 01:38
Show Gist options
  • Save sAVItar02/6ca5bcb9289e789d728c0d4e07c38415 to your computer and use it in GitHub Desktop.
Save sAVItar02/6ca5bcb9289e789d728c0d4e07c38415 to your computer and use it in GitHub Desktop.
Find all numbers disappeared in an array
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDisappearedNumbers = function(nums) {
let ans = [];
for(let i=0; i<nums.length; i++) {
if(nums[Math.abs(nums[i]) - 1] < 0) continue;
nums[Math.abs(nums[i]) - 1] = -nums[Math.abs(nums[i]) - 1];
}
for(let i=0; i<nums.length; i++) {
if(nums[i] > 0) ans.push(i+1);
}
return ans;
};
// Iterate through the array and negate the element at index equal to the current element - 1
// ex: [4, 2, 1 ,3 , 5, 5] element at 0 = 4 ==> mark element at nums[4 - 1] as -nums[4 - 1]
// at the end, iterate through the array again and add the (index + 1) of elements which are greater than 0 to the ans array
// Time: O(n)
// Space: O(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment