Learn / Lesson 10 of 10
How to approach any problem
A six-step method to go from a blank editor to a working answer.
Words on this page, in plain English (24)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Boolean (true or false)
- A value that can only be
trueorfalse. Like a light switch: on or off. - Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- Length
- How many items a list (or letters a string) has. The last position is always
length - 1. - If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Function
- A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
- Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Map
- A lookup table: it stores pairs of a key and a value, and finds any key instantly. Like a coat check: hand over a ticket, get your coat straight back.
- Hash, hashing
- A quick calculation that turns a key into a shelf number, so a Map can jump straight to it instead of searching.
- Algorithm
- A step-by-step method for solving a problem. A recipe is an algorithm for a cake.
- Pattern
- A trick that solves a whole family of problems. Learn the trick once, and you can solve problems you've never seen.
- Template
- The usual shape of a pattern's code. You fill in the parts that change for each problem.
- Brute force (the slow way)
- Trying every possibility, one by one. It's usually easy to write and correct, but slow on big inputs.
- Big O
- A way to say how much slower code gets as the input grows. It's about the trend, not exact seconds.
- O(n²): quadratic time
- Twice the items means four times the work. Usually a loop inside a loop. Fine for 100 items, painful for 100,000.
- Pointer
- A variable that holds a position in a list, like a finger resting on one item.
leftandrightare pointers. - Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
- Window
- A stretch of items next to each other in a list, from a
leftposition to arightone. - Stack
- A pile where you only touch the top: add with
push, take withpop. The last thing in is the first out, like a pile of plates. - Test
- An example input with the answer it should give. Your code passes if it gives that answer.
- Bug, debugging
- A bug is a mistake in code. Debugging is finding it, often by printing values with
console.log.
Don't start by typing
The most common mistake with a new problem is jumping straight into code. Experienced developers spend most of their time thinking first, and the code comes quickly after. Here's a six-step method that works for almost any problem. Every walkthrough on this site follows it.
1. Understand: say it in your own words
Read the problem twice. Then answer:
- What exactly goes in? (A list of numbers? Can it be empty? Negative?)
- What exactly comes out? (A number? Positions?
true/false?) - What are the rules? (Can an item be used twice? Is the list sorted?)
If you can't explain the problem to a friend in two sentences, you're not ready to code it yet.
2. Examples: solve it by hand
Take a small example and solve it on paper, slowly, noticing what your brain does. Then try the awkward cases: an empty list, one item, all the same, the answer at the very start or very end.
Your hand-solving is often the algorithm in disguise. When you catch yourself thinking "I need the partner of this number" or "throw away the smaller one", write it down.
3. Brute force: the simplest thing that works
Write down the most obvious solution, even if it's slow: try every pair, check every stretch. Then work out its Big O.
- It gives you a correct answer to compare against.
- Its weak spot shows you what to speed up.
- In an interview, a working slow solution beats an unfinished clever one.
4. Spot the pattern: find the clue
Look at what makes the brute force slow, and at the problem's clues:
| Clue | Pattern to try |
|---|---|
| "find a pair / duplicate", "have I seen this?" | Hashing |
| sorted list, pairs, compare from both ends | Two pointers |
| best stretch of items next to each other | Sliding window |
| sorted, or "smallest value that works" | Binary search |
| matching pairs, undo, "next bigger" | Stack |
The Patterns page lists every pattern with its "spot it when" clue.
5. Code it: small, clear steps
Now write the code, translating your plan line by line. Use clear names (partner, not x). Split tricky parts into helper functions. Don't optimise anything you don't need to.
6. Check it: run, then test the edges
Run the examples. Then check the awkward cases from step 2. When something fails:
- Read the failing test's input, expected answer and your answer.
- Add
console.logto see what your variables really are. - Trace the code by hand with that exact input.
Try it: debugging with console.log
// This should return the position of the largest number, but something is off.
function biggestAt(nums) {
let best = 0;
for (let i = 1; i < nums.length; i++) {
console.log("i =", i, "nums[i] =", nums[i], "best =", best);
if (nums[i] > best) best = i;
}
return best;
}
console.log(biggestAt([3, 9, 4, 1]));Press Run to see the output. You can change the code first.
The logs show the bug: best is a position, but the code compares it with a value. The fix is if (nums[i] > nums[best]). Try it!
Putting it together
Try the whole method on your first real problem, Pair to target:
- Understand: positions of two different items adding to a budget.
- Examples:
[3, 8, 5, 2]with budget 10. By hand: for each price, look for its partner. - Brute force: check every pair, O(n²).
- Pattern: "have I seen this partner already?" is hashing.
- Code it with a Map.
- Check it with repeated prices and negatives.
Stuck? Each problem has hints that unlock one at a time, and a full walkthrough. Reading a walkthrough after a real attempt is one of the best ways to learn.
Practise: spot the pattern
Step 4 is the one that improves fastest with practice. Below are a few real problems from this site, from mixed patterns. For each, pick the pattern, then say the key idea out loud before you check it.
Problem 1 of 5
Spot the pattern
Pair to target
You have a gift card worth exactly budget, and you want to spend all of it on two different items.
Given a list of item prices and the budget, return the positions of the two items whose prices add up to exactly budget.
Positions start at 0, so the first item is at position 0. You can return the two positions in either order.
Which pattern?
Every problem page also has a Break it down tab that walks you through all six steps for that problem: you write your answer to each question, then compare it with ours.
Make it stick
Understanding a solution today doesn't mean you can write it next week. Memory researchers keep finding the same two things:
- Pulling something out of memory strengthens it far more than reading it again. Struggling to remember is the workout.
- Spacing it out works better than cramming. Review after a day, then a few days, then a week, each time just before you'd forget.
So the site helps you do both. Every pattern page ends with Learn it by heart: each template in four steps (read it, put its shuffled lines in order, fill in missing lines, write it all from memory). Every problem has the same drill for its solution, and the animations have a Guess each step first switch, so you predict what the code does before you see it. Your results go to the Review page, which brings each one back at the right time.
What you learned
- Understand the problem in your own words.
- Solve examples by hand, including awkward ones.
- Write the brute force and its Big O.
- Spot the pattern from the clues.
- Code it in small, clear steps.
- Check it, and debug with
console.log. - Make it stick by recalling the code from memory, spaced out over days.