Practical problem solving
A repeatable process for turning a vague problem into a correct, tested solution.
- Restate the problem and name the inputs and outputs.
- Solve a tiny example by hand before coding.
- Read the constraints to pick an approach that is fast enough.
- Test empty, single, duplicate and large inputs.
In plain English
Restating the problem in your own words confirms you understand the input, the output and the goal before you write anything. Working through examples by hand, including tiny ones, reveals the pattern and gives you test cases. Constraints are the stated limits on input size and values, and they tell you which algorithm is fast enough and which edge cases to expect. A brute force solution tries the most direct approach without worrying about speed, and it is the right first step because it proves you understand the problem and gives you something to check against. Edge cases are the unusual inputs such as empty lists, single elements, duplicates and large values, and testing them catches the bugs a happy-path example misses.
Step by step
- 1Restate the problem in one sentence and name the inputs and output.
- 2Trace a tiny example by hand to find the pattern.
- 3Write the straightforward brute force version first.
- 4Read the constraints and decide whether to optimise.
- 5Run empty, single, duplicate and large inputs through the code.
function largestProduct(numbers) {
if (numbers.length < 2) return 0
let max = numbers[0] * numbers[1]
for (let i = 0; i < numbers.length; i++) {
for (let j = i + 1; j < numbers.length; j++) {
const product = numbers[i] * numbers[j]
if (product > max) max = product
}
}
return max
}
console.log(largestProduct([3, 1, 4, 2]))
console.log(largestProduct([5]))
console.log(largestProduct([]))Common mistakes
- Skipping the restatement leads to solving the wrong problem, which wastes every later step.
- Jumping to a clever optimisation before a brute force is risky, because you have nothing correct to compare against.
- Ignoring constraints can make you pick an algorithm that is far too slow for the largest input.
- Testing only the happy path misses empty lists, single elements and duplicates, which is where most bugs live.
Handle the empty case
Finish the function so it returns 0 for an empty or single-element list and otherwise returns the largest product of two numbers.
function largestProduct(numbers) {
}Why write a brute force solution first?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.