1. Check All Triplets (Brute Force)
Intuition
Iterate with three nested loops for all triplets 0 <= i < j < k < n. Compute sum = nums[i] + nums[j] + nums[k]. If abs(sum - target) < abs(closest - target), update closest.
When to apply: Use to understand the baseline search for triplet sums.
Exhaustive Triplet Enumeration (O(N^3) Time)
2 of 2 questions left todayStart exhaustive enumeration at indices (0, 1, 2)
Start exhaustive enumeration at indices (0, 1, 2). The sum of 2 is only 1 away from target 1.
public class Main { public static class Solution { public int threeSumClosest(int[] nums, int target) { int closest = nums[0] + nums[1] + nums[2]; int n = nums.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { int sum = nums[i] + nums[j] + nums[k]; if (Math.abs(sum - target) < Math.abs(closest - target)) { closest = sum; } } } } return closest; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {-1, 2, 1, -4}; int target = 1; System.out.println("Closest sum: " + sol.threeSumClosest(nums, target)); }}Time & Space Complexity
- Time complexity:
O(n^3)— Three nested loops examine all n*(n-1)*(n-2)/6 triplets. - Space complexity:
O(1)— Only scalar closest tracking variable.
Why Brute Force Doesn't Scale:
For N = 500, N3 = 125,000,000 loop operations. Sorting reduces search space by a factor of N to N2 = 250,000 operations.
On an array of size 500: Brute force takes ~125M operations (~150 ms); Two-pointer takes ~250K operations (< 1 ms).