Target Sum
Problem Statement
You get a list of numbers nums and a number target. Put a + or a - in front of every number, then add all of them up.
Count how many ways of choosing the signs make the total equal to target.
nums, a list of non-negative integers, and target, an integer.
The number of ways to put a + or - before each number so that the total is target.
The minus sign can go on any one of the five 1s, which gives five ways: for example −1 + 1 + 1 + 1 + 1 = 3.
Only +1 gives 1.
The biggest total is 1 + 2 = 3, so 4 cannot be reached.
- • 1 ≤ nums.length ≤ 20
- • 0 ≤ nums[i] ≤ 1000
- • 0 ≤ sum(nums) ≤ 1000
- • −1000 ≤ target ≤ 1000
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Recurse on each number with a + or a −; count the sign patterns whose total is the target
The same recursion, but remember each (index, running sum) pair so it is solved only once
P = (total + target) / 2; check it is a whole number in range, then count subsets with sum P
Each number gets a + or a -. Walk the numbers in order and try both signs for each one. When every number has a sign, check whether the total equals target. Each sign pattern is exactly one path, so the paths that end at the target are the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Knapsack translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.