1. Brute Force — Nested Linear Search
Intuition
For each element in nums1, linearly scan nums2 to check if it exists. If found, add it to the result array only if not already added.
Algorithm
- Initialize an empty list
result. - For each number
xinnums1: - Scan
nums2to see ifxexists innums2. - If
xexists innums2, check ifxis already inresult. - If not in
result, appendxtoresult. - Return
result.
Nested Loops Deduplication (O(M*N) Time)
2 of 2 questions left todayElement 1 does not match
Hash map state
Execution stateElement 1 does not match.
#include <algorithm>#include <iostream>#include <vector>using namespace std; // Brute Force: Linear search in nums2 and deduplication in resultvector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> result; for (int x : nums1) { // Check if x exists in nums2 bool inNums2 = false; for (int y : nums2) { if (x == y) { inNums2 = true; break; } } // If in nums2, check if already in result if (inNums2) { bool inResult = false; for (int r : result) { if (r == x) { inResult = true; break; } } if (!inResult) { result.push_back(x); } } } return result;} int main() { vector<int> nums1 = {1, 2, 2, 1}; vector<int> nums2 = {2, 2}; vector<int> res = intersection(nums1, nums2); cout << "Output: ["; for (size_t i = 0; i < res.size(); i++) { cout << res[i] << (i + 1 < res.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Nested Linear Search. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Nested Linear Search.
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.