1. Brute Force — Check All Pairs
Intuition
Iterate through every pair of elements using nested loops and verify if their sum equals the target.
Algorithm
- Loop with index i from 0 to N - 1.
- Nested loop with index j from i + 1 to N - 1.
- Check if nums[i] + nums[j] == target.
- If equal, return [i, j].
- If no pair matches after checking all pairs, return an empty array.
Brute Force All Pairs Comparison Trace
2 of 2 questions left todayPair (0, 1): Fix i=0 (value 3)
Pair (0, 1): Fix i=0 (value 3). Test j=1 (value 8). Sum is 11, which does not equal 10. Increment j.
#include <iostream>#include <vector>using namespace std; // Brute Force: Check all pairsvector<int> twoSum(const vector<int>& nums, int target) { int n = nums.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (nums[i] + nums[j] == target) { return {i, j}; } } } return {};} int main() { vector<int> nums = {3, 2, 4}; int target = 6; vector<int> result = twoSum(nums, target); cout << "Output: [" << result[0] << ", " << result[1] << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N²)— The outer loop runs N times and the inner loop runs up to N times, totaling N × (N - 1) / 2 comparisons = O(N²) quadratic time. - Space complexity:
O(1)— Only a few integer loop variables (i, j) are used. No extra data structures are allocated.
Why Brute Force Doesn't Scale:
For an array of size N, brute force performs N × (N - 1) / 2 comparisons.
For N = 10,000: 10,000² / 2 ≈ 50,000,000 operations.
For N = 100,000: 100,000² / 2 ≈ 5,000,000,000 operations (5 billion checks).
Even though brute force is logically correct, its quadratic growth causes Time Limit Exceeded (TLE) on large inputs.
At N = 104: Brute Force takes ~50,000,000 ops (~150ms). Hash Map takes ~10,000 ops (< 2ms).