1. Nested Loops Validation (Brute Force)
Intuition
Inspect every possible subarray (i, j), maintaining running min and max values.
Algorithm
- 1. Initialize ans = 0.
- 2. Loop i from 0 to N-1: - curMin = infinity, curMax = -infinity - Loop j from i to N-1: - curMin = min(curMin, nums[j]), curMax = max(curMax, nums[j]) - if curMin < minK or curMax > maxK: break - if curMin == minK and curMax == maxK: ans++.
- 3. Return ans.
Brute Force All Subarrays Min/Max Evaluation
2 of 2 questions left todayPhase 1 — Step 1: Step 1: Subarray [1, 3, 5] from i=0 to j=2 has min = 1 and max = 5
Phase 1 — Step 1: Step 1: Subarray [1, 3, 5] from i=0 to j=2 has min = 1 and max = 5. Both bounds satisfied! count = 1.
#include <iostream>#include <vector>#include <algorithm>using namespace std; // Brute Force Approach: Nested Loops Validationlong long countSubarrays(const vector<int>& nums, int minK, int maxK) { long long ans = 0; int n = nums.size(); for (int i = 0; i < n; i++) { int curMin = nums[i]; int curMax = nums[i]; for (int j = i; j < n; j++) { curMin = min(curMin, nums[j]); curMax = max(curMax, nums[j]); if (curMin < minK || curMax > maxK) { break; } if (curMin == minK && curMax == maxK) { ans++; } } } return ans;} int main() { vector<int> nums = {1, 3, 5, 2, 7, 5}; int minK = 1, maxK = 5; long long result = countSubarrays(nums, minK, maxK); cout << "Output: " << result << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Nested loops examine up to N*(N+1)/2 subarrays. - Space complexity:
O(1)— Only constant extra variables are used.
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.