1. Brute Force — Hash Set per Window
Intuition
For each window of size k, construct a fresh hash set, insert all k elements, and record the number of unique elements.
Algorithm
- Initialize required state variables and allocate data structures for Brute Force — Hash Set per Window.
- Iterate through the input array and apply the core algorithmic condition.
- Update boundaries, frequencies, or pointers in accordance with the invariant.
- Return the computed result or transformed array.
Brute Force — Hash Set per Window 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=1.
#include <iostream>#include <vector>#include <unordered_set> using namespace std; class Solution {public: vector<int> countDistinct(vector<int>& arr, int k) { int n = arr.size(); vector<int> result; for (int i = 0; i <= n - k; i++) { unordered_set<int> uniqueElements; for (int j = i; j < i + k; j++) { uniqueElements.insert(arr[j]); } result.push_back(uniqueElements.size()); } return result; }}; int main() { Solution sol; vector<int> arr = {1, 2, 1, 3, 4, 2, 3}; int k = 4; cout << "Input: arr = [1, 2, 1, 3, 4, 2, 3], k = 4\n"; vector<int> res = sol.countDistinct(arr, k); cout << "Brute Force Result: ["; for (size_t i = 0; i < res.size(); i++) { cout << res[i] << (i + 1 < res.size() ? ", " : ""); } cout << "]\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force — Hash Set per Window. - Space complexity:
O(1)— Space complexity for Brute Force — Hash Set per Window.
Why Brute Force Doesn't Scale:
For N = 100,000 and K = 50,000, N * K = 5 * 109 operations, which takes several seconds.
Sliding window does 2 operations per window, reducing 5 billion operations to ~200,000 operations (25,000x speedup).