Notes for JS based data structures, algorithms, and technical interviews.
Prompt: We are given an unsorted array containing
n
numbers taken from therange 1 to n
. The array originally contained all the numbers from 1 to n, but due to a data error, one of the numbers got duplicated which also resulted in one number going missing.
- Find both these numbers.
Input: [3, 1, 2, 5, 2]
Output: [2, 4]
Explanation: '2' is duplicated and '4' is missing.
O(n)
O(1)
// No comments
const find_corrupt_numbers = function(nums) {
let i = 0;
while(i < nums.length){
let j = nums[i]-1;
if(nums[i] === nums[j]){
i++;
} else {
[nums[i], nums[j]] = [nums[j], nums[i]];
}
}
for(let i = 0; i < nums.length; i++){
if(nums[i] !== i+1) return [nums[i], i+1];
}
return [-1, -1];
};
// Comments
const find_corrupt_numbers = function(nums) {
let i = 0;
while(i < nums.length){
let j = nums[i]-1; // Sorted index of i;
// If the value at i is at it's sorted position or there is a duplicate, increment i
if(nums[i] === nums[j]){
i++;
} else {
// Else, swap the value at i into it's sorted position
[nums[i], nums[j]] = [nums[j], nums[i]];
}
}
// Find the out of place number, that will be our duplicate, and it's index+1 will be our missing number
for(let i = 0; i < nums.length; i++){
if(nums[i] !== i+1) return [nums[i], i+1];
}
return [-1, -1];
};