Count all subsequences having product less than K
Pattern: Subsequences and knapsack
Count non-empty subsequences whose product is below k. With positive values, dp[p] counts subsequences with product p (for p below k); each new value x adds dp[p] to dp[p × x] when p × x < k.
The problem
Given positive integers and k, return how many non-empty subsequences have a product less than k. The catalogue has no practice link for this one.
Think first
- How is this like counting subsets with a sum?
- Why only products below k?
- What is the table size?
Hints
Brute force, and why it fails
Try all 2ⁿ subsequences.
The key insight
Products only grow, so only the k possible values below k need counting.
Dry run
| count | 4 |
|---|
arr [1, 2, 3, 4], k = 10. Single values: 1, 2, 3, 4.
Step 1 of 3
The plan
dp[p] = subsequences with product p
for x: for p from k - 1 down to 1: if p × x < k: dp[p × x] += dp[p]
if x < k: dp[x] += 1
return sum(dp)
Complexity
- Time
O(n × k)- Space
O(k)
One table of counts.
Edge cases
- k = 1: 0.
- Values of 1 double counts.
- All values at least k: 0.
I've built my logic, show the code
Java
class Solution {
public int productSubSeqCount(int[] arr, int k) {
long[] ways = new long[k]; // ways[p]: subsequences (possibly empty) whose product is exactly p, for p < k
ways[1] = 1; // the empty one has product 1
for (int x : arr)
for (int p = k - 1; p >= 1; p--) // downwards so x is used at most once
if ((long) p * x < k) ways[p * x] += ways[p];
long total = 0;
for (int p = 1; p < k; p++) total += ways[p];
return (int) (total - 1); // leave out the empty subsequence
}
}C++
class Solution {
public:
int productSubSeqCount(vector<int>& arr, int k) {
vector<long long> ways(k, 0); // ways[p]: subsequences (possibly empty) with product exactly p, for p < k
if (k > 1) ways[1] = 1; // the empty one has product 1
for (int x : arr)
for (int p = k - 1; p >= 1; p--) // downwards so x is used at most once
if (static_cast<long long>(p) * x < k) ways[p * x] += ways[p];
long long total = 0;
for (int p = 1; p < k; p++) total += ways[p];
return static_cast<int>(total - (k > 1 ? 1 : 0)); // leave out the empty subsequence
}
};Python
class Solution:
def productSubSeqCount(self, arr: list[int], k: int) -> int:
ways = [0] * k # ways[p]: subsequences (possibly empty) with product exactly p, for p < k
if k > 1:
ways[1] = 1 # the empty one has product 1
for x in arr:
for p in range(k - 1, 0, -1): # downwards so x is used at most once
if p * x < k:
ways[p * x] += ways[p]
return sum(ways) - (1 if k > 1 else 0) # leave out the empty subsequenceCommon mistakes
- Counting the empty subsequence.
- Processing products upwards, which reuses x.