DSA interview question
A logging service keeps recent log entries in a singly linked list and occasionally needs to delete the entry N positions from the end, for example the second-to-last. Counting the length first and then walking to position L − N takes two passes. The one-pass trick: start two pointers together, move the first N steps ahead, then move both until the first reaches the last node. The second pointer is then just before the node to remove. A dummy node in front of the head makes removing the head itself (N = length) no different from any other case.
Example: 1 -> 2 -> 3 -> 4 -> 5, N = 2 → 1 -> 2 -> 3 -> 5.
Node* removeNthFromEnd(Node* head, int n); // 1 <= n <= length; returns the new head
Input (list, n) | Output list | Explanation |
|---|---|---|
(1 -> 2 -> 3 -> 4 -> 5, 2) | 1 -> 2 -> 3 -> 5 | Removes 4 |
(1, 1) | (empty) | Removes the only node |
(1 -> 2, 1) | 1 | Removes the tail |
(1 -> 2, 2) | 2 | Removes the head |
(1 -> 2 -> 3, 3) | 2 -> 3 | Removes the head of a longer list |
(Confirm: n is valid (1 ≤ n ≤ length); the removed node is freed; one pass is the goal.)
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