Lesson 41/48 ยท ๐ŸŽฏ Problem Solving
๐ŸŽฏ Problem SolvingLesson 41/48
Phase 6 ยท Problem Solving25 min

List Problems

Accumulator, two-pointer, and sliding window patterns

Three patterns cover the majority of list problems. Learn these shapes and you'll recognize them in interview questions, coding challenges, and real scripts.
Pattern 1: The AccumulatorBuild up a result by iterating through the list once.
Accumulator patternpython
# Running total
numbers = [1, 2, 3, 4, 5]
total = 0
for n in numbers:
    total += n
print(total)   # 15

# Running max
max_so_far = numbers[0]
for n in numbers[1:]:
    if n > max_so_far:
        max_so_far = n
print(max_so_far)   # 5
Pattern 2: Two PointersUse two indices moving toward each other (or in the same direction) to avoid nested loops.
Two-pointer: check if list is palindromepython
def is_palindrome_list(lst):
    left, right = 0, len(lst) - 1
    while left < right:
        if lst[left] != lst[right]:
            return False
        left += 1
        right -= 1
    return True

print(is_palindrome_list([1, 2, 3, 2, 1]))   # True
print(is_palindrome_list([1, 2, 3]))          # False
Pattern 3: Sliding WindowMaintain a "window" of fixed or variable size as you slide through the list.
Sliding window: max sum of k consecutive elementspython
def max_subarray_sum(nums, k):
    # Build initial window
    window_sum = sum(nums[:k])
    max_sum = window_sum

    # Slide the window
    for i in range(k, len(nums)):
        window_sum += nums[i] - nums[i - k]  # add new, remove old
        max_sum = max(max_sum, window_sum)

    return max_sum

print(max_subarray_sum([2, 1, 5, 1, 3, 2], 3))   # 9 (5+1+3)

How would you approach this? Think first, then expand.

Practice Exercises

0/3 solved
Exercise 1 of 3easy
โฑ 00:00

Running Average

Print the running average after each number is added.
Given: numbers = [4, 2, 8, 6]Expected output:4.03.04.675.0
solution.py
1 / 3
Exercise 2 of 3medium
โฑ 00:00

Find the Pair

Find two numbers in the list that add up to the target.
Given: nums = [2, 7, 11, 15], target = 9Expected output: Found: 2 + 7 = 9
solution.py
2 / 3
Exercise 3 of 3medium
โฑ 00:00

Rotate a List

Rotate a list right by k positions.
Given: nums = [1, 2, 3, 4, 5], k = 2Expected output: [4, 5, 1, 2, 3]
(Last 2 elements move to the front)
solution.py
3 / 3
Solve all 3 exercises to unlock completion