Search code examples
javascriptarraysspace-complexity

What is the Space Complexity of Array.filter?


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:

  1. Create a results array and store duplicate numbers in that. Then return this array. I believe this is O(n) because I need the extra array.
  2. Filter the nums array and store this in the nums variable. I am unsure if this is O(1) or O(n) as I am now generating a new array, but then replacing my original right away.
  3. Filter the nums array and immediately return the new array.
  4. Use a custom filterInPlace function to modify the size of the nums array. I believe this is O(1) but it is a bit of a hassle to need to write for a Leetcode problem.

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;

}

Solution

    1. The space is going to be O(n) for sure.

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

    1. This is O(1) because you just modify nums array