📘 CodingMarble Learn

Algorithm Design Techniques

To design an algorithm, first specify the problem: the input data, the expected output and any conditions. Then write clear, finite steps in natural language, as a list, pseudocode or flowchart. Big problems are split top-down into smaller parts (stepwise refinement) or built bottom-up from small tested pieces. Classic techniques: brute force (try everything), divide and conquer (split, solve, combine; halving as in binary search and merge sort), greedy (take the best-looking choice each time; fast but not always optimal), dynamic programming (solve each small subproblem once and store it in a table) and backtracking (try a choice, undo it at a dead end). Choose the technique and data structures (arrays, stacks, binary trees) by checking correctness and efficiency (time complexity).

🎬 Step-by-step story

  1. First specify the problem. Input: 8 numbers. Output: the largest. Steps: check each box and keep the biggest so far.
  2. Divide and conquer: to find a number from 1 to 16, ask about the middle and throw away half. Only 4 questions.
  3. Greedy: always take the biggest coin that fits. It is fast, but for 6 with coins 1, 3, 4 it gives 3 coins, not the best 2.
  4. Dynamic programming: solve small amounts first and save each answer in a table. The table finds 6 = 3 + 3.
  5. Backtracking: walk a path; at a dead end, go back to the last choice and try another way, until you reach the exit.
  6. Your turn: choose an amount and coins. Predict: does greedy give the fewest coins? Compare with DP.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Why write input and output before coding?

If you do not know exactly what comes in and must come out, you cannot test whether the steps are right.

How can 4 questions be enough for 16 numbers?

Each answer throws away half: 16, 8, 4, 2, 1. The greyed boxes show the half removed.

If greedy can be wrong, why use it?

It is very fast and simple, and for many problems (normal coins, earliest-ending activities) it is proven correct.

How is DP different from just trying everything?

It solves each small amount once and reuses it, so the table grows step by step instead of exploring every combination.

Does backtracking start again from the beginning?

No. It steps back only to the last junction with an untried way, then continues.

How do I know if greedy works for my coins?

Compare it with DP for many amounts. Try coins 1, 7, 10 in free play.

Specifying a problem: input, output and steps

Before writing any code, describe the problem exactly. This is the specification.

Writing the steps

An algorithm is a finite list of clear steps that turns any valid input into the right output. Write it as:

Test it by hand on small inputs, including tricky ones (all equal, negative numbers, only one number).

Top-down and bottom-up design

Top-down (stepwise refinement): start with the whole task, split it into a few big steps, then split each step again until each part is easy to code. Example: "Make a report card" → read marks → compute averages → assign grades → print.

Bottom-up: build and test small, reusable pieces first (a function that finds the maximum, one that sorts), then join them into the full program.

Real projects mix both: plan top-down, build and test bottom-up.

Divide and conquer, and the halving method

Divide and conquer has three moves: split the problem into smaller parts of the same kind, solve each part (often by recursion), combine the answers.

Greedy algorithms

A greedy algorithm makes the choice that looks best right now and never changes it.

But greedy is not always right: with coins 1, 3, 4, paying 6 greedily gives 4 + 1 + 1 (3 coins), while 3 + 3 uses 2. To trust a greedy method you must prove it, or test it against a sure method.

Dynamic programming and backtracking

Dynamic programming (DP)

When the same smaller problems repeat, solve each once and store the answer in a table. Fewest coins for amount a: best[a] = 1 + min(best[a - c]) over coins c ≤ a, starting from best[0] = 0. For coins 1, 3, 4: best = 0, 1, 2, 1, 1, 2, 2. Filling the table from small to large is bottom-up; recursion with a memory is top-down (memoization). See the separate Dynamic programming lesson for more.

Backtracking

Build a solution one choice at a time. If a choice breaks a rule or leads to a dead end, undo it and try the next option. Used for mazes, Sudoku, the N-queens puzzle and listing all subsets. It is a careful brute force: it skips whole branches that cannot work.

Brute force

Try every possible answer. Always correct, but often far too slow (2ⁿ subsets, n! orders).

Choosing a technique: correctness, efficiency and data structures

TechniqueUse whenExampleTypical time
Brute forceinput is tinytry all passwords of 3 digitsoften 2ⁿ or n!
Divide and conquerparts are independentbinary search, merge sortO(log n), O(n log n)
Greedya best local choice is proven safeactivity selection, changeO(n log n)
Dynamic programmingsubproblems repeatcoin change, shortest pathssize of table
Backtrackingsearch with rulesmaze, Sudokuexponential, but pruned

Justify it

Correctness: show the algorithm always stops and gives the right output (a loop invariant, a proof, or tests on edge cases). Efficiency: count steps as n grows (Big O) and compare with other methods.

Data structures help

Arrays for tables (DP), stacks for backtracking (remember where to go back), queues for level-by-level search. A binary tree stores items so that each node has at most two children; in a binary search tree smaller keys go left and larger go right, so searching halves the work at each level, just like binary search.

Try it: coins and a guessing game

  1. Play the 1-100 guessing game with a friend. Always ask about the middle. Can you always win in 7 questions? (2⁷ = 128.)
  2. With coins 1, 3, 4, write the DP table for amounts 0 to 10 on paper. Where does greedy fail?
  3. Open the last 3D step. Try coins 1, 7, 10 and amount 14. Greedy gives 10 + 1 + 1 + 1 + 1; DP gives 7 + 7.
  4. Write a step list for "find the smallest number in a list" and test it on 5, 5, 5 and on one number.

Key formulas and definitions

Worked examples

1. Write a specification and a step list for finding the largest of n numbers.

Input: n ≥ 1 numbers. Output: the largest. Steps: 1. best ← first number. 2. For each other number x: if x > best, best ← x. 3. Output best. For 4, 9, 2, 7, 12, 5, 10, 3 the output is 12 after 7 comparisons.

2. How many questions does halving need to find a number from 1 to 1000?

Each question halves the range: 1000 → 500 → 250 → 125 → 63 → 32 → 16 → 8 → 4 → 2 → 1. That is 10 questions (2¹⁰ = 1024 ≥ 1000).

3. Pay 87 greedily with coins 50, 20, 10, 5, 2, 1.

50 (37 left), 20 (17), 10 (7), 5 (2), 2 (0): 50 + 20 + 10 + 5 + 2 = 5 coins.

4. Fill the DP table for coins 1, 3, 4 up to amount 7.

best[0]=0, [1]=1, [2]=2, [3]=1, [4]=1, [5]=min(best4, best2, best1)+1=2, [6]=min(best5, best3, best2)+1=2, [7]=min(best6, best4, best3)+1=2 (3 + 4).

5. Activities (start-end): A 9-11, B 10-12, C 11-13, D 12-14, E 13-15. Choose the most activities that do not overlap.

Greedy by earliest end: A (ends 11), then C (starts 11, ends 13), then E (starts 13). 3 activities: A, C, E.

6. Plan top-down: a program that tells a class its average mark and the top student.

Level 1: read data → compute → print. Level 2: read names and marks into lists; compute total and average; find the maximum mark and its name; print both. Each piece is then coded and tested bottom-up.

Common mistakes

Practice quiz

1. A problem specification must state:
2. Binary search on 16 sorted items needs at most about:
3. Which technique always takes the best-looking choice now?
4. Dynamic programming works well when:
5. In a maze search, going back to the last junction after a dead end is:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What are the main algorithm design techniques?

Brute force, divide and conquer, greedy, dynamic programming and backtracking, chosen after specifying input and output.

What is the difference between greedy and dynamic programming?

Greedy makes one best-looking choice at each step and never looks back. DP considers all choices for small subproblems and stores the best answers, so it finds the true optimum when subproblems overlap.

What is top-down vs bottom-up design?

Top-down splits the whole task into smaller steps; bottom-up builds and tests small parts first and joins them. Most programs use both.

Where this is taught

PolandSzkoła podstawowa, klasa VIIUnderstanding, analysing and solving problems
PolandSzkoła podstawowa, klasa VIIIUnderstanding, analysing and solving problems
PolandLiceum ogólnokształcące, klasa IUnderstanding, analysing and solving problems
China高三Electives (选修)

Learn first

Learn next

Related lessons

All Computer Science lessons