I just finished working on the Leetcode problem Find All Duplicates in an Array and have some questions about the space complexity of the problem. This problem specifically asks for O(1) space complexity. Below I have written four different ways to solve this problem, but I am unsure what the space complexity of each of these options are.
The four options I came up with were:
I would appreciate some clarity on this. Thanks!
const findDuplicates = (nums) => {
const swap = (i, j) => {
[nums[i], nums[j]] = [nums[j], nums[i]];
};
let i = 0;
let idx;
const n = nums.length;
while (i < n) {
idx = nums[i] - 1;
if (nums[i] !== nums[idx]) {
swap(i, idx);
} else {
i += 1;
}
}
// Option 1 - Use a results array to contain duplicates
const result = [];
for (let i = 0; i < n; i += 1) {
if (nums[i] !== i + 1) {
result.push(nums[i]);
}
}
return result;
// Option 2 - Filter out duplicates and save in nums, then return nums
nums = nums.filter((num, i) => num !== i + 1);
return nums;
// Option 3 - Return the new array returned from Array.filter
return nums.filter((num, i) => num !== i + 1);
// Option 4 - Write a filterInPlace function to modify array in place
const filterInPlace = (array, condition) => {
// The number of items that have been kept
let j = 0;
for (let i = 0; i < array.length; i += 1) {
if (condition(array[i], i)) {
array[j] = array[i];
j += 1;
}
}
array.length = j;
return array;
}
filterInPlace(nums, (num, i) => num !== i + 1);
return nums;
}
The space is going to be O(n)
for sure.
and 3. Both are same , You can directly return it or Assign to new variable , then return it. Array.filter return a new array of required elements which is also O(n)
space for the newly formed array .
O(1)
because you just modify nums
array