So I’m studying for my algorithm analysis exam tomorrow and I’m reading over the instructors notes and examples. There’s just one thing that I don’t understand and it’s this question:
Question: Inserting an element after a given element in an array-based list (cursor implementation) requires worst case time:
Answer: O(1)
Personally, I see the worst case being where the cursor is at the beginning of the list, therefore N-1 items in the array must be copied over to the next position before the new element is inserted and therefore it is an O(N) operation in the worst case.
However, when asked if this was a typo, the instructor stated that it wasn’t.
What’s the reasoning behind this? To all future answerers, thank you for your time.
Let’s say we have to insert element ‘a’. Well it says given an element, let’s call it ‘b’. What that means is you know what the next element is, let’s call it ‘c’. So all you have to do is to set the ‘next’ element of ‘a’ equal to ‘c’. Then set the next element of ‘b’ equal to ‘a’. This procedure is valid for any element. So the operation is constant time.