Skip to content

Module 18 · Algorithms and Problem Solving — topic 18 of 18

Common problem-solving patterns

Reusable patterns for solving problems: brute force, hashing, prefix sums, greedy choices, divide and conquer, recursion with memoisation (dynamic programming), and how to recognise which pattern fits.

Beginner 12 min read·Lesson 278 of 306 in Python Programming

Learning objectives

  • Name and apply common algorithmic patterns
  • Recognise clues that suggest each pattern
  • Compare brute-force and optimised solutions

Definition

Problem-solving patterns are general strategies that apply to many different problems. Recognising which pattern fits a new problem is often the key step towards an efficient solution.

Introduction

Experienced programmers rarely invent solutions from scratch. They recognise that a new problem looks like one they've solved before and apply a familiar pattern.

Why it matters

Learning a handful of patterns makes unfamiliar problems approachable and is the core of preparing for coding interviews and competitions.

Detailed explanation

Brute force tries every possibility. It's a correct baseline and fine for small inputs.

Hashing (sets and dictionaries) answers 'have I seen this?' or 'how many?' in O(1), replacing inner loops — clue: duplicates, pairs, counts.

Prefix sums precompute running totals so any range sum is one subtraction — clue: many range queries on fixed data.

Greedy algorithms make the locally best choice at each step (largest coin first). They are fast but only correct when the problem has the right structure.

Divide and conquer splits the problem, solves parts recursively and combines them — clue: the answer for the whole follows from answers for halves (merge sort, binary search).

Dynamic programming solves overlapping subproblems once and reuses the results, via memoisation (lru_cache) or a table — clue: a recursive solution that repeats the same calls.

Two pointers, sliding windows, stacks, queues and BFS (earlier lessons) are patterns too.

To choose: look at the constraints (input size), the structure (sorted? nested? ranges?) and the question (count, best, exists?).

Syntax

Text
# hashing: seen = set()
# prefix sums: prefix[i + 1] = prefix[i] + nums[i]
# greedy: take the best option now
# divide: solve halves, combine
# memoise: @functools.lru_cache
  • Start with brute force.
  • Look for clues in the problem.
  • Pick the pattern that removes repeated work.

Code examples

Hashing: first repeated element

Python
def first_repeat(xs):
seen = set()
for x in xs:
if x in seen:
return x
seen.add(x)
return None
print(first_repeat([3, 5, 1, 5, 3]), first_repeat([1, 2]))
Output
5 None

Prefix sums for range queries

Python
nums = [3, 1, 4, 1, 5, 9, 2]
prefix = [0]
for n in nums:
prefix.append(prefix[-1] + n)
def range_sum(i, j):
return prefix[j + 1] - prefix[i]
print(prefix, range_sum(2, 4), range_sum(0, 6))
Output
[0, 3, 4, 8, 9, 14, 23, 25] 10 25

More examples

Greedy, dynamic programming and divide and conquer

Python
from functools import lru_cache
def coin_change_greedy(amount, coins=(2000, 500, 200, 100, 50, 20, 10, 5, 2, 1)):
result = {}
for c in coins:
if amount >= c:
result[c], amount = divmod(amount, c)
return result
@lru_cache(maxsize=None)
def ways(n):
"""Ways to climb n stairs taking 1 or 2 steps at a time."""
return 1 if n <= 1 else ways(n - 1) + ways(n - 2)
def max_dc(xs):
if len(xs) == 1:
return xs[0]
mid = len(xs) // 2
return max(max_dc(xs[:mid]), max_dc(xs[mid:]))
print(coin_change_greedy(2786))
print(ways(10), ways(40))
print(max_dc([4, 17, 9, 23, 5]))
Output
{2000: 1, 500: 1, 200: 1, 50: 1, 20: 1, 10: 1, 5: 1, 1: 1}
89 165580141
23

Step-by-step explanation

  • Greedy change takes as many of the largest note as possible, which is optimal for the Indian rupee denominations.
  • ways(40) would take hundreds of millions of calls without memoisation; with lru_cache each value is computed once.
  • max_dc finds the maximum of each half and combines them — the shape of merge sort and many divide-and-conquer algorithms.

Expected output

Running “Greedy, dynamic programming and divide and conquer” prints exactly:

TextOutput
{2000: 1, 500: 1, 200: 1, 50: 1, 20: 1, 10: 1, 5: 1, 1: 1}
89 165580141
23

Practical applications

  • Caching and dynamic programming in route planning and text diffing.
  • Greedy scheduling and compression algorithms.

Best practices

  • Write a brute-force reference first.
  • Look for repeated work to eliminate.
  • Verify greedy choices with counterexamples.

Common mistakes

Greedy where it fails

Avoid

coin_change_greedy(6, coins=(4, 3, 1)) # 4 + 1 + 1 = three coins

Prefer

Use dynamic programming: 3 + 3 = two coins.

Greedy choices are only optimal for some coin systems; check before relying on them.

Important notes

  • This completes the Algorithms module; next comes debugging, testing and writing maintainable code.

Key takeaways

  • Brute force, hashing, prefix sums, greedy, divide and conquer, dynamic programming.
  • Clues in the problem suggest the pattern.
  • Remove repeated work to gain efficiency.

Try it yourself

  1. 1
    Solve 'minimum coins for an amount' with dynamic programming for any coin set.
  2. 2
    Use prefix sums to answer several 'total sales between day i and day j' queries.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is printed?
Practise this topic