1. Four Nested Loops with Hash Set (Brute Force)
Intuition
Iterate through every distinct quadruplet index combination (i, j, k, l) and store sorted quadruplets in a set.
Algorithm
- 1. Create a set to store unique quadruplets.
- 2. Loop i from 0 to N - 1.
- 3. Nested loop j from i + 1 to N - 1.
- 4. Nested loop k from j + 1 to N - 1.
- 5. Nested loop l from k + 1 to N - 1: - If nums[i] + nums[j] + nums[k] + nums[l] == target: sort and insert into set.
- 6. Return the list of unique quadruplets.
Brute Force 4-Nested Loops Quadruplet Scan
2 of 2 questions left todayPhase 1 — Step 1: Step 1: Fix indices i=0, j=1, k=2, l=3
Phase 1 — Step 1: Step 1: Fix indices i=0, j=1, k=2, l=3. Quadruplet [-2, -1, 0, 0] sums to -3. No match.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, int target) { int n = nums.size(); set<vector<int>> st; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { for (int l = k + 1; l < n; l++) { long long sum = (long long)nums[i] + nums[j] + nums[k] + nums[l]; if (sum == target) { vector<int> quad = {nums[i], nums[j], nums[k], nums[l]}; sort(quad.begin(), quad.end()); st.insert(quad); } } } } } return vector<vector<int>>(st.begin(), st.end()); }}; int main() { Solution sol; vector<int> nums = {1, 0, -1, 0, -2, 2}; int target = 0; vector<vector<int>> res = sol.fourSum(nums, target); cout << "Unique Quadruplets:" << endl; for (const auto& quad : res) { cout << "[" << quad[0] << ", " << quad[1] << ", " << quad[2] << ", " << quad[3] << "] "; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^4)— Four nested loops produce N*(N-1)*(N-2)*(N-3)/24 iterations, leading to O(N4) operations. - Space complexity:
O(2 * K) where K is number of unique quadruplets— A hash set is used to store unique quadruplets.
Why Brute Force Doesn't Scale:
For N = 200, N4 = 1,600,000,000 checks which exceeds the standard 1-second limit. By sorting first (O(N log N)), fixing two indices i and j takes O(N2), and finding the remaining two elements with two converging pointers takes O(N). Total operations drop to ~2003 / 24 ≈ 330,000 operations, which runs in less than 5 milliseconds.
At N = 200: Brute Force = ~1.6 billion ops (~15s). Optimal = ~330k ops (< 5ms).