Skip to content

Commit 242a1f3

Browse files
committed
solve Subarray Product Less Than K
1 parent 5aeadc1 commit 242a1f3

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# Gets TLEd.
6+
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
7+
n = len(nums)
8+
ans = 0
9+
10+
for i in range(n):
11+
prod = 1
12+
for j in range(i, n):
13+
prod *= nums[j]
14+
if prod < k:
15+
ans += 1
16+
else:
17+
break
18+
19+
return ans
20+
21+
22+
class OfficialSolution:
23+
def numSubarrayProductLessThanKApproach2(self, nums: List[int], k: int) -> int:
24+
"""
25+
== Approach #2: Sliding Window ==
26+
== Intuition ==
27+
For each right, call opt(right) the smallest left so that the product of the
28+
subarray nums[left] * nums[left+1] * ... * nums[right] is less than k. opt is a
29+
monotone increasing function, so we can use a sliding window.
30+
31+
== Algorithm ==
32+
Our loop invariant is that left is the smallest value so that the product in the
33+
window prod = nums[left] * nums[left+1] * ... * nums[right] is less than k.
34+
For every right, we update left and prod to maintain this invariant. Then, the
35+
number of intervals with subarray product less than k and with right-most
36+
coordinate right, is right - left + 1. We'll count all of these for each value
37+
of right.
38+
39+
== Complexity Analysis ==
40+
- Time Complexity: O(N), where N is the length of nums. At each iteration, we
41+
either increase left or right, and we both left and right can be incremented
42+
at most N times.
43+
- Space Complexity: O(1).
44+
"""
45+
left = right = 0
46+
prod = 1
47+
ans = 0
48+
49+
while right < len(nums):
50+
# Case 1. Include right.
51+
if prod * nums[right] < k:
52+
prod *= nums[right]
53+
ans += right - left + 1
54+
right += 1
55+
# Case 2. Cannot include right.
56+
# Case 2a. If left and right point to same element.
57+
elif left == right:
58+
left += 1
59+
right += 1
60+
# Case 2b. Left points to a left element.
61+
else:
62+
prod //= nums[left]
63+
left += 1
64+
65+
return ans
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
3+
from subarray_product_less_than_k import Solution, OfficialSolution
4+
5+
6+
class TestSubarrayProductLessThanK(unittest.TestCase):
7+
def test_example_1(self):
8+
assert Solution().numSubarrayProductLessThanK(nums=[10, 5, 2, 6], k=100) == 8
9+
assert (
10+
OfficialSolution().numSubarrayProductLessThanKApproach2(
11+
nums=[10, 5, 2, 6], k=100
12+
)
13+
== 8
14+
)

0 commit comments

Comments
 (0)