DSA interview question
You're building a "grant allocation validator" for a nonprofit's finance system. Given an array of donation amounts arr and a target grant amount K, the finance team wants to know how many distinct combinations of donations could have been bundled together to exactly fund a grant of size K — useful for auditing which donation groupings are even mathematically possible before manually verifying paperwork. Given array arr and integer K, return the number of subsets of arr whose sum equals K.
int countSubsetsWithSumK(vector<int>& arr, int K);
arr | K | Output | Explanation |
|---|---|---|---|
[1,2,3,3] | 6 | 3 | {1,2,3}, {1,2,3} (using the other 3), {3,3} — 3 distinct subsets sum to 6 |
[1,1,1,1] | 2 | 6 | choose any 2 of the four 1s → C(4,2) = 6 |
[5] | 5 | 1 | {5} itself |
[5] | 0 | 1 | empty subset — sums to 0 |
[] | 0 | 1 | empty array, target 0 → one way: the empty subset |
[] | 5 | 0 | empty array, positive target unreachable |
[0,0,1] | 1 | 4 | zeros can be freely included or excluded without affecting sum — classic doubling trap |
(Note: the empty subset always counts toward K=0 — a very common off-by-one/base-case trap if not handled carefully.)
K = 0? (Standard convention: yes, exactly one way.)arr? (Yes, typically — duplicates are treated as distinct elements by position, even if their values are equal.)K and array size? (Signals whether O(n·K) DP is acceptable, and what capacity the DP array needs.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in