DSA interview question
The music player's "play next" button puts a song at the front of the queue, and "insert at position k" drops a song into a specific slot. With an array, both shift every later element. With a singly linked list, inserting at the head is O(1): create a node whose next is the old head, and it becomes the new head. Inserting at position k needs a walk to the node just before position k, then two pointer assignments. The order of those two assignments is where bugs hide.
Example: list 2 -> 3, insert 1 at the head → 1 -> 2 -> 3.
Node* insertAtHead(Node* head, int x); // returns the new head
Node* insertAtPosition(Node* head, int pos, int x); // pos is 1-indexed, 1 <= pos <= length + 1
| Input | Output list | Explanation |
|---|---|---|
insertAtHead(2 -> 3, 1) | 1 -> 2 -> 3 | The new node becomes the head |
insertAtHead(empty, 5) | 5 | Inserting into an empty list |
insertAtHead(7, 7) | 7 -> 7 | |
insertAtPosition(1 -> 2 -> 4, 3, 3) | 1 -> 2 -> 3 -> 4 | In the middle |
insertAtPosition(1 -> 2, 1, 0) | 0 -> 1 -> 2 | Position 1 is the head |
insertAtPosition(1 -> 2, 3, 9) | 1 -> 2 -> 9 | Position length + 1 is the tail |
(Confirm: positions are 1-indexed and valid; the function returns the (possibly new) head.)
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