Skip to main content

Target Sum

Given an array of integers and a target sum Assign + or - to each number to reach the target Return the number of different ways to achieve this Example: nums = [1,1,1,1,1], target = 3 => 5 ways (+1+1+1+1+1 = 5, +1+1+1-1-1 = 1, etc.)

Target Sum is a dynamic programming question: define the state cleanly and the transitions usually follow. Interviewers love it because it reveals your state-and-transition thinking and your edge-case discipline. Don't rush the code—spend your time nailing the state definition first.

Examples

You write

find_target_sum_ways(nums: List[int], target: int)

  1. Example 1

    Input
    nums = [1,1,1,1,1], target = 3
    returns
    5
  2. Example 2

    Input
    nums = [1], target = 1
    returns
    1

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Backtracking

I reach for it when

  • The question asks for all combinations, permutations or placements.
  • You make a choice, explore it, and may need to take it back.

Say this before you type. Say the choice, the stopping rule, and the earliest moment you can prune.

All 15 Backtracking problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Count Ways to Reach Target Summedium