Sobes.tech
Junior — Middle

What is the time complexity of searching for an element in an ArrayList?

sobes.tech AI

Answer from AI

The time complexity of searching for an element in an ArrayList depends on how the search is performed:

  • If it's about searching by index (for example, get(index)), then the operation is performed in O(1), since ArrayList is implemented based on an array and index access is instant.

  • If you need to find an element by value (for example, contains(element) or indexOf(element)), then ArrayList iterates through the elements sequentially, so the time complexity will be O(n), where n is the number of elements in the list.

Example of searching by value:

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

boolean found = list.contains("banana"); // O(n)
What is the time complexity of searching for an… - sobes.tech