Junior — Middle
What is the time complexity of searching for an element in an ArrayList data structure?
sobes.tech AI
Answer from AI
In the data structure ArrayList (in Java, this is the ArrayList class), searching for an element by index is performed in O(1) time, since it internally uses an array, and access by index is a constant-time operation.
However, if it is about searching for an element by value (for example, the contains or indexOf method), then the time complexity will be O(n), where n is the number of elements in the list, as it requires iterating through the elements until a match is found.
In summary:
- Access by index: O(1)
- Search by value: O(n)