Problem 494

Abstract / Summary

Given a set of numbers and a target, can you use plus or minus on each number to make their sum equal the target

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0494.py

class Solution:
    def half(self, nums, target):
        size  = len(nums)
        mid   = size // 2
        left  = nums[:mid]
        right = nums[mid:]

        limit = 2 ** mid
        current = 0
        leftSum = defaultdict(int)
        for current in range(limit):
            have = 0
            mask = limit
            for j in range(mid):
                mask >>= 1
                if (current & mask) == 0:
                    have += left[j]
                else:
                    have -= left[j]
            leftSum[have] += 1

        limit = 2 ** (size - mid)
        current = 0
        rightSum = defaultdict(int)
        for current in range(limit):
            have = 0
            mask = limit
            for j in range(size - mid):
                mask >>= 1
                if (current & mask) == 0:
                    have += right[j]
                else:
                    have -= right[j]
            rightSum[have] += 1

        result = 0
        for l in leftSum:
            howOften = leftSum[l]
            need = target - l
            if need in rightSum:
                result += howOften * rightSum[need]
        return result


    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        size = len(nums)
        if size > 5:
            return self.half(nums, target)

        nums.sort(reverse = True)
        total = sum(nums)

        remaining = [0] * size
        for i in range(size):
            total -= nums[i]
            remaining[i] = total

        loops = 0

        result = 0
        limit = 2**size
        current = 0
        while current < limit:
            have = 0
            mask = limit
            for j in range(size):
                mask >>= 1
                if (current & mask) == 0:
                    have += nums[j]
                else:
                    have -= nums[j]

                need = target - have
                # already too big or too small ?
                if need > +remaining[j] or need < -remaining[j]:
                    current += mask - 1
                    break

            if have == target:
                result += 1

            current += 1
            loops += 1

        return result
85 lines | 2313 bytes | submitted August 16, 2023 | GitHub   1% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “Target Sum” problem: given an integer array nums and a target value, count the number of ways to assign a ‘+’ or ‘-’ sign to each element so that the resulting expression equals the target. Two distinct strategies are employed based on the length of the input array. For arrays longer than five elements a meet-in-the-middle approach is used, while shorter arrays are processed with a depth-first enumeration that incorporates a pruning technique based on remaining possible sums.

Meet-in-the-Middle Path

When the array length exceeds five, the method half is invoked. The core idea is to split the array into two halves, enumerate all possible signed sums for each half, and then combine the results.

Splitting the Input

size  = len(nums)
mid   = size // 2
left  = nums[:mid]
right = nums[mid:]

The split point mid is the integer division of the total size, ensuring that the left half contains mid elements and the right half contains the remainder.

Enumerating Signed Sums for the Left Half

limit = 2 ** mid
leftSum = defaultdict(int)
for current in range(limit):
    have = 0
    mask = limit
    for j in range(mid):
        mask >>= 1
        if (current & mask) == 0:
            have += left[j]
        else:
            have -= left[j]
    leftSum[have] += 1

limit represents the total number of sign configurations for the left half (each element can be ‘+’ or ‘-’). The outer loop iterates over every configuration encoded as a binary number. Inside, a shifting mask extracts each bit to decide whether to add or subtract the corresponding element. The resulting sum have is stored in a dictionary that counts how many configurations produce that sum.

Enumerating Signed Sums for the Right Half

limit = 2 ** (size - mid)
rightSum = defaultdict(int)
for current in range(limit):
    have = 0
    mask = limit
    for j in range(size - mid):
        mask >>= 1
        if (current & mask) == 0:
            have += right[j]
        else:
            have -= right[j]
    rightSum[have] += 1

The right half is processed analogously, with its own limit based on the number of elements in that half. The dictionary rightSum records the frequency of each possible signed sum.

Combining the Two Halves

result = 0
for l in leftSum:
    howOften = leftSum[l]
    need = target - l
    if need in rightSum:
        result += howOften * rightSum[need]
return result

For each sum l achievable by the left half, the algorithm computes the complementary sum need that the right half must provide to reach the overall target. If need exists in rightSum, the product of the frequencies yields the number of full-array configurations that satisfy the target. This step avoids explicit enumeration of the full search space, reducing the combinatorial explosion from 2^n to roughly 2^{n/2}.

Pruned Enumeration for Small Arrays

When the array length is five or fewer, the method findTargetSumWays proceeds with a direct enumeration but incorporates a pruning mechanism that skips large swaths of the search space when the remaining elements cannot possibly satisfy the target.

Sorting and Pre-computing Remaining Sums

nums.sort(reverse = True)
total = sum(nums)

remaining = [0] * size
for i in range(size):
    total -= nums[i]
    remaining[i] = total

The array is sorted in descending order, which tends to increase the effectiveness of the pruning because larger numbers are considered earlier. The list remaining stores, for each index i, the sum of all elements that appear after i. This information is later used to bound the achievable range of the expression from that point onward.

Enumerating Configurations with Early Exit

limit = 2**size
current = 0
while current < limit:
    have = 0
    mask = limit
    for j in range(size):
        mask >>= 1
        if (current & mask) == 0:
            have += nums[j]
        else:
            have -= nums[j]

        need = target - have
        if need > +remaining[j] or need < -remaining[j]:
            current += mask - 1
            break
    if have == target:
        result += 1
    current += 1

The outer while loop walks through every binary configuration of signs. Inside, the inner for loop builds the partial sum have element by element. After each addition or subtraction, the algorithm computes the residual value need required to reach the target. The condition

if need > +remaining[j] or need < -remaining[j]:

detects when the remaining unprocessed elements, even if all assigned the most favorable signs, cannot bridge the gap to the target. In such a case the algorithm jumps ahead by adding mask - 1 to current, effectively skipping all configurations that share the same prefix up to index j. This leap is possible because the binary representation of current determines the sign choices for the remaining positions; incrementing by mask - 1 moves to the next distinct prefix.

If the loop completes without breaking, the full configuration is evaluated; a match increments result. The current counter is then advanced to examine the next configuration.

Edge Cases Handled

The code gracefully handles an empty input array. In that scenario size is zero, mid becomes zero, and both halves are empty. The enumeration loops run with limit = 1, producing a single sum of zero for each half. The combination step then checks whether target equals zero, yielding a count of one if it does and zero otherwise.

When the target value is zero, the algorithm correctly counts configurations that balance positive and negative contributions. The pruning logic in the small-array path also respects the zero target, because the need calculation reduces to -have, and the bounds derived from remaining remain valid.

The meet-in-the-middle method works for odd-length arrays because the split uses integer division, leaving the right half with one more element when size is odd. The enumeration loops adapt to the exact half sizes, ensuring all configurations are covered.

Sorting in descending order does not affect correctness; it only influences the order in which pruning checks are performed. The algorithm still explores every possible sign assignment, either directly or via the skip mechanism.

Performance Optimizations

The primary optimization is the meet-in-the-middle technique, which reduces the effective exponential factor by half. By storing frequencies of partial sums in hash maps (defaultdict(int)), the algorithm avoids recomputing identical sub-expressions and enables constant-time lookups when pairing left and right contributions.

The use of a bitmask (mask) that is shifted on each iteration provides an efficient way to extract individual bits without additional arithmetic. This approach eliminates the need for costly list slicing or index calculations inside the inner loops.

In the small-array enumeration, the pre-computed remaining array supplies tight bounds for early termination. The conditional jump current += mask - 1 skips an entire block of configurations that share a common prefix, dramatically cutting down the number of iterations when the target is far from the reachable range given the remaining numbers.

Sorting the array in descending order further enhances pruning effectiveness because larger magnitudes are considered earlier, causing the residual need to exceed the possible range more frequently, which triggers the skip logic sooner.

The combination of these strategies yields a solution that scales well for moderate input sizes while remaining exact for all edge conditions.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big bag of numbered blocks and you want to put a plus sign or a minus sign in front of each one so that they all add up to a special goal number. This code is like a clever helper that finds all the different ways to do that.

Since trying every single combination one by one takes a very long time when there are many blocks, the code uses a neat shortcut. It takes the pile of blocks and splits it into two smaller heaps of equal size. It figures out every possible total for the first heap and keeps those totals in a notebook. Then it does the same thing for the second heap.

After it has those two notebooks ready, it looks for pairs of numbers, one from each notebook, that combine to reach the goal. By doing this, the computer does not have to check as many combinations, making the work go much faster, almost like solving a giant puzzle by working on two sides at once.

If there are only a few blocks, the computer uses a slightly different approach. It checks the sums and is smart enough to stop early if it sees that the numbers will never reach the goal, which keeps it from wasting time looking at paths that cannot possibly work. It moves through the numbers in a steady way, making sure it finds every single way to reach the target without missing any.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.00 | σ = 1.56

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
ruoru Rust
Shamik07 Dart
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
fsq Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
ruoru Rust
Shamik07 Dart
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak Python
48 links | 32 authors | 11 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

2 easy 5 medium
8 solutions   August 16, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality