Hacker News new | past | comments | ask | show | jobs | submit login

O(n) - regardless linked structure or array backed.



How is inserting an item at the head of a linked list O(n)?


Easy:

    insert(list, node):
        node.next = list.head;
        list.head = node;
        sleep(list.count++);
Remove the `sleep` in second version, and quote significant speedup. See also http://thedailywtf.com/articles/The-Speedup-Loop


It's an average. Sometimes you insert at 0, sometimes at 1, sometimes at 2, ... sometimes at n. On average it's O(n).


In this case it's the worst-case performance.


Who said you insert at different locations?


Nobody. But who said you insert at the head? And who said the whole thing is list-backed? Insert is just insert--not a lot to work with there.

Performance complexity is spoken to general cases and averages unless indicated otherwise.


"insert" does not stipulate prepend or append. The latter two operations are O(1) both for linked and array backed [amortized O(1) for array backed and actually faster due to high constant costs of allocating/releasing/iterating linked structures]


O(n) means it takes less than or equal to linear time to preform the operation. So if an operation is O(1), it is also O(n).


O(1) is a subset of O(n).




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: