The task is taken from leetcode
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
My solution
/**
* @param {number[]} nums
* @return {number[]}
*/
var findDisappearedNumbers = function(nums) {
return nums
.reduce((arr, x) => {
arr[x - 1] = null;
return arr;
}, Array.from({length: nums.length}, (v, k) => k+1))
.filter(Boolean);
};
There has to be a more elegant solution to that.
console.log(findDisappearedNumbers([4,7,2,9]));
yields[1,3]
. The problem description is defective. \$\endgroup\$1 ≤ a[i] ≤ n (n = size of array)
. Your array[4,7,2,9]
has to have at least the size of9
. \$\endgroup\$