Bird
Raised Fist0
Interview Prepsubsets-combinationsmediumAmazonGoogle

Count of Subsets With Sum K

Choose your preparation mode4 modes available
📋
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. Consider the following Python code implementing the optimal backtracking with bitmask and memoization approach for the Matchsticks to Square problem. Given the input [1,1,2,2,2], what is the final return value of makesquare([1,1,2,2,2])?
easy
A. True
B. Depends on the order of matchsticks
C. Raises an exception due to index error
D. False

Solution

  1. Step 1: Calculate total and side length

    Total = 1+1+2+2+2 = 8, side = 8/4 = 2.
  2. Step 2: Trace backtracking calls

    Sorted sticks: [2,2,2,1,1]. The algorithm tries to form sides of length 2. It can form three sides with three 2's, and the last side with two 1's. Hence, returns true.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sum divisible by 4 and sticks fit sides exactly [OK]
Hint: Sum divisible by 4 and sticks fit sides exactly [OK]
Common Mistakes:
  • Forgetting to sort and prune
  • Assuming order affects result
  • Miscounting sides formed
2. You are given an integer array that may contain duplicates. Your task is to find all possible subsets without duplicate subsets in the result. Which approach guarantees generating all unique subsets efficiently without redundant computations?
easy
A. Generate all subsets using brute force recursion and then filter duplicates by storing subsets in a hash set.
B. Use a greedy algorithm that picks elements only if they are not duplicates of the previous element.
C. Use dynamic programming with a 2D table tracking subset sums to avoid duplicates.
D. Sort the array and use backtracking with skipping duplicates at the same recursion depth to avoid repeated subsets.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires generating all unique subsets from an array that may contain duplicates, avoiding duplicate subsets in the output.
  2. Step 2: Identify the approach that handles duplicates efficiently

    Sorting the array groups duplicates together, allowing the backtracking algorithm to skip duplicates at the same recursion level, preventing repeated subsets without extra filtering.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Backtracking with sorting and skipping duplicates is the standard pattern for Subsets II [OK]
Hint: Sort and skip duplicates at recursion level [OK]
Common Mistakes:
  • Using greedy approach misses some subsets
  • DP approach is unrelated to subset generation here
  • Brute force with set filtering is inefficient
3. What is the worst-case time complexity of the optimal backtracking solution with sum bound pruning for Combination Sum III (k numbers from 1 to 9 summing to n)?
medium
A. O(k!) because permutations of k numbers are explored
B. O(k * n) because we explore all sums up to n for k elements
C. O(n^k) because we try all sequences of length k with sum n
D. O(2^9) because each number 1-9 can be either included or excluded, pruning reduces calls but worst case remains exponential

Solution

  1. Step 1: Identify search space size

    Numbers 1 to 9 can be included or excluded, so 2^9 subsets possible.
  2. Step 2: Consider pruning effect

    Pruning reduces calls but worst-case complexity remains O(2^9) since all subsets might be explored.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Backtracking worst case is exponential in number of candidates [OK]
Hint: Backtracking subsets of 9 elements is O(2^9) worst case [OK]
Common Mistakes:
  • Confusing with DP complexity O(k*n)
  • Thinking permutations cause factorial complexity
4. Suppose you want to generate all combinations of size k from numbers 1 to n, but now elements can be reused multiple times in a combination (combinations with replacement). Which modification to the backtracking approach correctly handles this?
hard
A. Use iterative lexicographic generation without any changes
B. Change the recursive call to backtrack(i + 1, path) to prevent reuse of elements
C. Change the recursive call to backtrack(i, path) to allow reuse of the current element
D. Sort the input array before backtracking to handle duplicates

Solution

  1. Step 1: Understand combinations with replacement allow repeated elements

    To allow reuse, the recursive call must not increment start index beyond current element.
  2. Step 2: Modify recursion to backtrack(i, path) to allow current element reuse

    This ensures the same element can be chosen multiple times in subsequent recursive calls.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Using backtrack(i, path) enables combinations with replacement [OK]
Hint: Reuse requires recursive calls with same start index [OK]
Common Mistakes:
  • Incrementing start index prevents element reuse
5. Suppose the problem is modified so that elements can be reused multiple times in the subset (i.e., the subset can contain duplicates). Which modification to the algorithm is necessary to correctly find the largest divisible subset under this new constraint?
hard
A. Modify DP to consider all previous elements including i itself, allowing repeated use, and remove early break
B. Switch to a graph cycle detection algorithm to handle repeated elements
C. Use the same DP approach but allow dp[i] to consider dp[i] itself for reuse, enabling cycles
D. Use a greedy approach picking the largest element repeatedly until no more divisible

Solution

  1. Step 1: Understand reuse impact

    Allowing reuse means elements can appear multiple times, so dp must consider extending from the same element multiple times.
  2. Step 2: Modify DP logic

    DP inner loop must consider j ≤ i (including i itself) and remove early break because sorted order no longer guarantees divisibility breaks.
  3. Step 3: Reject incorrect options

    Greedy fails to find longest chain; graph cycle detection is unnecessary; naive DP without modification misses reuse.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    DP adjusted for reuse and no early break handles duplicates [OK]
Hint: Reuse requires DP to consider self and no early break [OK]
Common Mistakes:
  • Using original DP without changes leads to incorrect results
  • Trying greedy approach which fails on complex divisibility
  • Confusing graph cycles with DP chains
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard