DSA interview question
A budgeting app lists the prices of items a user is considering and asks: in how many different ways can they pick items whose total is exactly K? Two picks count as different if they use different positions, even when the values are equal, and prices can be 0 (free items), which doubles the number of ways. The recursive pick/skip count is the natural first answer, but it is exponential. Since the sums are bounded, the same recursion turns into an O(n · K) DP over "number of ways to reach each sum", with the answer reported modulo 10⁹ + 7.
Example: [5, 2, 3, 10, 6, 8], K = 10 → 3 ({2, 8}, {10}, {5, 2, 3}).
int perfectSum(const vector<int>& arr, int k); // non-negative values; count modulo 1e9 + 7
Input (arr, K) | Output | Explanation |
|---|---|---|
([5, 2, 3, 10, 6, 8], 10) | 3 | {2, 8}, {10}, {5, 2, 3} |
([2, 5, 1, 4, 3], 10) | 3 | {2, 5, 3}, {2, 1, 4, 3}, {5, 1, 4} |
([0, 0, 1], 1) | 4 | Each 0 can be in or out |
([1, 1, 1], 2) | 3 | Positions are distinct |
([3], 5) | 0 |
(Confirm: values are non-negative; subsequences are counted by positions; the empty subsequence counts when K = 0.)
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