Two Sum

Use a hash map to resolve complement lookups in one pass.

Easy1 min read
Lookup / Frequency / MatchingHash Map

What This Problem Is Asking

In one sentence

Find two indexes whose values add up to a target value.

Full problem statement

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input has exactly one solution, and you may not use the same element twice.

Recognition Clues

Signals that this pattern likely applies.

  • The prompt asks for a pair that satisfies a sum constraint.
  • A brute-force nested loop works but is too slow.
  • You can derive the needed value from current input.

Why This Pattern Fits

Hash map lookups collapse pair search from O(n^2) to O(n).

Daily usefulness: Useful for quick lookup joins and dedup checks in product code.

Interview usefulness: Classic hash map exercise used to evaluate tradeoff fluency.

Real-world relevance: Mirrors matching workflows in reconciliation and telemetry logic.

Code Snippets

Swift
1import Foundation
2
3func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
4    var seen: [Int: Int] = [:]
5
6    for (index, num) in nums.enumerated() {
7        let needed = target - num
8        if let otherIndex = seen[needed] {
9            return [otherIndex, index]
10        }
11        seen[num] = index
12    }
13
14    return []
15}

Visual Demo

Hash Map Walkthrough

Watch the map populate until a matching complement appears.

Checking index 0: need 7.

Numbers

271115

Seen Map (value -> index)

JSON
{}

Practical Use Cases

  • Match request IDs and acknowledgment IDs in event streams.
  • Resolve complementary values in dashboard filters.
  • Validate pair constraints in backend payload processing.

Demo Ideas

Interactive ways to teach this algorithm.

  • Animate map growth and complement checks each iteration.
  • Show side-by-side brute force and hash map timelines.

Related Problems