1. Brute Force (Nested Loops)
Intuition
Check every possible subarray by fixing the start index i and multiplying elements until the product reaches or exceeds k.
Algorithm
- If
k <= 1, return 0. - Initialize
count = 0. - Loop
ifrom 0 tonums.length - 1: - Set
prod = 1. - Loop
jfromitonums.length - 1: -
prod *= nums[j] - If
prod < k, incrementcount. - Else, break early because all elements are positive (product will only grow).
- Return
count.
All Subarrays Product (O(N^2) Time)
2 of 2 questions left todaySingle element [10] qualifies
Single element [10] qualifies.
#include <iostream>#include <vector> class Solution {public: int numSubarrayProductLessThanK(std::vector<int>& nums, int k) { if (k <= 1) return 0; int n = nums.size(); int count = 0; for (int i = 0; i < n; ++i) { long long prod = 1; for (int j = i; j < n; ++j) { prod *= nums[j]; if (prod < k) { count++; } else { break; } } } return count; }}; int main() { Solution sol; std::vector<int> nums = {10, 5, 2, 6}; int k = 100; std::cout << sol.numSubarrayProductLessThanK(nums, k) << std::endl; // Output: 8 return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force (Nested Loops). - Space complexity:
O(1)— Space complexity for Brute Force (Nested Loops).
Why Brute Force Doesn't Scale:
For N = 30,000, N2 / 2 is ~450 million operations, triggering Time Limit Exceeded (TLE).
With N = 30,000, the O(N) sliding window executes in under 5ms using only 2 pointers and a running product accumulator.