šŸ† Problem-Solving Patterns

The capstone: think like an algorithm pro

← Back to Algorithms

🧠 Patterns beat memorizing

You don't need to memorize a thousand puzzles. Most coding problems are solved by a handful of patterns. Learn the pattern, and you can crack a whole family of problems!

This capstone brings together everything: loops, hash tables, two-finger tricks, and smart thinking to turn slow O(n²) solutions into fast O(n) ones.

šŸ‘‰šŸ‘‰ Pattern 1: Two Pointers

Use two indexes that move toward each other (or in the same direction). Great for sorted lists and reversing.

def is_palindrome(s): left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True print(is_palindrome("racecar")) # True

šŸ’” When to reach for it

Two pointers turn many O(n²) "check every pair" problems into O(n).

🪟 Pattern 2: Sliding Window

Keep a "window" over part of a list and slide it along, updating a running total instead of recomputing from scratch.

def max_sum(nums, k): window = sum(nums[:k]) best = window for i in range(k, len(nums)): window += nums[i] - nums[i - k] # slide! best = max(best, window) return best print(max_sum([1, 4, 2, 10, 2], 2)) # 12

šŸ—‚ļø Pattern 3: Hash for Speed

When you find yourself searching "have I seen this before?", a set or dict turns that lookup into O(1).

def first_repeat(nums): seen = set() for n in nums: if n in seen: return n seen.add(n) return None

šŸŽ“ Your algorithm toolkit

  • Big-O — measure how an algorithm scales.
  • Recursion — solve a problem with smaller copies of itself.
  • Search & Sort — binary search, bubble/merge sort.
  • Stacks, Queues, Linked Lists — organize data your way.
  • Hash tables & Trees — instant lookups and branching data.
  • Patterns — two pointers, sliding window, hashing for speed.

šŸŽ‰ You've finished the Algorithms track. You now think like a real computer scientist!