Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Backtracking

Signs that reach a target

Medium · Target 20 minutes · Backtracking · Type asked atAmazonBloomberg

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.

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.