Skip to content
Guest
Learn DSA · Course Syllabus Show lessons
Complexity & Patterns · 9 min read · Intermediate

Hash Maps & Two Pointers

Eliminate O(n^2) nested loops using O(1) Hash Map lookups (Two Sum) and sorted Two Pointers.

What you'll learn

  • Solve Two Sum in O(n) time using a Hash Map of seen values
  • Check palindromes or sorted pairs in O(n) time and O(1) space using Two Pointers
  • Trade O(n) space for a huge speed win over O(n^2) brute force

Whenever you see a brute-force solution checking “is there another element that complements x?”, a Hash Map (new Map()) turns the inner $O(n)$ scan into an $O(1)$ lookup, dropping total runtime from $O(n^2)$ to $O(n)$.

Fill-in-the-Blank Exercise

O(n) Two Sum with Map

Compute the needed complement and check if seen already contains it.

const need = target - nums[i];
if (seen.(need)) return [seen.(need), i];
seen.set(nums[i], i);

Live DSA Playground

Two Sum in O(n) Time
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. What is the time and space complexity of Hash Map Two Sum?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind