I am having a hard time understanding what is O(1) space complexity. I understand that it means that the space required by the algorithm does not grow with the input or the size of the data on which we are using the algorithm. But what does it exactly mean?
If we use an algorithm on a linked list say 1->2->3->4, to traverse the list to reach "3" we declare a temporary pointer. And traverse the list until we reach 3. Does this mean we still have O(1) extra space? Or does it mean something completely different. I am sorry if this does not make sense at all. I am a bit confused.
To answer your question, if you have a pointer and traverse the list it is counted as O(1) space complexity. If you have 10 or 100 or even 1000 pointers the space complexity is O(1). But, if you wanna have 'N' pointers, and even if 'N' is as small as 1, the space complexity is O(N).
Hope you understand, O(1) denotes constant (10, 100 and 1000 are constant) space and DOES NOT vary depending on the input size (say N).
Let's say I create some data structure with a fixed size, and no matter what I do to the data structure, it will always have the same fixed size. Operations performed on this data structure are therefore O(1).
An example, let's say I have an array of fixed size 100. Any operation I do, whether that is reading from the array or updating an element, that operation will be O(1) on the array. The array's size (and thus the amount of memory it's using) is not changing.
Another example, let's say I have a LinkedList to which I add elements to it. Every time I add an element to the LinkedList, that is a O(N) operation to the list because I am growing the amount of memory required to hold all of it's elements together.
Hope this helps!
来源:https://stackoverflow.com/questions/43260889/what-is-o1-space-complexity