Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Space complexity of overwriting function input

Suppose we have the function below:

def foo(nums):
    nums = sorted(nums)
    return nums

In our function, we overwrite our original parameter nums, by storing the sorted version of the input in it.

My question is simple: does overwriting the input count toward auxiliary space occupation? More specifically, is the auxiliary space of our function O(N) or O(1)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I know this question is not very nuanced, but I cannot find a clear answer anywhere. I understand that sorted() produces and stores a new version of the list. In this way, such an operation occupies O(N) space, where N is the length of the input list.

However, since we are overwriting the input, which already held a list of size N, do we still consider this operation occupying additional O(N) space?

>Solution :

However, since we are overwriting the input

This is not how Python works. We’re not overriding the input.
nums is a name for the input list within the function scope, and then we change it to be the name for the sorted list.

To better understand how Python names and values work I recommend this excellent PyCon talk.

Since the list behind nums is at least still referenced by the caller of the method, it can not be garbage collected until the operation finishes.

There will be a moment when the new list and the old list both co-exist, thus we take additional O(N) space.

Python uses Timsort for sorting which consumes O(N) space complexity, so even sorting it in place with .sort() still consumes O(N).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading