Skip to lesson

Start with brute force

A brute-force solution solves a problem in the most direct way possible: it generates every candidate answer and checks which one satisfies the rules. Starting with brute force gives you a working baseline before you try anything clever.

What brute force means

Brute force is the simplest solution that tries every possibility. It is usually slow, but it is easy to write, easy to trust and a good starting point.

Imagine you have a ring of ten keys and one locked door. The brute-force way to open the door is to try key 1, then key 2, then key 3, until the lock turns. There is no trick—just systematic, complete checking.

Example 1 · Brute force over all pairs: maximum product of two distinct elements

BruteForcePairsDemo.javaJava
public class BruteForcePairsDemo {    // nums[i] * nums[j] for two distinct indices i < j.    public static int maxPairProduct(int[] nums) {        int best = nums[0] * nums[1];        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < nums.length; j++) {                int product = nums[i] * nums[j];                if (product > best) {                    best = product;                }            }        }        return best;    }
    public static void main(String[] args) {        System.out.println("Positive max : " + maxPairProduct(new int[]{3, 7, 2, 5}));        // Tricky case: two negative numbers multiply to a large positive number!        System.out.println("With negatives: " + maxPairProduct(new int[]{-10, -8, 4, 6}));    }}
Output
Positive max : 35
With negatives: 80

What this code does

  • Because brute force checks every pair, it automatically checks (-10) * (-8) = 80 without needing special negative-number branches.
  • Initializing best = nums[0] * nums[1] guarantees we start from a real pair product even if all products are negative.

In programming, a brute-force solution translates the problem rules directly into loops and if statements. It does not skip any possibilities, which makes it easy to reason about and verify.

In practice: If the problem asks for the best single item, brute force checks every item. If the problem asks for the best pair of items, brute force checks every pair (i, j). If the problem asks for the best contiguous slice (a subarray), brute force checks every (start, end) range.

Never stay silent because you cannot see the clever trick yet. State the brute-force idea out loud first.

Trying every option with loops

Most array and string brute-force solutions use one of three loop patterns. Knowing these three shapes lets you write a working brute-force method in under two minutes.

  1. Every single element: one loop for (int i = 0; i < n; i++).
  2. Every distinct pair: outer loop i from 0 to n - 1, inner loop j from i + 1 to n - 1.
  3. Every subarray: outer loop start from 0 to n - 1, inner loop end from start to n - 1.

Brute force: try every pair

Step 1 of 7

Array: 3, 7, 2, 5.
best
21
Goal: the largest product of two different elements of {3, 7, 2, 5}. Brute force will test all 6 pairs. best starts as the first pair product, 21.

Example 2 · Brute force over all subarrays: longest contiguous run of 1s

BruteForceSubarraysDemo.javaJava
public class BruteForceSubarraysDemo {    // Brute force: try every subarray [start..end] and check if it contains only 1s.    // Cost: O(n^2) subarrays checked.    public static int longestOnesBruteForce(int[] bits) {        int maxLen = 0;        for (int start = 0; start < bits.length; start++) {            for (int end = start; end < bits.length; end++) {                if (bits[end] == 0) {                    break; // Any longer subarray from this start will also contain this 0                }                int currentLen = end - start + 1;                if (currentLen > maxLen) {                    maxLen = currentLen;                }            }        }        return maxLen;    }
    public static void main(String[] args) {        System.out.println("Mixed : " + longestOnesBruteForce(new int[]{1, 1, 0, 1, 1, 1, 0, 1}));        System.out.println("All 0s: " + longestOnesBruteForce(new int[]{0, 0, 0}));    }}
Output
Mixed : 3
All 0s: 0

What this code does

  • The outer loop picks start and the inner loop extends end one element at a time.
  • Notice the repeated work: when bits has a long run of 1s, the inner loop re-scans the same 1s from start = 0, start = 1, start = 2, and so on.

A subarray is a contiguous (unbroken) slice of an array from index start to index end. By fixing start in an outer loop and moving end forward in an inner loop, you visit every possible subarray cleanly.

Why a correct slow answer is still valuable

Beginners often think brute force is 'wrong' because a faster algorithm exists. In reality, a correct brute-force solution has three practical benefits.

Example 3 · Brute force: best stock trade (O(n²) time, O(1) space)

StockBruteForceDemo.javaJava
public class StockBruteForceDemo {    // Time O(n^2), extra space O(1): every buy day against every later sell day.    public static int maxProfit(int[] prices) {        int best = 0;        for (int buy = 0; buy < prices.length; buy++) {            for (int sell = buy + 1; sell < prices.length; sell++) {                best = Math.max(best, prices[sell] - prices[buy]);            }        }        return best;    }
    public static void main(String[] args) {        System.out.println("Profit: " + maxProfit(new int[]{7, 1, 5, 3, 6, 4}));        System.out.println("Profit: " + maxProfit(new int[]{9, 7, 4, 2}));    }}
Output
Profit: 5
Profit: 0

What this code does

  • Every buy day is paired with every later sell day, so n(n - 1) / 2 pairs are tested: O(n²) time and O(1) extra space.
  • It is easy to trust, but for each sell day it scans all earlier days again just to find the cheapest buy price. That repeated work is what the next step removes.

Example 4 · Better: remember the lowest price so far (O(n) time, O(n) space)

StockBetterDemo.javaJava
public class StockBetterDemo {    // Time O(n), extra space O(n): lowestUpTo[i] is the cheapest price on days 0..i.    public static int maxProfit(int[] prices) {        if (prices.length == 0) {            return 0;        }        int[] lowestUpTo = new int[prices.length];        lowestUpTo[0] = prices[0];        for (int i = 1; i < prices.length; i++) {            lowestUpTo[i] = Math.min(lowestUpTo[i - 1], prices[i]);        }        int best = 0;        for (int sell = 1; sell < prices.length; sell++) {            best = Math.max(best, prices[sell] - lowestUpTo[sell - 1]);        }        return best;    }
    public static void main(String[] args) {        System.out.println("Profit: " + maxProfit(new int[]{7, 1, 5, 3, 6, 4}));        System.out.println("Profit: " + maxProfit(new int[]{9, 7, 4, 2}));    }}
Output
Profit: 5
Profit: 0

What this code does

  • lowestUpTo[i] is built once in a single pass. Each sell day then reads its cheapest earlier price from the array instead of rescanning.
  • That removes the inner loop, so time drops from O(n²) to O(n), but the extra array costs O(n) space. Do we really need the whole array?

Example 5 · Optimal: one running minimum (O(n) time, O(1) space)

StockOptimalDemo.javaJava
public class StockOptimalDemo {    // Time O(n), extra space O(1): one running minimum replaces the whole array.    public static int maxProfit(int[] prices) {        if (prices.length == 0) {            return 0;        }        int minBuy = prices[0];        int best = 0;        for (int i = 1; i < prices.length; i++) {            best = Math.max(best, prices[i] - minBuy);            minBuy = Math.min(minBuy, prices[i]);        }        return best;    }
    // The slow version from before, kept as a test oracle.    public static int maxProfitBruteForce(int[] prices) {        int best = 0;        for (int i = 0; i < prices.length; i++) {            for (int j = i + 1; j < prices.length; j++) {                best = Math.max(best, prices[j] - prices[i]);            }        }        return best;    }
    public static void main(String[] args) {        int[][] tests = {{7, 1, 5, 3, 6, 4}, {9, 7, 4, 2}, {3, 3, 3}};        for (int[] t : tests) {            int oracle = maxProfitBruteForce(t);            int fast = maxProfit(t);            System.out.println("Oracle=" + oracle + " Fast=" + fast + " Match=" + (oracle == fast));        }    }}
Output
Oracle=5 Fast=5 Match=true
Oracle=0 Fast=0 Match=true
Oracle=0 Fast=0 Match=true

What this code does

  • Only the newest lowest price is ever used, so a single variable minBuy replaces the whole array. Time stays O(n) and extra space falls to O(1).
  • The slow maxProfitBruteForce stays as a test oracle: if the fast method ever disagrees with it on a small input, the fast method has the bug.

First, when the maximum input size n is small (such as n ≤ 200), a nested loop runs in less than a millisecond in Java 17 and passes every test. Second, in an interview, stating a correct brute-force idea earns partial credit immediately and proves you understand the rules. Third, you can use your brute-force method as a test oracle—a trusted slow method whose output you compare against your faster method on small inputs.

The three benefits in short: Small constraints (n <= 100): brute force is often the smartest code to write and ship. Partial credit: a working slow solution beats an unfinished, broken optimal attempt. Test oracle: if fastMethod(arr) and bruteForce(arr) disagree on a 5-element array, you immediately have a tiny input to debug.

Saying why the brute force is slow

Explaining why brute force is slow takes three short sentences: count the steps, plug in the limit, and name the repeated work.

Example 6 · Counting the exact number of inner-loop checks as n grows

CountBruteForceStepsDemo.javaJava
public class CountBruteForceStepsDemo {    public static long countPairChecks(int n) {        long checks = 0;        for (int i = 0; i < n; i++) {            for (int j = i + 1; j < n; j++) {                checks++;            }        }        return checks;    }
    public static void main(String[] args) {        System.out.println("n = 10   -> checks = " + countPairChecks(10));        System.out.println("n = 100  -> checks = " + countPairChecks(100));        System.out.println("n = 1000 -> checks = " + countPairChecks(1000));    }}
Output
n = 10   -> checks = 45
n = 100  -> checks = 4950
n = 1000 -> checks = 499500

What this code does

  • When n grows 10× (from 100 to 1000), the number of pair checks grows roughly 100× (from 4,950 to 499,500).
  • The exact formula is n(n - 1) / 2, which is why we say the work grows with n².

Checking every pair of n elements takes about n²/2 steps: the first element meets n - 1 others, the second n - 2, and so on. For n = 100,000 that is about 5 billion checks, which takes several seconds and misses a typical one-second limit.

Say it in this order. Count the steps: "each of the n elements scans up to n others". Plug in the limit: "n = 100,000 means about 10 billion steps, too slow". Name the repeated work: "we keep rescanning the rest of the array to ask the same lookup question".

Predict the output

Count the checks

Read each program and pick how many checks it prints.

Round 1 of 3

Pairs of 4 items, with j after i.

public class CountA {
public static void main(String[] args) {
int n = 4;
int checks = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
checks++;
}
}
System.out.println(checks);
}
}

Next step

Check your understanding

10 quick questions