Skip to the solution
EasyDSA12 min read

How do you solve the Two Sum problem efficiently?

46 views

The problem

Question presented to candidate: "Given a list of integers and a target, return the indices of the two numbers that add up to the target. You can assume there is exactly one answer and you cannot use the same element twice. Please code it in Python and tell me the time and space complexity."

What a strong answer should cover:

  • The brute force first (check every pair, O(nยฒ)), then the improvement: for each x, look up its complement target - x.
  • A one-pass dict mapping value โ†’ index, with the lookup done before the insert so an element never pairs with itself.
  • O(n) average time and O(n) extra space, and why "average": dict lookups are O(1) on average, not in the worst case.
  • The sorted-input alternative: two pointers, O(n) time and O(1) space, and why sorting loses the original indices.
  • Python specifics: enumerate for index + value, in on a dict is a hash lookup (on a list it is a linear scan), and Python ints never overflow.

Clarifying questions expected:

  • Indices or values? Is the input sorted?
  • What should happen when there is no pair?

Code / implementation expected: Yes โ€” a two_sum(nums, target) function in Python using a dict, run on a few inputs including duplicates and a no-answer case.

  • arrays
  • hashing

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonOne-pass hash map Two Sum on six inputs
PythonBrute force vs sort + two pointers vs hash map: counting the work

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 38 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is topological sort and when is it used?

Continue