Adarsh Mohanty
Adarsh Mohanty

Reputation: 11

Time complexity of traversing an array

Below are two ways I could traverse any array:

  1. Using for loop a variable would traverse from starting to end of array.
  2. Using while loop 2 variables would traverse from opposite direction and meet in between.

How would the time complexity vary, would it be reduced in second case or it would be same?

Upvotes: 0

Views: 3286

Answers (1)

haoyu wang
haoyu wang

Reputation: 1377

Of course the same. Both are O(n), in fact there is no way to traverse an array faster than O(n).Even if you tarverse from opposite direction, you still have to visit each element once.

Upvotes: 1

Related Questions