Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of contains(Object o), in an ArrayList of Objects

As the title says, I was wondering what the time complexity of the contains() method of an ArrayList is.

like image 408
Samuel Avatar asked Apr 24 '11 16:04

Samuel


People also ask

What is the time complexity of Contains method in ArrayList?

Getting back to complexity analysis, the ArrayList. contains() method requires O(n) time. So the time we spend to find a specific object here depends on the number of items we have in the array.

What is the big O of ArrayList?

Big O: Formal DefinitionLet T(n) – the number of operations performed in an algorithm as a function of n. T(n) ∈ O(f(n)) if and only if there exists two constants, n0 > 0 and c > 0 and a function f(n) such that for all n > n0 , cf(n) ≥ T(n).

Does Hashset contain O 1?

It runs in O(1) expected time, as any hash table (assuming the hash function is decent). It is backed by a HashMap where the key is the Object.


1 Answers

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.

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html

like image 89
davin Avatar answered Oct 11 '22 04:10

davin