Bird
Raised Fist0
Interview Prepsubsets-combinationsmediumAmazonGoogle

Count of Subsets With Sum K

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem

Imagine you have a collection of coins and want to find out how many different ways you can pick some coins so that their total value equals exactly a target amount.

Given an array of integers and a target sum K, find the number of subsets of the array whose elements sum exactly to K. Return the count of such subsets.

1 ≤ n ≤ 10^5 (for optimized solutions)Array elements can be positive integers0 ≤ K ≤ sum of all elements
Edge cases: Empty array with K=0 → 1 (empty subset counts)Array with all elements greater than K → 0Array with multiple zeros and K=0 → multiple subsets including empty and zeros
</>
IDE
def count_subsets(arr: list[int], K: int) -> int:public int countSubsets(int[] arr, int K)int countSubsets(vector<int> &arr, int K)function countSubsets(arr, K)
def count_subsets(arr, K):
    # Write your solution here
    pass
class Solution {
    public int countSubsets(int[] arr, int K) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int countSubsets(vector<int> &arr, int K) {
    // Write your solution here
    return 0;
}
function countSubsets(arr, K) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 0Returning 0 for empty array with K=0 instead of 1 (missing empty subset).Return 1 when index == len(arr) and current_sum == K.
Wrong: Overcounted subsetsCounting subsets with repeated use of elements (unbounded) instead of 0/1 usage.Ensure each element is included at most once by advancing index in recursion.
Wrong: Undercount due to ignoring duplicatesTreating duplicate values as one element, missing subsets with different instances.Treat each element as unique in recursion/DP even if values repeat.
Wrong: Non-zero count when no subsets sum to KNot pruning subsets exceeding K or incorrect base case handling.Return 0 when no valid subsets found and prune sums exceeding K.
Wrong: TLEUsing brute force recursion for large n causing exponential time.Implement O(n*K) DP solution with memoization or tabulation.
Test Cases
t1_01basic
Input{"arr":[1,2,3,3],"K":6}
Expected3

The subsets are [1,2,3] (using first 3) and [3,3] (using both 3s). The subset [1,2,3] is counted once per unique element combination, so total 2 subsets.

t1_02basic
Input{"arr":[2,4,6,10],"K":16}
Expected2

Subsets [6,10] and [2,4,10] sum to 16.

t2_01edge
Input{"arr":[],"K":0}
Expected1

Empty subset sums to 0, so count is 1.

t2_02edge
Input{"arr":[5,6,7],"K":4}
Expected0

All elements are greater than K, no subsets sum to 4.

t2_03edge
Input{"arr":[0,0,0],"K":0}
Expected8

All subsets of zeros sum to 0; total subsets = 2^3 = 8.

t2_04edge
Input{"arr":[7],"K":7}
Expected1

Single element equal to K forms one valid subset.

t3_01corner
Input{"arr":[1,2,2,3],"K":4}
Expected2

Subsets: [1,3] and [2,2] sum to 4. The subset [1,2,1] mentioned is invalid as no extra 1 exists; duplicates treated as distinct elements.

t3_02corner
Input{"arr":[1,2,3],"K":6}
Expected1

Only subset [1,2,3] sums to 6; tests 0/1 knapsack vs unbounded confusion.

t3_03corner
Input{"arr":[1,3,5],"K":4}
Expected1

No subset sums to 4; [1,3] sums to 4 but 3+1=4 is correct, but 3+1=4 is valid so expected should be 1. Re-checking: 1+3=4 is valid subset, so expected should be 1. Original expected was 1, so correct is 1.

t4_01performance
Input{"arr":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100],"K":2500}
⏱ Performance - must finish in 2000ms

n=100, K=2500; O(n*K) DP must complete within 2 seconds.

Practice

(1/5)
1. What is the worst-case time complexity of the optimized dynamic programming solution for the Largest Divisible Subset problem, where n is the number of elements in the input array?
medium
A. O(n^2) due to nested loops checking divisibility pairs
B. O(2^n) because all subsets are considered
C. O(n^3) because of triple nested loops for subset checks
D. O(n log n) due to sorting and linear DP

Solution

  1. Step 1: Identify main operations

    Sorting takes O(n log n). The DP uses two nested loops: outer loop over n elements, inner loop up to i elements.
  2. Step 2: Analyze nested loops

    Each pair (i,j) is checked once, resulting in O(n^2) divisibility checks. Early break may speed up in practice but worst case remains O(n^2).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    DP nested loops dominate complexity [OK]
Hint: DP nested loops -> O(n^2) worst case [OK]
Common Mistakes:
  • Confusing sorting time as dominant (O(n log n))
  • Assuming triple nested loops due to subset checks
  • Thinking brute force complexity applies to DP
2. Examine the following buggy code snippet from the trie-based solution. Which line contains the subtle bug that causes incorrect counts for some puzzles?
medium
A. Line where node.count is incremented
B. Line missing filtering words with more than 7 unique letters before insertion
C. Line checking if bit is set in mask during insertion
D. Line checking if puzzle_mask contains child bit during dfs

Solution

  1. Step 1: Identify filtering step

    The code inserts all words regardless of unique letter count, causing large trie and slow traversal.
  2. Step 2: Understand impact

    Words with >7 unique letters cannot match puzzles (7 letters max), so filtering them out is necessary for correctness and efficiency.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Filtering missing leads to incorrect counts and performance issues [OK]
Hint: Filter words with >7 unique letters before insertion [OK]
Common Mistakes:
  • Not filtering large words
  • Incorrect bit checks
  • Misplaced count increments
3. Suppose the problem changes: now candidates can include negative numbers, and you still want all unique combinations summing to the target with reuse allowed. Which modification to the backtracking approach is necessary to handle this variant correctly?
hard
A. Remove pruning on target < 0 and add a visited set to detect cycles to avoid infinite recursion.
B. No change needed; the existing backtracking with pruning on target < 0 still works correctly.
C. Sort candidates in descending order and prune when target is less than the smallest candidate.
D. Use dynamic programming instead of backtracking because negative numbers break recursion.

Solution

  1. Step 1: Understand impact of negative candidates

    Negative numbers allow sums to decrease indefinitely, causing infinite recursion if pruning on target < 0 is used or missing.
  2. Step 2: Modify pruning and cycle detection

    Pruning on target < 0 is invalid because target can oscillate; must remove it and add a visited set or memoization to detect repeated states and avoid infinite loops.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Cycle detection is essential when negative numbers allow infinite recursion [OK]
Hint: Negative numbers require cycle detection to prevent infinite recursion [OK]
Common Mistakes:
  • Assuming pruning on target < 0 always applies
  • Ignoring infinite recursion caused by negatives
4. Suppose the problem is modified so that elements can be chosen multiple times (unlimited reuse) to form subsets. Which approach correctly adapts to count the number of max bitwise-OR subsets under this new constraint?
hard
A. Use dynamic programming over OR values with state compression to count combinations
B. Use backtracking with memoization to handle repeated elements and prune search
C. Use the same bitmask enumeration approach since subsets remain finite
D. Sort elements and greedily pick those with highest bits until max OR is reached

Solution

  1. Step 1: Recognize infinite subsets due to unlimited reuse

    Bitmask enumeration is infeasible as subsets are infinite with reuse allowed.
  2. Step 2: Use DP over OR states to count combinations efficiently

    DP with state compression tracks counts of subsets achieving each OR value, handling reuse.
  3. Step 3: Understand greedy or naive backtracking fail due to infinite or redundant subsets

    Greedy misses combinations; naive backtracking is exponential and inefficient.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    DP over OR states handles reuse -> correct and efficient [OK]
Hint: Reuse means infinite subsets -> DP over OR states needed [OK]
Common Mistakes:
  • Trying bitmask enumeration despite infinite subsets
  • Using greedy approach ignoring subset counts
5. Suppose the problem is modified so that puzzles can have repeated letters and words can be counted multiple times if they match multiple subsets of the puzzle letters. Which modification to the optimal bitmask + trie approach correctly handles this variant?
hard
A. Preprocess puzzles to remove duplicates and apply the original algorithm unchanged.
B. Modify dfs to not require the puzzle's first letter to be present in the word and allow counting multiple matches per word.
C. Enumerate all subsets of puzzle letters including duplicates and sum counts from trie traversal without filtering first letter.
D. Use a multiset trie that stores counts for repeated letters and traverse all subsets including duplicates.

Solution

  1. Step 1: Understand variant requirements

    Repeated letters in puzzles and multiple counting per word require handling multisets, not just sets.
  2. Step 2: Modify data structure and traversal

    A multiset trie that stores counts for repeated letters and traverses all subsets including duplicates correctly counts all matches.
  3. Step 3: Why other options fail

    Ignoring first letter breaks mandatory condition; removing duplicates loses information; naive enumeration is inefficient.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Multiset trie handles repeated letters and multiple counts correctly [OK]
Hint: Multiset trie needed for repeated letters and multiple counts [OK]
Common Mistakes:
  • Ignoring repeated letters
  • Removing duplicates incorrectly
  • Dropping first letter condition