From brute force to optimal
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)An optimal solution rarely comes from a flash of genius. Instead, you reach it by looking at your brute-force loop, spotting the exact work it repeats on every step, and replacing that inner scan with a smarter lookup or running value.
Finding the repeated work
An optimal solution is one whose time and space cost cannot be improved for the problem, usually found by removing repeated work from the brute force.
When a brute-force solution uses two nested loops, the outer loop picks an element nums[i] and the inner loop scans the rest of the array to answer a question about nums[i]. That inner scan is your bottleneck—the slowest part of the code.
Example 1 · Replacing a repeated prefix scan with a running variable
public class RunningMinimumOptimizationDemo { // Problem: Count how many days had a strictly lower price than EVERY earlier day. public static int countRecordLowsBruteForce(int[] prices) { int count = 0; for (int i = 1; i < prices.length; i++) { boolean isRecordLow = true; for (int j = 0; j < i; j++) { if (prices[j] <= prices[i]) { isRecordLow = false; break; } } if (isRecordLow) { count++; } } return count; }
public static int countRecordLowsOptimal(int[] prices) { if (prices.length < 2) { return 0; } int minSoFar = prices[0]; int count = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < minSoFar) { count++; minSoFar = prices[i]; } } return count; }
public static void main(String[] args) { int[] prices = {50, 40, 45, 30, 30}; System.out.println("Brute force: " + countRecordLowsBruteForce(prices)); System.out.println("Optimal : " + countRecordLowsOptimal(prices)); }}Brute force: 2 Optimal : 2
What this code does
- Being strictly smaller than every earlier element is identical to being strictly smaller than the minimum earlier element.
- Carrying
minSoFarforward removes the inner loop completely without using any extra array or collection. - Trace of the optimal method on {50, 40, 45, 30, 30}: 40 < 50 gives count 1, 45 is not lower, 30 < 40 gives count 2, and the second 30 is not strictly lower.
To optimize, write the inner loop's job as a single question. Usually it is one of two things: searching ('Does a matching value x exist earlier in the array?') or recomputing ('What is the sum or minimum of all elements up to i?').
Two common fixes: Repeated search: If the inner loop scans for a target number, a HashSet or HashMap can answer that question in O(1) average time. Repeated sum or minimum: If the inner loop re-adds or re-checks earlier elements, a single running variable can carry the result forward from i - 1 to i. Eliminating the inner loop drops O(n²) work down to a single O(n) pass.
Trading memory for speed
A time-space trade-off means spending extra memory (space) to save CPU steps (time). When you store previously seen numbers in a HashSet or HashMap, you use O(n) extra memory so you never have to rescan the array.
static boolean hasDuplicate(int[] nums) { Set<Integer> seen = new HashSet<>(); // O(n) extra memory... for (int x : nums) { if (!seen.add(x)) return true; // ...buys an O(1) average check, no rescan } return false;}In modern coding rounds and backend servers, a few megabytes of extra memory for a set or map is almost always worth turning a 10-second O(n²) loop into a 5-millisecond O(n) pass.
- Brute force: O(n²) time, O(1) extra space (slow, but uses almost no memory).
- HashSet / HashMap: O(n) average time, O(n) extra space (fast, uses memory proportional to n).
- Running variable (like
runningSumorminSoFar): O(n) time, O(1) extra space—the best of both worlds when you only need a single summary value.
Order of execution
Run the HashSet method
Tap what happens for each number x, in order.
Sorting first or using a set
When a problem asks about duplicates, closest values, or pairs that add up to a target, you have two classic tools to beat O(n²): sorting first or using a hash set/map.
Example 2 · Why original indices require a HashMap instead of sorting in place
import java.util.Arrays;import java.util.HashMap;import java.util.Map;
public class TwoSumIndicesDemo { // Return the two ORIGINAL indices [i, j] (i < j) whose values sum to target, // or [-1, -1] if no pair exists. // Time: O(n) average | Space: O(n) public static int[] twoSumIndices(int[] nums, int target) { Map<Integer, Integer> indexByValue = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int needed = target - nums[i]; if (indexByValue.containsKey(needed)) { return new int[]{indexByValue.get(needed), i}; } indexByValue.put(nums[i], i); } return new int[]{-1, -1}; }
public static void main(String[] args) { int[] nums = {15, 7, 2, 11}; System.out.println(Arrays.toString(twoSumIndices(nums, 9))); System.out.println(Arrays.toString(twoSumIndices(new int[]{3, 3}, 6))); }}[1, 2] [0, 1]
What this code does
- Sorting
{15, 7, 2, 11}into{2, 7, 11, 15}would lose the original positions1and2of7and2. - Storing
value -> indexin aHashMapfinds both the complement and its original index in O(1) average time.
Example 3 · When sorting first beats hashing: smallest difference between any two elements
import java.util.Arrays;
public class SortingBeatsHashingDemo { // Problem: Find the minimum absolute difference |nums[i] - nums[j]| (i != j). // A HashSet only checks exact equality, not 'closest value'. // Sorting places closest numbers right next to each other! O(n log n) time. public static int minDifferenceOptimal(int[] nums) { if (nums == null || nums.length < 2) { throw new IllegalArgumentException("Need at least 2 elements"); } int[] sorted = Arrays.copyOf(nums, nums.length); Arrays.sort(sorted); int minDiff = Integer.MAX_VALUE; for (int i = 1; i < sorted.length; i++) { int diff = sorted[i] - sorted[i - 1]; if (diff < minDiff) { minDiff = diff; } } return minDiff; }
public static void main(String[] args) { int[] data = {40, 12, 29, 15, 50}; System.out.println("Min difference: " + minDifferenceOptimal(data)); }}Min difference: 3
What this code does
- After sorting
{40, 12, 29, 15, 50}into{12, 15, 29, 40, 50}, the closest pair must be two adjacent elements (15 - 12 = 3). - Instead of checking all n(n - 1) / 2 pairs, we sort once in O(n log n) and check only n - 1 adjacent pairs.
Sorting with Arrays.sort(nums) takes O(n log n) time and puts equal or nearby values right next to each other, allowing two pointers (left and right) to walk inward. Using a HashSet takes O(n) average time and preserves the original array order, which is essential whenever the problem asks you to return original indices.
How to choose: Use HashSet / HashMap when: you need O(n) speed, or you must return original array indices. Use Arrays.sort when: extra memory must stay small, or you need elements in numerical order (such as closest pair or triplets). Watch out: Arrays.sort rearranges the array in place! If original indices matter, either use a HashMap or sort a separate index array.
Worked walk-through: pair with a given sum
Let's apply Step 5 to the classic problem: Given an int[] nums and an int target, check whether two distinct indices i and j satisfy nums[i] + nums[j] == target.
- Stage 1 — Brute force (O(n²) time, O(1) space): For each
i, loopjfromi + 1ton - 1and checknums[j] == target - nums[i]. - Stage 2 — Sort + Two pointers (O(n log n) time, O(n) space for a copy): Sort a copy, place
left = 0andright = n - 1. Ifa[left] + a[right]is too small, incrementleft; if too large, decrementright. - Stage 3 — HashSet of seen numbers (O(n) average time, O(n) space): Loop through
numsonce. For eachx, check ifseen.contains(target - x). If yes, returntrue; otherwiseseen.add(x).
HashSet pair sum, target 9
Step 1 of 6
- target
- 9
Example 4 · Brute force: pair with a given sum (O(n²) time, O(1) space)
public class PairSumBruteForceDemo { // Time O(n^2), extra space O(1): test every pair (i, j) with j after i. public static boolean hasPair(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return true; } } } return false; }
public static void main(String[] args) { int[] nums = {3, 8, 5, 1, 6}; System.out.println("Target 9 : " + hasPair(nums, 9)); System.out.println("Target 20: " + hasPair(nums, 20)); }}Target 9 : true Target 20: false
What this code does
- Every pair (i, j) is added up and compared with the target. Nothing is stored, so extra space is O(1), but the work is about n² / 2 additions.
- Why a better way exists: for each
nums[i]the inner loop is really asking "istarget - nums[i]somewhere else?". That one question can be answered faster.
Example 5 · Better: sort a copy, then two pointers (O(n log n) time, O(n) space)
import java.util.Arrays;
public class PairSumSortingDemo { // Time O(n log n), extra space O(n) for the sorted copy. public static boolean hasPair(int[] nums, int target) { int[] sorted = Arrays.copyOf(nums, nums.length); Arrays.sort(sorted); int left = 0; int right = sorted.length - 1; while (left < right) { int sum = sorted[left] + sorted[right]; if (sum == target) { return true; } else if (sum < target) { left++; } else { right--; } } return false; }
public static void main(String[] args) { int[] nums = {3, 8, 5, 1, 6}; System.out.println("Target 9 : " + hasPair(nums, 9)); System.out.println("Target 20: " + hasPair(nums, 20)); }}Target 9 : true Target 20: false
What this code does
- After sorting,
leftandrightwalk inward: a sum that is too small movesleftup, and a sum that is too large movesrightdown. - Each pointer moves at most n steps, so the search is O(n) and sorting (O(n log n)) is the main cost. It is faster than n² because every step rules out a whole group of pairs.
Example 6 · Optimal: one pass with a HashSet (O(n) time, O(n) space)
import java.util.HashSet;import java.util.Set;
public class PairSumHashSetDemo { // Time O(n) on average, extra space O(n) for the set of numbers seen so far. public static boolean hasPair(int[] nums, int target) { Set<Integer> seen = new HashSet<>(); for (int x : nums) { if (seen.contains(target - x)) { return true; } seen.add(x); } return false; }
public static void main(String[] args) { int[] nums = {3, 8, 5, 1, 6}; System.out.println("Target 9 : " + hasPair(nums, 9)); System.out.println("Target 20: " + hasPair(nums, 20)); System.out.println("One 7, target 14: " + hasPair(new int[]{7, 2}, 14)); }}Target 9 : true Target 20: false One 7, target 14: false
What this code does
- The set remembers the numbers already seen, so "is
target - xearlier in the array?" becomes one lookup instead of a scan. That makes one pass enough: O(n) average time. - The check comes before
seen.add(x), soxis never paired with itself: one7with target 14 gives false. The price is O(n) extra memory.
Look at what happens when we sit at element x = nums[i]: we only need to know whether the complement needed = target - x exists at another index. We can evolve the solution through three clear stages.
Next step
Check your understanding
10 quick questions