Reputation: 1240
When looping an array, people often use a simple method like below.
const array = [1,2,3,4,5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
My question is if array[i]
is O(1) operation or not.
For example, when i
is 3, does javascript get the number immediately OR count from 0 to 3 again?
Upvotes: 1
Views: 387
Reputation: 329
Should be O(1) you can read it at here javascript array complexity
Upvotes: 0
Reputation: 709
Because it takes a single step to access an item of an array via its index, or add/remove an item at the end of an array, the complexity for accessing, pushing, or popping a value in an array is O(1).
ref: here
Upvotes: 1
Reputation: 201439
Yes. array[i]
is O(1). However you do it N
times, which makes the entire loop O(n).
Upvotes: 2