awelgorithms

Nested scan versus a map

Updated

For each i, scanning the rest or the prefix for a complement, a duplicate, or a count is O(n²). Storing what you have seen in a map or set makes each query expected O(1) and the pass O(n).

What to focus on

The map is the index you wished the array had. Two-sum, first duplicate, anagram checks against a fixed bag all use this swap.

Worked examples

nested two-sum

a = [4, 1, 9], t = 10
  1. i=0 scan 1,9; i=1 scan 9

Result: O(n²) pair scan

map two-sum

a = [4, 1, 9], t = 10
  1. seen 4, at 1 need 9 miss, at 9 need 1 hit

Result: expected O(n)

empty

a = [], t = 0
  1. no pairs

Result: none either way

Try it

Write twoSum(a, t). a is an array of integers. t is the target sum. Use a value-to-index map in one pass, expected O(n). Do not nest a scan for each i. a = [4, 1, 9], t = 10 → O(n²) pair scan. a = [4, 1, 9], t = 10 → expected O(n). a = [], t = 0 → none either way.

a is a list of integers and may be empty.