Algorithm Thinking
Develop the mindset for designing algorithms — step-by-step recipes that solve problems efficiently and correctly.
What you'll learn
- What an algorithm is and how it differs from code
- How to design step-by-step solutions to problems
- The importance of correctness and efficiency
- Common algorithm patterns: search, sort, accumulate
- How to verify your algorithm works before coding
Concept
Algorithm Thinking
An algorithm is a precise, step-by-step procedure for solving a problem. It is the recipe behind the code — the logic that determines *what* to do, independent of *which language* you write it in. Algorithm thinking is the skill of designing these procedures: breaking a problem into clear, ordered, finite steps that are guaranteed to produce the correct result.
Algorithm vs. Code
An algorithm is an idea; code is an implementation. The algorithm for finding the largest number in a list is: "look at each number, keep track of the largest so far." That algorithm can be implemented in JavaScript, Python, Java, or any language. The algorithm is the same; only the syntax differs. This is why algorithm thinking is a language-independent skill — it transfers everywhere.
Properties of a Good Algorithm
Every algorithm must have these properties:
- Finiteness — it terminates after a finite number of steps. No infinite loops.
- Definiteness — each step is precisely defined. No ambiguity.
- Input — it accepts zero or more inputs.
- Output — it produces at least one output.
- Effectiveness — each step is basic enough to be carried out mechanically.
Common Patterns
Most algorithms you will write fall into a few recognizable patterns:
- Linear search — look at each item one by one until you find the target. Simple but slow for large lists.
- Accumulation — iterate through a collection, building up a running result (sum, count, maximum, concatenation).
- Filtering — iterate and select only items that pass a condition.
- Sorting — arrange items in order (alphabetical, numerical, by a custom key).
- Divide and conquer — split the problem into smaller subproblems, solve each, and combine the results.
Recognizing which pattern fits your problem is the core of algorithm thinking. Once you identify the pattern, the implementation often follows naturally.
Correctness
An algorithm is correct if it produces the right output for every valid input. Verifying correctness means thinking about edge cases: empty inputs, single-element inputs, duplicate values, already-sorted data, reverse-sorted data. A common technique is to trace the algorithm by hand on a small example, writing down the state at each step, and confirming the final output matches the expected result.
Efficiency
Two algorithms can both be correct but differ wildly in speed. Finding a name in an unsorted list by checking each entry takes, on average, N/2 steps. If the list is sorted, binary search takes about log₂(N) steps — for a million entries, that is 20 steps instead of 500,000. Efficiency is the subject of the next lesson (time complexity), but the intuition starts here: always ask "is there a faster way?"
The Design Process
- Understand the problem — what is the input? What is the expected output? What are the constraints?
- Identify the pattern — is this a search, a sort, an accumulation, a transformation?
- Sketch the steps — in pseudocode or a flowchart.
- Trace it by hand — run through a small example to verify.
- Consider edge cases — empty input, single item, duplicates, worst case.
- Implement — translate to code.
- Test — verify with real inputs, including the edge cases.
This process turns "I have no idea where to start" into a systematic approach. The first few steps are thinking, not typing — and that is where most of the value is.
Example
// Algorithm: Find the two largest numbers in an array.
// Pattern: Accumulation (track top values while iterating)
// --- Design ---
// Input: array of numbers
// Output: [largest, secondLargest]
// Steps:
// 1. Initialize largest and secondLargest to -Infinity
// 2. For each number in the array:
// a. If number > largest:
// secondLargest = largest
// largest = number
// b. Else if number > secondLargest:
// secondLargest = number
// 3. Return [largest, secondLargest]
function findTopTwo(numbers) {
if (numbers.length < 2) {
throw new Error("Need at least two numbers");
}
let largest = -Infinity;
let secondLargest = -Infinity;
for (const n of numbers) {
if (n > largest) {
secondLargest = largest; // demote current largest
largest = n; // promote new largest
} else if (n > secondLargest) {
secondLargest = n; // update second place only
}
}
return [largest, secondLargest];
}
// Trace: [3, 7, 2, 9, 5]
// n=3: largest=3, second=-Inf
// n=7: largest=7, second=3
// n=2: 2 < 7, 2 > 3? No → no change
// n=9: largest=9, second=7
// n=5: 5 < 9, 5 > 7? No → no change
// Result: [9, 7] ✓
console.log(findTopTwo([3, 7, 2, 9, 5])); // [9, 7]
console.log(findTopTwo([10, 10, 5])); // [10, 10]
This algorithm finds the top two values in a single pass — O(n) time. The trace in comments verifies the logic step by step. The edge case (fewer than 2 elements) is handled with an explicit error.
Try it
- Text Sorter
Sorting is a classic algorithm. Try different sort orders and think about what algorithm the tool uses internally.
- Line Deduplicator
Removing duplicates is an algorithm problem. This tool implements it — think about how you would design it yourself.
Common mistakes
The mistake
Starting to code before understanding the problem fully.
The fix
Write down the input, output, and constraints first. If you cannot state the problem clearly in one sentence, you do not understand it well enough to solve it. Clarity of problem definition is half the solution.
The mistake
Not tracing the algorithm by hand before coding.
The fix
Pick a small input (3-5 items) and walk through each step on paper, writing down every variable's value. This catches logic errors in minutes instead of debugging for hours after the code is written.
The mistake
Ignoring edge cases like empty arrays or single-element inputs.
The fix
Always ask: what happens with 0 items? 1 item? All identical items? Already sorted? Reverse sorted? These cases are where correct algorithms fail and buggy ones crash.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Reference for loops and array methods used to implement algorithms.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.