FastPrepAll Subsets with a Given Sum

All Subsets with a Given Sum

Apple logoApple● MediumNEW GRADPHONE SCREEN

Problem statement

Given an array arr of distinct positive integers and a nonnegative integer target, return every subset whose sum equals target. Each array element may be used at most once.

List each subset in increasing numeric order. List the subsets in lexicographic order: compare the first differing values, with the smaller value first; if one list is a prefix of the other, put the shorter list first.

The empty subset has sum zero and must be returned when target is zero. Return an empty list when no subset works. Use backtracking for the final approach, and discuss the exponential search cost and the space used by returned subsets.

Function

subsetsWithSum(arr: int[], target: int) → int[][]

Examples

Example 1

arr = [3,1,2,5]target = 5return = [[2,3],[5]]

The subsets [2,3] and [5] both sum to 5. No other subset does. Since 2 is less than 5, [2,3] comes first.

Example 2

arr = [2,4]target = 0return = [[]]

The empty subset sums to zero. Every nonempty subset has a positive sum, so the empty subset is the only result.

Constraints

  • 0 <= arr.length <= 16.
  • Every value in arr is between 1 and 100, inclusive.
  • All values in arr are distinct.
  • 0 <= target <= 1600.

More Apple problems

See Apple hiring insights
Saved
public int[][] subsetsWithSum(int[] arr, int target) {
    // Write your solution here.
}
Checking account…