Opening the reading…
Opening the reading…
SLIDING WINDOW › DYNAMIC SIZE SLIDING-WINDOW
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Fix a right endpoint and consider the contiguous subarrays that end there. If the product from left to right is less than k, then removing elements from the left can only decrease the product because every number is positive. Therefore every start between left and right also forms a valid subarray ending at right.
When the product becomes too large, move left forward and divide out the elements that leave the window. Because extending the right endpoint never decreases the product, the left boundary never needs to move backward. Once the window is valid again, its length is exactly the number of valid subarrays ending at right.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The right pointer advances n times, and the left pointer also advances at most n times overall. Although the while loop can run several times for one right index, each division removes an element permanently from the window, so no element is removed twice. |
| Space | O(1) extra | Only prod, the two indices, and the answer are maintained. The returned count is required output and is excluded from working memory; the extra space remains O(1) even for the worst-shaped input. |
#include <vector>
using namespace std;
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if (k <= 1) return 0;
int ans = 0;
long long prod = 1;
int left = 0;
for (int right = 0; right < static_cast<int>(nums.size()); ++right) {
prod *= nums[right];
while (prod >= k) {
prod /= nums[left];
++left;
}
ans += right - left + 1;
}
return ans;
}
};The while loop is the core invariant: after it finishes, the product from left through right is strictly less than k. The final addition does not search individual subarrays. It uses positivity to conclude that every shorter suffix of this window is valid, giving exactly right - left + 1 choices.