11

I have N numbers in arraylist. To get the indexOf, arraylist will have to iterate maximum N times, so complexity is O(N), is that correct?

OmG
  • 15,398
  • 7
  • 42
  • 71
good_evening
  • 19,773
  • 60
  • 178
  • 288
  • The worst case complexity is O(N), but the typical complexity is also O(N) as it will have to search half way on average. c.f. HashMap.get() has a typical complexity of O(1) but a worst case complexity of O(N). – Peter Lawrey Jan 27 '14 at 19:04

7 Answers7

11

Source Java API

Yes,Complexity is O(N).

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Nambi
  • 11,454
  • 3
  • 34
  • 49
4

Yes it's O(n) as it needs to iterate through every item in the list in the worst case.

The only way to achieve better than this is to have some sort of structure to the list. The most typical example being looking through a sorted list using binary search in O(log n) time.

Daniel Imms
  • 43,032
  • 14
  • 130
  • 152
2

Yes, that is correct. The order is based off the worst case.

Tim B
  • 38,707
  • 15
  • 73
  • 123
1

It is true. Best Case is 1 so O(1), Average Case is N/2 so O(N) and Worst Case is N so O(N)

Dakkaron
  • 4,941
  • 2
  • 32
  • 48
0

100%, it needs to iterate through the list to find the correct index.

Hong Wei Wang
  • 1,188
  • 2
  • 16
  • 28
0

In the worst case you find the element at the very last position, which takes N steps, that is, O(N). In the best case the item you are searching for is the very first one, so the complexity is O(1). The average length is of the average number of steps. If we do not have further context, then this is how one can make the calculations:

avg = (1 + 2 + ... n) / n = (n * (n + 1) / 2) / n = (n + 1) / 2

If n -> infinity, then adding a positive constant and dividing by a positive constant has no effect, we still have infinity, so it is O(n).

However if you have a large finite data to work with, then you might want to calculate the exact average value as above.

Also, you might have a context there which could aid you to get further accuracy in your calculations.

Example:

Let's consider the example when your array is ordered by usage frequency descendingly. In case that your call of indexOf is a usage, then the most probable item is the first one, then the second and so on. If you have exact usage frequency for each item, then you will be able to calculate a probable wait time.

Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148
-1

An ArrayList is an Array with more features. So the order of complexity for operations done to an ArrayList is the same as for an Array.

Roudy Tarabay
  • 399
  • 1
  • 3
  • 17