Sum Up a Pair in Array

Can you find a pair in array that will sum up to particular number?

💡Strategies for Solving This Problem

The Hash Map Classic

This is "Two Sum" - one of the most common interview questions ever. I've seen it at Google, Facebook, and Amazon. Everyone should know this cold.

The Problem

Given an array of numbers and a target sum, find two numbers that add up to the target. Return their indices.

Example: nums = [2, 7, 11, 15], target = 9
Answer: [0, 1] because nums[0] + nums[1] = 2 + 7 = 9

Naive Approach: Nested Loops

Try every pair: O(n²) time, O(1) space. Too slow.

Better: Hash Map

The key insight: When we see number x, we need to find (target - x).

Use a hash map to remember what we've seen:

  1. For each number, check if (target - number) is in the map
  2. If yes, we found the pair
  3. If no, add current number to map

O(n) time, O(n) space. Single pass.

Why Hash Map Wins

Hash map lookup is O(1). So checking "have we seen target - x?" is instant.

Without it, we'd need to search the array each time - that's O(n), making total O(n²).

Variation: Sorted Array

If array is sorted, you can use two pointers (left and right). Move them based on whether sum is too small or too large. O(n) time, O(1) space.

But if array isn't sorted, sorting first takes O(n log n), which is worse than hash map.

At Google

They asked me this as a warmup. Then asked: "What if there are multiple pairs?" Return all pairs or just one? "What if no solution exists?" Return empty array or null?

These clarifications matter. Always ask before coding.

Scroll to Top