Skip to content

Two Sum

EasyLeetCode #1Time O(n)Space O(n)

You get a list of integers and a target number. Exactly one pair of entries adds up to the target. Return the indices of that pair. You can’t use the same entry twice.

nums = [2, 7, 11, 15], target = 9 -> [0, 1] (2 + 7 = 9)

Brute force checks every pair, which is O(n²). The waste is that for each number you re-scan the array looking for its partner, even though you know exactly what the partner is: target - num.

So ask a different question as you walk the array once: have I already seen the partner of this number? A hash map from value to index answers that in O(1). If the partner is there, you’re done. If not, record the current number and move on.

Show solutionHide solution
def two_sum(nums: list[int], target: int) -> list[int]:
seen = {} # value -> index where we saw it
for i, num in enumerate(nums):
if target - num in seen:
return [seen[target - num], i]
seen[num] = i
return []
  • Time: O(n) — one pass, with an O(1) map lookup and insert per element.
  • Space: O(n) — in the worst case the map holds every element before the pair is found.
  • Check before you insert. If you add the current number to the map first, an input like [3, 3] with target 6 still works, but [3, 2, 4] with target 6 would match 3 with itself.
  • Return indices, not values. That’s why sorting first doesn’t work directly: it destroys the original positions.
  • Say the trade-off out loud. You are spending O(n) memory to drop from O(n²) to O(n) time. Interviewers want to hear that.

Two Sum II - Input Array Is Sorted (LeetCode 167)

Section titled “Two Sum II - Input Array Is Sorted (LeetCode 167)”

The array is sorted and you must use O(1) extra space. The trick: two pointers, one at each end. If the sum is too small move the left pointer right; if too big move the right pointer left. Sorted order guarantees you never skip the answer.

Find all unique triplets that sum to zero. The trick: sort, fix one number, then run the sorted two-pointer Two Sum on the rest. Skip repeated values to avoid duplicate triplets. O(n²) overall.

Count contiguous subarrays that sum to k. The trick: the same “have I seen the partner?” idea applied to running totals. Keep a map of prefix-sum counts; at each position, add the count of prefix - k seen so far.