Skip to the page

DSA · Build it

Two Sum: return every pair (LeetCode 1)

The interviewer asks

Given an array and a target, return all pairs that add up to the target. For [1,5,2,6,8,9,10] and 7, return [1,6], [5,2], [2,5], [6,1]. Write it in JavaScript.

Then

Follow-ups the interviewer asks next

  1. Return indices instead of values.
  2. Unique unordered pairs only.
  3. The array is sorted: use O(1) extra space.
  4. Three numbers instead of two.

The answer

What a strong answer covers

  • clarify duplicates and whether order matters; build a Set (or a value → count Map, so x = target − x needs count ≥ 2) and scan in order, emitting [x, target − x] when present; O(n) time, O(n) space; for unique unordered pairs, sort and use two pointers, O(n log n) time and O(1) extra.

The red pen

Common traps

Avoid:O(n²) nested loops without mentioning better; pairing an element with itself; not asking about ordering.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview