'Calculate space complexity of list comprehension
I have written the below code:
nums = [0,2,1,5,3,4]
Here, nums is an array of distinct integers from 0 to nums.length - 1
def new_array(nums):
return [nums[num] for num in nums]
Please help me understand if the space complexity of above code is O(n) or O(1).
My understanding is that the space complexity is O(n) because a new list is created via list comprehension.
How the above code can be rewritten with space complexity O(1)?
Solution 1:[1]
You're creating a new list, so the space complexity is O(n).
A list comprehension returns a new list, and the list you construct contains the same number of elements as the original list. The memory used to store the elements of the list you pass in and the memory used to store the elements of the returned list are separate.
Solution 2:[2]
According to python documentation (https://docs.python.org/3/tutorial/datastructures.html?highlight=comprehension) list comprehension is a syntax sugar for a standard for so your code is equivalent to the following
nums = [0,2,1,5,3,4]
def new_array(nums):
L = []
for num in nums:
L.append(nums[num])
return L
Which is O(n)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrokenBenchmark |
| Solution 2 | Sergio PeƱafiel |
