PPractick

DSA interview question

Two Sum

Easy · Algorithms · Topics: array, hash map

The problem

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).

Function signature

vector<int> twoSum(const vector<int>& nums, int target);  // indices of the two numbers, or {-1, -1}

Test cases

Input (nums, target)OutputExplanation
([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.)

How interviewers phrase it

Clarifying questions to ask

  1. Return indices or values?
  2. Is exactly one solution guaranteed? What if there is none?
  3. Can the same element be used twice?
  4. Is the array sorted?

Follow-ups to expect

  1. "Why check the map before inserting the current element?"
  2. "What if the array is sorted?"
  3. "Can you sort first for an unsorted array?"
  4. "How would you count all pairs with the sum?"
  5. "Complexity?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in