DEV Community

Discussion on: JavaScript Data Structures: Singly Linked List

Collapse
 
shivang12051996 profile image
shivang

Hii,

For arrays, isn't insert operation have O(1) complexity (since you don't have to shift anything when inserting) while deletion have O(n) (Referring to "What is an array" section)??

Thanks,

Collapse
 
miku86 profile image
miku86 • Edited

Hi @shivang,

if you have an array,
e.g. const myChars = ["A", "B", "C"],
then its elements are:
myChars[0] = "A",
myChars[1] = "B",
myChars[2] = "C".

If you add a new element at the beginning,
then every element has to get updated,
e.g. myChars[1] goes from B to A,
myChars[2] goes from C to B etc.

This is the worst case, because we have to update N elements.
In the middle of the array we have to update N/2 elements,
what also boils down to O(N).

Greetings
Michael

Collapse
 
shivang12051996 profile image
shivang

Thanks for reply and clarification!!!