FastPrepSubset Sum to Target

Subset Sum to Target

Goldman Sachs logoGoldman Sachs● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given an array nums of signed integers and a signed integer target. Determine whether some subset of array indices has values summing exactly to target. Each index may be selected at most once, and the empty subset is allowed.

Return 1 if such a subset exists; otherwise return 0.

Function

hasSubsetSum(nums: int[], target: int) → int

Examples

Example 1

nums = [3,34,4,12,5,2]target = 9return = 1

Selecting 4 and 5 reaches the target 9.

Example 2

nums = [2,-4,7]target = 1return = 0

The possible non-empty sums are 2, -4, 7, -2, 9, 3, and 5, so no subset reaches 1.

Constraints

  • 0 <= nums.length <= 30.
  • -10^9 <= nums[i], target <= 10^9.
  • Use 64-bit arithmetic for intermediate subset sums.

More Goldman Sachs problems

See Goldman Sachs hiring insights
public int hasSubsetSum(int[] nums, int target) {
    // Return 1 when a subset reaches target, otherwise 0.
}
nums[3,34,4,12,5,2]
target9
expected1
Checking account…