Sobes.tech
Junior — Middle

What is the time complexity of index access in a list?.

sobes.tech AI

Answer from AI

Access time complexity by index in a list (std::list in C++) is O(n), where n is the element's position.

This is because std::list is implemented as a doubly linked list, and accessing an element by index requires a sequential traversal from the beginning or end of the list to the desired element.

Example:

#include <list>
#include <iostream>

int main() {
    std::list<int> lst = {10, 20, 30, 40, 50};
    int index = 3;
    auto it = lst.begin();
    std::advance(it, index); // move iterator forward by 3 positions
    std::cout << "Element at index " << index << ": " << *it << std::endl;
    return 0;
}

For faster access by index, it is better to use std::vector, where access by index is O(1).