1. Brute Force — Generate All Pairs and Sort
Intuition
Compute Cartesian product of nums1 and nums2, sort all pairs ascending by their sum, and take the first k pairs.
When to apply: When N1, N2 are very small (<= 100).
Algorithm
- Step 1: Nested loops: for i in nums1, for j in nums2: store [i, j].
- Step 2: Sort all pairs based on (p[0] + p[1]).
- Step 3: Slice and return first min(k, total) pairs.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class Solution {public: vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { vector<vector<int>> allPairs; for (int x : nums1) { for (int y : nums2) { allPairs.push_back({x, y}); } } sort(allPairs.begin(), allPairs.end(), [](const vector<int>& a, const vector<int>& b) { return (a[0] + a[1]) < (b[0] + b[1]); }); int count = min((int)allPairs.size(), k); return vector<vector<int>>(allPairs.begin(), allPairs.begin() + count); }}; int main() { Solution sol; vector<int> nums1 = {1, 7, 11}; vector<int> nums2 = {2, 4, 6}; auto res = sol.kSmallestPairs(nums1, nums2, 3); cout << "K Smallest Pairs (Brute Force): "; for (auto& p : res) cout << "[" << p[0] << "," << p[1] << "] "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N1 * N2 log(N1 * N2))— O(N1 * N2 log(N1 * N2)) due to sorting all pairs. - Space complexity:
O(N1 * N2)— O(N1 * N2) storage for pairs.
Why Brute Force Doesn't Scale:
For N1 = 105 and N2 = 105, N1 * N2 = 1010 pairs, requiring ~80 GB of RAM. The optimal heap uses only O(K) space (~104 items).
Runs in ~15ms for K = 10,000 versus crash/OOM for naive Cartesian product.