1. Brute Force (Nested Loop Subarray Inspection)
Intuition
Fix starting index i. Expand right index j, keeping a hash map of frequencies for the current subarray. When a number is added, add its prior count to pairs. If pairs >= k, increment total.
Algorithm
- Step 1: Initialize
ans = 0. - Step 2: For each i from 0 to n - 1:
- - Initialize frequency map
freqandpairs = 0. - - For each j from i to n - 1:
- - Add
freq[nums[j]]topairs. - - Increment
freq[nums[j]]. - - If
pairs >= k, incrementans. - Step 3: Return
ans.
Brute Force (Nested Loop Subarray Inspection) Trace
2 of 2 questions left todayPhase 1 — Window Initialization: Both left and right pointers anchor at index 0
Phase 1 — Window Initialization: Both left and right pointers anchor at index 0. Initial window length is 1 with sum/metric=2.
#include <iostream>#include <vector>#include <unordered_map> class Solution {public: long long countGood(std::vector<int>& nums, int k) { int n = nums.size(); long long ans = 0; for (int i = 0; i < n; i++) { std::unordered_map<int, int> freq; long long pairs = 0; for (int j = i; j < n; j++) { pairs += freq[nums[j]]; freq[nums[j]]++; if (pairs >= k) { ans++; } } } return ans; }}; int main() { Solution sol; std::vector<int> nums = {3, 1, 4, 3, 2, 2, 4}; std::cout << "Good Subarrays: " << sol.countGood(nums, 2) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Nested Loop Subarray Inspection). - Space complexity:
O(1)— Space complexity for Brute Force (Nested Loop Subarray Inspection).
Why Brute Force Doesn't Scale:
For N = 100,000, N2 = 1010 operations, causing TLE. Two pointers ensures each element is added and removed from the frequency map at most once, reducing operations from 1010 to 200,000.
With N = 100,000: Brute force takes ~10 billion operations (> 10 seconds); Sliding Window finishes in ~200,000 operations (< 15 ms).