1

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?

1
  • Time complexity is used for loops and not for operations. So O() will be evaluated for for and not for lookup array[i]. Commented Nov 8, 2022 at 4:37

3 Answers 3

2

Yes. array[i] is O(1). However you do it N times, which makes the entire loop O(n).

Sign up to request clarification or add additional context in comments.

1 Comment

This could be a comment but oddly answers question as well. Simple and to the point
1

Yes, it is O(1).

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

Comments

0

Should be O(1) you can read it at here javascript array complexity

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.