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,
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".
const myChars = ["A", "B", "C"]
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.
myChars[1]
B
A
myChars[2]
C
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
Thanks for reply and clarification!!!
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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,
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 fromB
toA
,myChars[2]
goes fromC
toB
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
Thanks for reply and clarification!!!