DSA interview question
A price-matching tool keeps a store's product prices in a sorted doubly linked list of distinct values and needs every pair of products whose prices add up to a gift card's value. Checking all pairs is O(n²); a hash set works but ignores the sorting. Because the list is doubly linked, the classic two-pointer technique applies directly: one pointer starts at the head (smallest), one at the tail (largest), and they walk toward each other depending on whether the current sum is too small or too large.
Example: 1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9, target 7 → (1, 6), (2, 5).
vector<pair<int, int>> findPairsWithSum(DNode* head, int target); // pairs (smaller, larger), ascending by first value
Input (list, target) | Output | Explanation |
|---|---|---|
(1 <-> 2 <-> 4 <-> 5 <-> 6 <-> 8 <-> 9, 7) | (1, 6) (2, 5) | |
(1 <-> 5 <-> 6, 6) | (1, 5) | |
(2 <-> 4 <-> 6 <-> 8, 10) | (2, 8) (4, 6) | |
(1 <-> 2 <-> 3, 10) | (none) | |
(5, 10) | (none) | One node can't pair with itself |
(Confirm: the list is sorted with distinct values; each pair uses two different nodes.)
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