1. Nested Loops All Pairs
Intuition
For each element i, compute the product of all elements j != i using a nested loop.
Algorithm
- 1. Initialize an answer array result of size n.
- 2. For each index i from 0 to n-1: - Set prod = 1. - For each index j from 0 to n-1: - If j != i, prod *= nums[j]. - Set result[i] = prod.
- 3. Return result.
Brute Force Nested Loop Product Calculation
2 of 2 questions left todayCalculate res[0]: Exclude index 0
Calculate res[0]: Exclude index 0. Multiply all remaining elements: 2 * 3 * 4 = 24. Store res[0] = 24.
#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<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); vector<int> ans(n, 1); for (int i = 0; i < n; ++i) { long long prod = 1; for (int j = 0; j < n; ++j) { if (i != j) prod *= nums[j]; } ans[i] = prod; } return ans; }}; int main() { Solution sol; vector<int> nums = {1, 2, 3, 4}; vector<int> res = sol.productExceptSelf(nums); cout << "Product Except Self: "; for (int x : res) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— For each of the N elements, the inner loop iterates over N-1 elements. Total operations = N * (N-1) = O(N2). - Space complexity:
O(1)— The output array does not count toward auxiliary space, requiring O(1) extra space.
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.