1. Combinations Generator with Set Difference
Intuition
Iterate recursively to select N/2 indices. Compute the sum of selected elements and compare with remaining elements.
Algorithm
- Step 1: Generate all 2N subsets of the array.
- Step 2: Filter to keep only subsets of exact size N/2 (or (N-1)/2 if N is odd).
- Step 3: For each subset, calculate abs(totalSum - 2 * subsetSum).
- Step 4: Track and return the two subsets that yield the minimum difference.
#include <iostream>#include <vector>#include <cmath>#include <climits>#include <numeric> class Solution {public: void backtrack(int start, const std::vector<int>& arr, int k, std::vector<int>& current, int totalSum, int& minDiff, std::vector<int>& bestSet) { if ((int)current.size() == k) { int currentSum = 0; for (int x : current) currentSum += x; int diff = std::abs(totalSum - 2 * currentSum); if (diff < minDiff) { minDiff = diff; bestSet = current; } return; } for (int i = start; i < (int)arr.size(); i++) { current.push_back(arr[i]); backtrack(i + 1, arr, k, current, totalSum, minDiff, bestSet); current.pop_back(); } } std::pair<std::vector<int>, std::vector<int>> tugOfWar(const std::vector<int>& arr) { int n = arr.size(); int totalSum = std::accumulate(arr.begin(), arr.end(), 0); int k = n / 2; int minDiff = INT_MAX; std::vector<int> current, bestSet; backtrack(0, arr, k, current, totalSum, minDiff, bestSet); std::vector<int> otherSet; std::vector<bool> used(n, false); for (int x : bestSet) { for (int i = 0; i < n; i++) { if (!used[i] && arr[i] == x) { used[i] = true; break; } } } for (int i = 0; i < n; i++) { if (!used[i]) otherSet.push_back(arr[i]); } return {bestSet, otherSet}; }}; int main() { Solution solver; std::vector<int> arr = {3, 4, 5, -3, 100, 1, 89, 54, 23, 20}; auto [s1, s2] = solver.tugOfWar(arr); std::cout << "Subset 1 size: " << s1.size() << "\n"; std::cout << "Subset 2 size: " << s2.size() << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N * C(N, N/2))— Generates C(N, N/2) combinations, taking O(N) to process each. - Space complexity:
O(N)— O(N) for current combination buffer and call stack.