DSA interview question
A factory line records each part's grade as 0, 1 or 2 in a linked list, and the report needs all the 0s, then the 1s, then the 2s. With only three possible values there's no need for an O(n log n) sort. One option counts the values and overwrites them in a second pass. A cleaner option relinks the nodes into three separate chains (zeros, ones and twos) using dummy heads, then connects the chains, in one pass without changing any node's value. That matters when nodes carry more data than just the key.
Example: 1 -> 2 -> 2 -> 1 -> 2 -> 0 -> 2 -> 2 → 0 -> 1 -> 1 -> 2 -> 2 -> 2 -> 2 -> 2.
Node* sortZeroOneTwo(Node* head); // values are 0, 1 or 2; returns the new head
| Input list | Output list | Explanation |
|---|---|---|
1 -> 2 -> 2 -> 1 -> 2 -> 0 -> 2 -> 2 | 0 -> 1 -> 1 -> 2 -> 2 -> 2 -> 2 -> 2 | |
2 -> 2 -> 0 -> 1 | 0 -> 1 -> 2 -> 2 | |
2 -> 1 | 1 -> 2 | No zeros: the empty chain is skipped |
0 | 0 | |
(empty) | (empty) |
(Confirm: only the values 0, 1 and 2 appear; nodes are relinked rather than having their values overwritten.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in