💻7 Official Course Tracks

Computer Science

Computer Science: step-by-step Socratic AI tutors, core formulas, worked examples, and exam prep across High School, CÉGEP, and University.

High School & AP

CÉGEP & College

University & Honours

1-Page Exam Sheet: O(n²) → O(n) Hash Map Pattern

Eliminate nested loops by storing seen values in a Hash Map and checking if (target - current) already exists in O(1) time.

  • 1. Initialize empty map: seen = new Map()
  • 2. Loop once: complement = target - nums[i]; if seen.has(complement) return [seen.get(complement), i]
  • 3. Store current element AFTER checking: seen.set(nums[i], i) → O(n) time, O(n) space

Why check seen.has(complement) BEFORE seen.set(nums[i], i)?

So an element doesn’t match with itself when target = 2 × nums[i] (e.g., target = 6, nums[i] = 3).

When does a Hash Map degrade from O(1) to O(n)?

When many keys hash to the exact same bucket (collision chain).

What if the input array is ALREADY sorted and O(1) space is required?

Use Two Pointers (left = 0, right = n - 1) instead of a Hash Map.