Arrays

Episode 2 Two Sum

5 min · LeetCode 1 · Java

Title card of Episode 2: Two Sum

▶ This video is coming to YouTube soon.

LeetCode 1, Two Sum, solved on screen. We start with three examples, including the one that catches people out (you can't use the same element twice). Then we watch the brute force check every pair, read its code line by line, and see why it's O(n²). Finally, one pass with a HashMap finds the answer in O(n): for each number, look up the partner it needs.

What you'll learn

  • What Two Sum asks, through three worked examples
  • The brute force: every pair, O(n²) time, O(1) space
  • The key idea: the partner of x is target − x
  • The one-pass HashMap solution: O(n) time, O(n) space
  • Why you check the map before putting into it

Chapters

  1. 0:00The problem
  2. 0:15Examples
  3. 0:53Brute force, visualized
  4. 1:38Brute force: the code
  5. 1:52Brute force, line by line
  6. 2:30One-pass HashMap: the idea
  7. 2:45One-pass HashMap, visualized
  8. 3:29One-pass HashMap: the code
  9. 3:43One-pass HashMap, line by line
  10. 4:22Comparing the approaches