Subset sum to a target
Given a list of positive integers nums and a non-negative integer target, decide whether some subset of nums adds up to exactly target. Each element may be used at most once, though equal values at different positions count as separate elements.
Implement:
def can_reach_target(nums: list[int], target: int) -> bool: ...
Return True if such a subset exists and False otherwise. The empty subset sums to 0, so target = 0 is always reachable.
Constraints
0 <= len(nums) <= 2001 <= nums[i] <= 10000 <= target <= 10^5
Example 1
nums = [4, 9, 2, 7], target = 13
-> True (4 + 9, or 4 + 2 + 7)
Example 2
nums = [5], target = 10
-> False (the single 5 cannot be used twice)
Be ready to return one subset that reaches the target, not just a yes/no answer.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
