Top 150 InterviewMedium

Target Sum

Detailed guide and Python implementation for the 'Target Sum' problem.

Problem Statement

Medium

You are given an integer array nums and an integer target.

You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.

Return the number of different expressions that you can build, which evaluates to target.

Write a function findTargetSumWays(nums: List[int], target: int) -> int.

Constraints
  • 1 <= len(nums) <= 20
  • 0 <= nums[i] <= 1000
  • 0 <= sum(nums) <= 1000
  • -1000 <= target <= 1000

Examples

Example 1
Input
nums = [1,1,1,1,1], target = 3
Output
5
Explanation

There are 5 ways: -1+1+1+1+1, +1-1+1+1+1, +1+1-1+1+1, +1+1+1-1+1, +1+1+1+1-1.

Example 2
Input
nums = [1], target = 1
Output
1
Explanation

+1 = 1

Need a Hint?
Consider using 2D DP-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.