PPractick

DSA interview question

Find the Length of a Linked List

Easy · Data structures · Topics: linkedlist

The problem

The music player shows "12 songs in queue". The queue is a singly linked list and doesn't store its size, so the only way to know is to walk it from the head, counting nodes until you reach nullptr. It's the simplest linked-list traversal, and it's also the building block for many problems that first need the length: finding the middle, removing the n-th node from the end, rotating a list, or comparing two lists' lengths to find where they intersect.

Example: 1 -> 2 -> 3 -> 4 -> 5 → 5.

Function signature

int length(Node* head);            // iterative
int lengthRecursive(Node* head);   // recursive

Test cases

Input listOutputExplanation
1 -> 2 -> 3 -> 4 -> 55
(empty)0head is nullptr
91
4 -> 42Values don't matter, only nodes

(Confirm: the list is acyclic; an empty list has length 0.)

How interviewers phrase it

Clarifying questions to ask

  1. Could the list have a cycle? (Then a naive count never ends; detect the cycle first.)
  2. Is the list very long? (The recursive version uses O(n) stack.)

Follow-ups to expect

  1. "Iterative or recursive?"
  2. "What if the list has a cycle?"
  3. "Can you get the length in O(1)?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in