Skip to lesson

Brute Force First, Then Improve

Most coding questions have an obvious slow answer and a smarter one, and the interviewer wants to hear you walk from one to the other. They are checking that you can see where the work repeats and name what each improvement costs.

Why stating brute force earns credit

A brute force is the simplest correct approach, usually trying every possibility, with a complexity you can state in one sentence.

Stating the slow answer first takes thirty seconds and earns credit. Example 1 uses it as a checker: an O(n²) maximum-subarray against Kadane's O(n) on 500 random arrays.

Example 1 · Brute force as a test oracle

OracleDemo.javaJava
import java.util.Random;
public class OracleDemo {    // Brute force: try every subarray, O(n²)    static int maxSubarrayBrute(int[] a) {        int best = Integer.MIN_VALUE;        for (int i = 0; i < a.length; i++) {            int sum = 0;            for (int j = i; j < a.length; j++) {                sum += a[j];                best = Math.max(best, sum);            }        }        return best;    }
    // Kadane: best sum ending here, O(n)    static int maxSubarrayKadane(int[] a) {        int best = a[0];        int current = a[0];        for (int i = 1; i < a.length; i++) {            current = Math.max(a[i], current + a[i]);            best = Math.max(best, current);        }        return best;    }
    public static void main(String[] args) {        System.out.println("Example: " + maxSubarrayKadane(new int[] {-2, 1, -3, 4, -1, 2, 1, -5, 4}));        Random random = new Random(42);        int agree = 0;        for (int t = 0; t < 500; t++) {            int[] a = new int[1 + random.nextInt(12)];            for (int i = 0; i < a.length; i++) {                a[i] = random.nextInt(21) - 10;            }            if (maxSubarrayBrute(a) == maxSubarrayKadane(a)) {                agree++;            }        }        System.out.println("Agree on " + agree + " of 500 random arrays");    }}
Output
Example: 6
Agree on 500 of 500 random arrays

What this code does

  • The brute force is easy to trust because it literally tries every subarray; the fixed seed makes the random tests repeatable.
  • If the optimized version had a bug, for example starting best at 0, all-negative arrays would make the counts disagree.

Saying the brute force first proves you understand the problem and gives the interviewer a correct baseline, even if time runs out: "Check every pair, O(n²) time, O(1) space. That is too slow for n = 10⁵, so let me improve it." Revise: Brute force first (opens in a new tab)

The same brute force is also a test oracle: a slow but trusted answer to compare a fast solution against. Code it in full only if the interviewer asks, or if you see no improvement.

The five optimization levers

An optimization lever is a standard technique that removes repeated work from a brute force: hashing, sorting, two pointers, prefix sums or binary search.

A brute force often adds up the same numbers again and again. Example 2 answers four range-sum queries by re-adding, then with prefix sums, and counts the additions.

Example 2 · Prefix sums remove repeated work

PrefixSumLeverDemo.javaJava
public class PrefixSumLeverDemo {    public static void main(String[] args) {        int[] runs = {5, 3, 8, 6, 2, 7};             // runs scored per over        int[][] queries = {{0, 2}, {1, 4}, {3, 5}, {0, 5}};
        int bruteSteps = 0;        StringBuilder brute = new StringBuilder("Brute:  ");        for (int[] q : queries) {            int sum = 0;            for (int i = q[0]; i <= q[1]; i++) {                sum += runs[i];                bruteSteps++;            }            brute.append(sum).append(' ');        }
        int[] prefix = new int[runs.length + 1];      // prefix[i] = sum of first i overs        for (int i = 0; i < runs.length; i++) {            prefix[i + 1] = prefix[i] + runs[i];        }        StringBuilder fast = new StringBuilder("Prefix: ");        for (int[] q : queries) {            fast.append(prefix[q[1] + 1] - prefix[q[0]]).append(' ');        }
        System.out.println(brute.toString().trim() + " (" + bruteSteps + " additions)");        System.out.println(fast.toString().trim() + " (" + runs.length + " additions + 1 subtraction per query)");    }}
Output
Brute:  16 19 15 31 (16 additions)
Prefix: 16 19 15 31 (6 additions + 1 subtraction per query)

What this code does

  • The brute force re-adds the same overs for every query: O(n) per query, O(n · q) in total.
  • Prefix sums do the adding once, then each range sum is one subtraction: O(n + q). For n = q = 10⁵ that is about 2 × 10⁵ steps instead of up to 10¹⁰.

Look for the repeated work first, then pick the lever that removes it. These five cover most fresher and product-company problems:

  • Hashing (HashMap/HashSet): replaces an inner search loop with an O(1) lookup. "Have I seen x?", counts, complements.
  • Sorting: O(n log n) once, then neighbours, duplicates and order become easy.
  • Two pointers / sliding window: on sorted data or contiguous ranges, move two indexes instead of nested loops.
  • Prefix sums for repeated range sums; binary search for sorted data or a yes/no answer that flips once.

Revise: Brute force to optimal (opens in a new tab), then prefix sum arrays (opens in a new tab).

Predict the output

Pick the lever

Read each brute force, find the repeated work and choose the lever that removes it.

Round 1 of 2

Which lever removes the inner loop?

static boolean hasPair(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] + a[j] == target) return true;
}
}
return false;
}
Repeated range sums → prefix sums. "Does a complement exist?" → hashing. Sorted input → two pointers or binary search.

Talking through the trade-off as you improve

A trade-off is what an improvement costs: extra memory, a changed input, lost indices or code that is harder to get right.

Every improvement costs something. Example 3 solves "contains duplicate" three ways, and each way pays a different price in time, memory or the input itself.

Example 3 · Three answers to "contains duplicate", three trade-offs

TradeOffDemo.javaJava
import java.util.Arrays;import java.util.HashSet;import java.util.Set;
public class TradeOffDemo {    // O(n²) time, O(1) extra space, input unchanged    static boolean bruteForce(int[] a) {        for (int i = 0; i < a.length; i++) {            for (int j = i + 1; j < a.length; j++) {                if (a[i] == a[j]) return true;            }        }        return false;    }
    // O(n log n) time, little extra space, but it sorts (changes) the array    static boolean sortFirst(int[] a) {        Arrays.sort(a);        for (int i = 1; i < a.length; i++) {            if (a[i] == a[i - 1]) return true;        }        return false;    }
    // O(n) time, O(n) extra space, input unchanged    static boolean hashSet(int[] a) {        Set<Integer> seen = new HashSet<>();        for (int x : a) {            if (!seen.add(x)) return true;        }        return false;    }
    public static void main(String[] args) {        int[] rolls = {41, 17, 23, 17, 8};        System.out.println("brute: " + bruteForce(rolls) + ", hash: " + hashSet(rolls));        int[] copy = rolls.clone();        System.out.println("sort:  " + sortFirst(copy) + ", array now " + Arrays.toString(copy));        System.out.println("original still " + Arrays.toString(rolls));    }}
Output
brute: true, hash: true
sort:  true, array now [8, 17, 17, 23, 41]
original still [41, 17, 23, 17, 8]

What this code does

  • All three are correct; they differ in time, extra memory and whether the input is changed. Saying that aloud is the trade-off discussion.
  • Sorting a clone() keeps the caller's array intact, at the cost of O(n) memory again, which is worth mentioning too.

Name the cost as you go: "A HashSet makes it O(n) time but O(n) extra space." "Sorting gives O(n log n) and little extra space, but it changes the array and loses the original indices." Interviewers want to hear that you see both sides.

Then say which cost matters more: memory, keeping the input unchanged, or speed. A short sentence like "if memory is tight I would sort instead" shows judgement and often answers the next question before it is asked.

Order of execution

Talk through an improvement

Put the spoken steps in the order that sounds strongest.

Worked example: pair sum from O(n²) to O(n)

Pair sum goes from O(n²) to O(n) in two different ways. Example 4 counts the checks each solution makes on 2,000 numbers with no valid pair, then confirms all three find the same pair.

Example 4 · Pair sum: counting the work of three solutions

PairSumStepsDemo.javaJava
import java.util.Arrays;import java.util.HashSet;import java.util.Set;
public class PairSumStepsDemo {    static long checks;
    static String brute(int[] a, int target) {        for (int i = 0; i < a.length; i++) {            for (int j = i + 1; j < a.length; j++) {                checks++;                if (a[i] + a[j] == target) return a[i] + "+" + a[j];            }        }        return "none";    }
    static String twoPointers(int[] input, int target) {        int[] a = input.clone();        Arrays.sort(a);        int lo = 0, hi = a.length - 1;        while (lo < hi) {            checks++;            int sum = a[lo] + a[hi];            if (sum == target) return a[lo] + "+" + a[hi];            if (sum < target) lo++; else hi--;        }        return "none";    }
    static String hashing(int[] a, int target) {        Set<Integer> seen = new HashSet<>();        for (int x : a) {            checks++;            if (seen.contains(target - x)) return (target - x) + "+" + x;            seen.add(x);        }        return "none";    }
    public static void main(String[] args) {        int[] big = new int[2000];        for (int i = 0; i < big.length; i++) big[i] = 2 * i;   // all even: no pair sums to an odd target        checks = 0; brute(big, 1);       System.out.println("Brute force checks:  " + checks);        checks = 0; twoPointers(big, 1); System.out.println("Two pointer checks:  " + checks + " (after an O(n log n) sort)");        checks = 0; hashing(big, 1);     System.out.println("Hashing lookups:     " + checks);
        int[] small = {8, 3, 11, 5, 1, 2};        System.out.println(brute(small, 16) + " | " + twoPointers(small, 16) + " | " + hashing(small, 16));    }}
Output
Brute force checks:  1999000
Two pointer checks:  1999 (after an O(n log n) sort)
Hashing lookups:     2000
11+5 | 5+11 | 11+5

What this code does

  • For n = 2,000 the brute force makes n(n - 1)/2 = 1,999,000 checks; the other two make about n. At n = 10⁵ that gap becomes 5 × 10⁹ versus 10⁵.
  • Two pointers needs sorted data (O(n log n), O(1) extra space); hashing needs O(n) extra space but keeps the original order. All three find the same pair.

Pair sum: "does any pair add up to the target?" Brute force checks all n(n - 1)/2 pairs: O(n²). Sorting plus two pointers checks one pair per step after an O(n log n) sort: start at both ends, move the left pointer up if the sum is too small and the right one down if it is too big. Hashing gets O(n) in one pass: for each x, ask whether target - x was seen before.

Revise: Pair sum on a sorted array (opens in a new tab)

Find the bug

Two-pointer pair sum

Each version is almost right. Click the line that breaks it.

It reports a pair for {4} and target 8, which has no pair.

Round 1 of 2

When to stop optimizing

A lower bound is a cost that no correct solution can avoid, for example O(n) to read n inputs, so no algorithm can beat it.

Stop when one of these is true, and say which one: the solution meets the constraints you clarified, you have reached a lower bound (you must read all n inputs, so O(n) time cannot be beaten), or further gains would make the code much harder to get right in the time left.

You can say "there is an O(1)-space version with Boyer-Moore voting; do you want me to go there, or should I code the O(n) HashMap version?" Offering the choice shows depth without risking the round on a trick you may not finish.

Next step

Check your understanding

12 quick questions