FastPrepCombination Sum with Unlimited Reuse

Combination Sum with Unlimited Reuse

NVIDIA logoNVIDIA● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an integer array candidates with distinct positive values and a nonnegative integer target, return every combination of candidate values whose sum is exactly target. Each candidate value may be reused any number of times.

Combination rules

  • A combination is determined by how many times each candidate value is selected. Different arrangements of the same selected values are one combination.
  • Represent each combination as a nondecreasing integer array. Return each distinct combination exactly once.
  • The input candidates may be in any order. Leave the supplied array unchanged.
  • If target = 0, return [[]]: the one empty combination.
  • If no combination reaches a positive target, return [].

Result order

Order the returned rows in decreasing numeric lexicographic order. Compare integer values from left to right; at the first unequal position, the row with the larger integer comes first. If one row is a prefix of the other, place the longer row first.

For example, [7] comes before [2,2,3], and [1,3] comes before [1,1,2]. Compare integers rather than their decimal strings.

What the interview report shared

The report gives distinct candidates, unlimited reuse, and the example candidates = [2,3,6,7], target = 7, output = [[7],[2,2,3]]. The candidate used recursion or DFS. The positive-value bounds, edge cases, and deterministic ordering above define this practice version.

Function

combinationSum(candidates: int[], target: int) → int[][]

Examples

Example 1

candidates = [2,3,6,7]target = 7return = [[7],[2,2,3]]

The combinations are [7] and [2,2,3]. Both sum to 7, and the row beginning with 7 comes first in decreasing numeric lexicographic order.

Example 2

candidates = [2]target = 1return = []

Every selected value is at least 2, so no combination can sum to 1.

Example 3

candidates = [1,2]target = 0return = [[]]

Selecting no values gives the empty combination, whose sum is 0. Positive candidates cannot form any other zero-sum combination.

Constraints

  • 0 <= candidates.length <= 6.
  • Every candidate value is a distinct integer in [1,30].
  • 0 <= target <= 20.
  • The candidates may be unsorted. Do not modify the supplied array.

More NVIDIA problems

See NVIDIA hiring insights
public int[][] combinationSum(int[] candidates, int target) {
    // Return every unique combination in the required order.
}
candidates[2,3,6,7]
target7
expected[[7],[2,2,3]]
Checking account…