← Questions

Reachable sum with reusable values and a huge target

0
GoogleCoding

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) <= 1000
  • 1 <= nums[i] <= 10^4
  • 1 <= k <= 10^12. The target is far too large to loop over every sum from 0 to k.

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 = 0 possible, and is it reachable with the empty multiset?
  • Are duplicates in nums just 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 k fails at 10^12.
  • Uses the smallest value m: if a sum s is reachable, so is s + m, so for each remainder r mod m only the smallest reachable sum dist[r] matters.
  • Computes dist with Dijkstra (or a BFS-like relaxation) on m nodes, one edge per distinct value: O(m * d log m) for d distinct values, about 10^4 nodes.
  • Answers k >= dist[k % m]; mentions the gcd as a quick filter (k must be a multiple of gcd(nums)).
  • Tests both examples, nums with a single value, and coprime values with a large k.

Follow-ups

  • Return the multiset itself.
  • Answer many targets for the same list (precompute dist once).
  • Each element may be used at most once.

Where it's asked

What it tests

dynamic programming · shortest path · number theory

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding