Reachable sum with reusable values and a huge target
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google. It tests dynamic programming, shortest path and number theory.
Given a non-empty list nums of positive integers and a target k, return true if some multiset of values from nums sums to exactly k, and false otherwise. You may use each value any number of times. The list may contain duplicates.
Implement:
def subset_sum_equals_k(nums: list[int], k: int) -> bool: ...
Constraints
1 <= len(nums) <= 10001 <= nums[i] <= 10^4-
1 <= k <= 10^12. The target is far too large to loop over every sum from 0 tok.
Example 1
nums = [4, 6], k = 14 -> true (4 + 4 + 6)
nums = [4, 6], k = 15 -> false (every sum is even)
Example 2
nums = [5, 7], k = 23 -> false
nums = [5, 7], k = 24 -> true (5 + 5 + 7 + 7)
Follow-ups may ask you to return the multiset itself, answer many targets for the same list, or forbid reusing an element.
Clarifying questions
- Is
k = 0possible, and is it reachable with the empty multiset? - Are duplicates in
numsjust redundant, since values can be reused anyway? - Is a yes or no answer enough, or is the multiset needed?
- Will many targets be asked for the same
nums?
What a strong answer covers
- Explains why a DP over every sum up to
kfails at10^12. - Uses the smallest value
m: if a sumsis reachable, so iss + m, so for each remainderrmodmonly the smallest reachable sumdist[r]matters. - Computes
distwith Dijkstra (or a BFS-like relaxation) onmnodes, one edge per distinct value:O(m * d log m)forddistinct values, about10^4nodes. - Answers
k >= dist[k % m]; mentions the gcd as a quick filter (kmust be a multiple ofgcd(nums)). - Tests both examples,
numswith a single value, and coprime values with a largek.
Follow-ups
- Return the multiset itself.
- Answer many targets for the same list (precompute
distonce). - Each element may be used at most once.
Where it's asked
What it tests
dynamic programming · shortest path · number theory
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
