Two Sum Visualizer
DSA Arrays Two Sum

Two Sum Visualizer

What is Two Sum

Find two numbers that add to a target, and return their indices. Checking every pair is O(n²). A hash map remembers each value as you scan, so the complement target − x is an O(1) lookup.

  • Complement: for each x, look up target − x. Do not pair an index with itself.
  • Brute force: two nested loops — O(n²) time, O(1) space.
  • Hash map: one pass, store value → index — O(n) time, O(n) space.
  • Where it shows up: interview classic, 3Sum / k-Sum, checkout pair matching, prefix-sum pair problems.

The problem

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.

Example: nums = [2, 7, 11, 15], target = 9 → [0, 1] because nums[0] + nums[1] = 2 + 7 = 9
Constraints: 2 ≤ nums.length ≤ 10⁴ · -10⁹ ≤ nums[i] ≤ 10⁹

Approach

Brute Force  O(n²) time · O(1) space

Try every possible pair of elements and check if they sum to the target. No extra memory needed — just nested loops.

  1. Start with the first element (index i = 0).
  2. For each i, scan every element to its right (index j = i+1 to end).
  3. Check if nums[i] + nums[j] == target.
  4. If yes → return [i, j] immediately.
  5. If no match found after all pairs → return empty (no solution).

Why it's slow

For an array of length n, you check up to n × (n−1) / 2 pairs. With 10 elements that's 45 checks; with 100 it's 4,950. The inner loop repeats work already done — there's no memory of what you've seen.

Hash Map  O(n) time · O(n) space

Walk the array once. At each step, ask: "have I already seen the number I need?" Use a hash map to answer that in O(1).

  1. Create an empty hash map to store value → index.
  2. Visit each element nums[i] one by one (single pass).
  3. Compute the complement = target − nums[i].
  4. Check if the complement already exists in the map.
  5. If yes → return [map[complement], i] — done in one pass!
  6. If no → store nums[i] → i in the map and move on.

Why it's fast

Each element is visited exactly once. The map lookup replaces the entire inner loop — instead of scanning backwards, you know in O(1) whether the complement exists. You trade O(n) space to eliminate O(n) repeated work.

Interactive Step-by-Step Visualizer

Array — pointer i (🟡) & j (🟠)
Step: — Comparisons: 0 i: — j: — Result: —
Array — current pointer (🟡 = scanning)
Hash Map — { value: index }
Step: — i: — Complement: — Result: —

Input Controls

Complexity Comparison

Approach
Time
Space
Brute Force
O(n²)
O(1)
Hash Map
O(n)
O(n)
Comparisons so far
Brute: 0 Hash: 0

Algorithm & Pseudocode

brute_force.pseudo

1// Brute Force — check all pairs
2// Time: O(n²) Space: O(1)
3
4ALGORITHM TwoSum_Brute(nums, target):
5n ← length(nums)
6
7FOR i ← 0 TO n-2 DO
8FOR j ← i+1 TO n-1 DO
9IF nums[i] + nums[j] = target THEN
10  RETURN [i, j] // found!
11END FOR
12END FOR
13
14RETURN [] // no solution
15
16// Why O(n²)?
17// Worst case: n*(n-1)/2 pairs checked
18// n=4 → 6 pairs, n=10 → 45 pairs

hash_map.pseudo

1// Hash Map — single pass
2// Time: O(n) Space: O(n)
3
4ALGORITHM TwoSum_HashMap(nums, target):
5map ← empty hash map // {value: index}
6
7FOR i ← 0 TO n-1 DO
8complement ← target - nums[i]
9
10IF complement ∈ map THEN
11RETURN [map[complement], i]
12END IF
13
14map[nums[i]] ← i // store for future
15END FOR
16
17RETURN [] // no solution
18
19// Key: map lookup is O(1) average
20// One pass replaces the inner loop!

Implementation

brute_force.c

1#include <stdio.h>
2#include <stdlib.h>
3
4/**
5 * Returns array of 2 indices, caller frees.
6 * Time: O(n²) Space: O(1)
7 */
8int* twoSum_brute(int* nums, int n,
9int target, int* retSize) {
10int* res = malloc(2 * sizeof(int));
11*retSize = 2;
12
13for (int i = 0; i < n - 1; i++) {
14for (int j = i + 1; j < n; j++) {
15if (nums[i] + nums[j] == target) {
16  res[0] = i;
17  res[1] = j;
18  return res;
19}
20}
21}
22*retSize = 0;
23return NULL;
24}
25
26int main() {
27int nums[] = {2, 7, 11, 15};
28int n = 4, sz, target = 9;
29int* r = twoSum_brute(nums, n, target, &sz);
30if (sz) printf("[%d, %d]\n", r[0], r[1]);
31free(r);
32}

hash_map.c

1#include <stdio.h>
2#include <stdlib.h>
3
4#define TABLE_SIZE 10007
5
6typedef struct {
7int key, value;
8int used;
9} Entry;
10
11Entry table[TABLE_SIZE];
12
13void put(int k, int v) {
14int h = ((k % TABLE_SIZE) + TABLE_SIZE) % TABLE_SIZE;
15table[h].key = k; table[h].value = v; table[h].used = 1;
16}
17
18int get(int k, int* val) {
19int h = ((k % TABLE_SIZE) + TABLE_SIZE) % TABLE_SIZE;
20if (table[h].used && table[h].key == k)
21{ *val = table[h].value; return 1; }
22return 0;
23}
24
25/* Time: O(n) Space: O(n) */
26int* twoSum_hash(int* nums, int n,
27int target, int* sz) {
28int* res = malloc(2 * sizeof(int));
29
30for (int i = 0; i < n; i++) {
31int comp = target - nums[i], idx;
32if (get(comp, &idx)) {
33res[0] = idx; res[1] = i;
34*sz = 2; return res;
35}
36put(nums[i], i);
37}
38*sz = 0; return NULL;
39}
40
41int main() {
42int nums[] = {2, 7, 11, 15};
43int sz, target = 9;
44int* r = twoSum_hash(nums, 4, target, &sz);
45if (sz) printf("[%d, %d]\n", r[0], r[1]);
46}