DSA interview question
The browser from the previous problem keeps its history as a doubly linked list, and opening a page from a "recently closed" menu inserts it at the front. In a doubly linked list, inserting before the head means wiring two links instead of one: the new node's next points to the old head, and the old head's prev points back to the new node. Forgetting the second link is the classic bug, and it only shows up when you traverse backwards. The same two-sided wiring applies when inserting at any position.
Example: 2 <-> 3, insert 1 before the head → 1 <-> 2 <-> 3.
DNode* insertBeforeHead(DNode* head, int x); // returns the new head
DNode* insertAtPosition(DNode* head, int pos, int x); // 1-indexed, 1 <= pos <= length + 1
| Input | Forward result | Explanation |
|---|---|---|
insertBeforeHead(2 <-> 3, 1) | 1 <-> 2 <-> 3 | Backward: 3 <-> 2 <-> 1 |
insertBeforeHead(empty, 5) | 5 | |
insertBeforeHead(7, 7) | 7 <-> 7 | |
insertAtPosition(1 <-> 2 <-> 4, 3, 3) | 1 <-> 2 <-> 3 <-> 4 | Four links change |
insertAtPosition(1 <-> 2, 1, 0) | 0 <-> 1 <-> 2 | Same as inserting before the head |
insertAtPosition(1 <-> 2, 3, 9) | 1 <-> 2 <-> 9 | At the tail |
(Confirm: after every insertion, the backward traversal must be the exact reverse of the forward one.)
oldHead->prev = newNode?"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