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.
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!
š® Final Boss Challenges!
Use the patterns to slay these. š
š
Task 1: Palindrome with Two Pointers
Medium
Finish is_palindrome using two pointers moving inward. "racecar" ā True, "hello" ā False.
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"))
print(is_palindrome("hello"))
šŖ
Task 2: Best Window Sum
Challenge
Find the biggest sum of any k=2 neighbours in [1, 4, 2, 10, 2] using a sliding window. Answer: 12 (10 + 2).
def max_sum(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best
print(max_sum([1, 4, 2, 10, 2], 2))
šÆ
Task 3: First Repeated Number
Boss
Return the first number that appears twice in [5, 1, 4, 4, 2, 1] using a set for O(1) lookups. Answer: 4.
def first_repeat(nums):
seen = set()
for n in nums:
if n in seen:
return n
seen.add(n)
return None
print(first_repeat([5, 1, 4, 4, 2, 1]))