Is this O(n) or O(1)?
Version: 5, id: 6114603: the worst-case time complexity of adding to a singly-linked list after the 10th node with a size of at least 10?
Is this O(n) or O(1)?
Version: 5, id: 6114603: the worst-case time complexity of adding to a singly-linked list after the 10th node with a size of at least 10?
[What is] the worst-case time complexity of adding to a singly-linked list after the tenth node with a size of at least ten.
That specific task, adding an item immediately after node ten, is O(1)
(a).
That's because the time taken to do it is not affected by the list size at all. It takes the exact same time whether the list has ten nodes, or a hundred billion nodes, and could be implemented as per the following pseudo-code:
def insert_after_tenth(first, item):
tenth = first.next.next.next.next.next.next.next.next.next # O(1)
item.next = tenth.next # O(1)
tenth.next = item # O(1)
I've calculated the tenth
variable in that way (rather than a loop) to make it clear that the time cost is not dependent on the list size. And, since every line is O(1)
, the complete operation is also O(1)
.
(a) Admittedly, that's based on a certain reading of the question, inserting the new item immediately after node ten. There is another reading you could argue, that of inserting at some point after node ten.
However, if that were the case, all that extra stuff about node ten would be irrelevant, since it would be O(n)
regardless of where you wanted to insert.
If you wanted extra marks (assuming this is some form of classwork), you may want to mention both possibilities but the first is by far the most likely.
If a LinkedList has n node, where n > 10, then the worst-case time complexity is O(N) since it needs to iterate through the list to get the last Node.