Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Backtracking

Signs that reach a target

Medium · Target 20 minutes · Backtracking· Type asked at

Given an array of non-negative integers nums and an integer target, put a + or a − in front of every number and add them up. Return the number of sign choices whose total equals target.

Examples

InputOutputWhy
nums = [1, 1, 1, 1, 1], target = 35Exactly one of the five 1s gets a minus sign.
nums = [2, 3, 5], target = 022 + 3 − 5 and −2 − 3 + 5.
nums = [0, 0, 1], target = 14A zero can take either sign, so each zero doubles the count.

Constraints

  • 1 ≤ n ≤ 20
  • 0 ≤ nums[i] ≤ 1000
  • 0 ≤ target ≤ 1000

Hints

Hint 1

Each number has two choices, so there are 2ⁿ sign patterns. With n ≤ 20 that is about a million: can you walk them all?

Hint 2

Recurse on the index, carrying the running total. At the end, count 1 if the total equals the target.

Hint 3

The same (index, running total) pair is reached by many different paths. Memoise on it, and the search becomes dynamic programming.

Where people lose marks

  • Skipping zeros or treating +0 and −0 as one choice. They are different sign choices, so each zero doubles the count.
  • Memoising on the index alone. The number of ways depends on the running total too.
  • In the subset-sum form, forgetting the parity check: (total + target) must be even, or there are no solutions.
  • Allowing target larger than the total: no sign pattern can reach it, and a memo table indexed by total + target would overflow its bounds.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.