What is the time complexity to count the number of elements in the linked list ?

2024

What is the time complexity to count the number of elements in the linked list ?

  1. A.

    O(1)

  2. B.

    O(n)

  3. C.

    O(logn)

  4. D.

    O(n²)

Attempted by 238 students.

Show answer & explanation

Correct answer: B

Counting elements in a linked list requires traversing all nodes from head to tail. This linear traversal means time complexity is O(n) where n is the number of nodes.

Explore the full course: Niacl Ao It Specialist