DSA interview question
A gift-card kiosk lets a customer pick exactly two items whose prices add up to the card's value, and it needs to show which two. With thousands of items, checking every pair is O(n²) and noticeably slow. The classic answer uses a hash map: as you walk through the prices, you ask "have I already seen the complement target − price?" If so, you've found the pair; if not, you remember the current price and its position. That's one pass and O(n) time, and it's probably the most frequently asked interview question there is.
Example: prices [2, 7, 11, 15], target 9 → indices [0, 1] (2 + 7).
vector<int> twoSum(const vector<int>& nums, int target); // indices of the two numbers, or {-1, -1}
Input (nums, target) | Output | Explanation |
|---|---|---|
([2, 7, 11, 15], 9) | [0, 1] | 2 + 7 |
([3, 2, 4], 6) | [1, 2] | 3 + 3 isn't allowed: the same element can't be used twice |
([3, 3], 6) | [0, 1] | Two different elements with equal values |
([-1, -2, -3, -4, -5], -8) | [2, 4] | Negative numbers |
([1, 2, 3], 7) | [-1, -1] | No pair exists |
(Confirm: return the indices (smaller first) of two different elements; LeetCode guarantees exactly one answer, and here {-1, -1} signals none.)
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