1. Nested Loops Counting (Brute Force)
Intuition
Inspect every possible subarray (i, j) and count how many odd numbers it contains.
Algorithm
- 1. Initialize ans = 0.
- 2. Loop i from 0 to N-1: - oddCount = 0 - Loop j from i to N-1: - if nums[j] % 2 != 0: oddCount++ - if oddCount == k: ans++ - else if oddCount > k: break.
- 3. Return ans.
Brute Force All Subarrays Odd Tally Scan
2 of 2 questions left todayPhase 1 — Not nice Advance j to 3: Step 1: Subarray [1, 1, 2] contains 2 odds
Phase 1 — Not nice Advance j to 3: Step 1: Subarray [1, 1, 2] contains 2 odds. Target is k = 3. Increment j.
#include <iostream>#include <vector>using namespace std; // Brute Force Approach: Nested Loops Countingint numberOfSubarrays(const vector<int>& nums, int k) { int n = nums.size(); int ans = 0; for (int i = 0; i < n; i++) { int oddCount = 0; for (int j = i; j < n; j++) { if (nums[j] % 2 != 0) oddCount++; if (oddCount == k) ans++; else if (oddCount > k) break; } } return ans;} int main() { vector<int> nums = {1, 1, 2, 1, 1}; int k = 3; int result = numberOfSubarrays(nums, k); cout << "Output: " << result << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Nested loops test up to N*(N+1)/2 subarrays. - Space complexity:
O(1)— Only scalar counters 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.