1. Three Nested Loops with Hash Set (Brute Force)
Intuition
Check every possible triplet combination (i, j, k) with three nested loops and store sorted triplets in a set to avoid duplicates.
Algorithm
- 1. Initialize a hash set to store unique triplets.
- 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. If nums[i] + nums[j] + nums[k] == 0, sort the triplet [nums[i], nums[j], nums[k]] and add it to the set.
- 6. Return the list of all triplets in the set.
Brute Force Three Nested Loops Enumeration
2 of 2 questions left todayTriplet (0, 1, 5): Sum is -3
Triplet (0, 1, 5): Sum is -3. No triplet starting with index 0 sums to 0.
#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>> threeSum(vector<int>& nums) { 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++) { if (nums[i] + nums[j] + nums[k] == 0) { vector<int> temp = {nums[i], nums[j], nums[k]}; sort(temp.begin(), temp.end()); st.insert(temp); } } } } return vector<vector<int>>(st.begin(), st.end()); }}; int main() { Solution sol; vector<int> nums = {-1, 0, 1, 2, -1, -4}; vector<vector<int>> res = sol.threeSum(nums); cout << "Unique Triplets:" << endl; for (const auto& triplet : res) { cout << "[" << triplet[0] << ", " << triplet[1] << ", " << triplet[2] << "] "; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^3 * log 3) = O(N^3)— Three nested loops yield N*(N-1)*(N-2)/6 triplet checks. Inserting and sorting each triplet takes constant time. - Space complexity:
O(2 * K) where K is number of unique triplets— Requires a set to store unique triplets, taking memory proportional to the number of valid triplets.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.