algorithmfree

Brute-force pair sum

Try every pair to find two numbers that add up to a target. Simple, but O(n²).

time
O(n²)
space
O(1)

// step through it

step 1 / 10
1function twoSumBrute(nums, target) {2  for (let i = 0; i < nums.length; i++) {3    for (let j = i + 1; j < nums.length; j++) {4      if (nums[i] + nums[j] === target) return [i, j];5    }6  }7  return null;8}
target
= 10
checks
= 1
  1. 1i
  2. 3j
  3. 4
  4. 6
  5. 8
  6. 11

1 + 3 = 4, not 10. Checks so far: 1.

How it works

Two nested loops try every pair: the first number with each one after it, then the second, and so on. For n items that is about n²/2 pairs, so doubling the array roughly quadruples the work. That is O(n²). Compare it with the two-pointers lesson, which solves the same problem on a sorted array in a single pass.