Skip to content
Advertisement

Is the space complexity O(1) or O(N) for the following code snippet?

This is one of the leetcode problems. In this problem we are to build an array from permutation and the challenge is to solve the problem in O(1) space complexity, so does the solution fulfills the criteria or not? One more thing if we are manipulating the same array but increasing its length by appending the elements at the end, does it mean that we are assigning new space hence causing O(N) space complexity during the execution of the program?

var buildArray = function(nums) {
        let len = nums.length
        for (let i = 0; i < len; i++) {
           nums.push(nums[nums[i]]); 
        }
        nums = nums.splice(len, nums.length);
        return nums;
    };

Advertisement

Answer

This is O(n) space complexity, you can’t “cheat” by pushing your data on the input array, because you are using extra space anyways.

This code would be the equivalent of storing your data in a new array, and then returning that

I would guess the target of this space complexity limitation is for you to reach to a solution using pointers to mutate the input array

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement