PPractick

DSA interview question

Sort a Linked List

Hard · Data structures · Topics: linkedlist, merge sort

The problem

A log collector receives events out of order and stores them in a singly linked list; before export, the list must be sorted by value in O(n log n), ideally without copying everything into an array. Quick sort needs random access for good pivots, and heap sort needs indexing, but merge sort fits linked lists perfectly: splitting at the middle uses fast and slow pointers, and merging two sorted lists only relinks nodes, so no extra buffer is needed.

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

Function signature

Node* sortList(Node* head);  // returns the head of the sorted list

Test cases

Input listOutput listExplanation
4 -> 2 -> 1 -> 31 -> 2 -> 3 -> 4
-1 -> 5 -> 3 -> 4 -> 0-1 -> 0 -> 3 -> 4 -> 5Negative values
2 -> 2 -> 11 -> 2 -> 2Duplicates (stable)
11
(empty)(empty)

(Confirm: sort by relinking nodes; O(n log n) time; the code cross-checks random lists against std::sort.)

How interviewers phrase it

Clarifying questions to ask

  1. Is O(n log n) required?
  2. Is O(1) extra space required? (Top-down recursion uses O(log n) stack; bottom-up merge sort is O(1).)
  3. Can I just copy values into an array and sort? (Usually not the intended answer.)

Follow-ups to expect

  1. "Why merge sort rather than quick sort?"
  2. "How do you split the list?"
  3. "Why must fast start at head->next?"
  4. "How do you get O(1) space?"
  5. "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