Brute-force
Solving problems by trying all possible candidates, with nine worked examples and a complexity guide for estimating feasibility.
The Core Idea
Every brute force solution follows the same structure:
- Define the search space — what are all possible answers?
- Iterate over it — one or more loops
- Check each candidate — does it satisfy the problem's conditions?
- Track the best/first/count — depending on what the problem asks
It is simple to implement but can be slow, so we use it only when the search space is small enough to scan entirely within the time limit.
Example 1: Maximum Sum Subarray of Length K
Given a list of integers and a number , find the maximum sum of any contiguous subarray of length exactly .
Search space: all starting indices from to .