LeetCode 1 Two Sum - Example and Complexity Analysis

Walkthrough and analysis

Let's trace through nums = [3, 2, 4] with target = 6.

At index 0, you see 3. Check: is 6-3=3 in the map? No. Store {3: 0}.

At index 1, you see 2. Check: is 6-2=4 in the map? No. Store {3: 0, 2: 1}.

At index 2, you see 4. Check: is 6-4=2 in the map? Yes, at index 1. Return [1, 2].

You check nn numbers, doing O(1)O(1) hash lookups each time. That's O(n)O(n) time.

The hash map stores up to nn entries, so O(n)O(n) space.