Back to Practice Dashboard
Top 150 InterviewMedium
Target Sum
Learn how to solve the 'Target Sum' problem. This detailed resource details brute force and optimized approaches.
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?
Define subproblem states, establish the recurrence relation, and use memoization (top-down) or tabulation (bottom-up).
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.