Introduction

The Count Subset With Target Sum II problem asks us to count the number of subsets whose sum equals a given target k.

At first glance, this looks like a classic subset-sum problem that can be solved using recursion or dynamic programming. However, there is an important constraint:

Code
1 ≤ n ≤ 40

Additionally:

Code
-10^7 ≤ arr[i], k ≤ 10^7

Because the array can contain negative numbers and the size can reach 40, traditional DP approaches become impractical.

This is where the powerful Meet in the Middle (MITM) technique comes into play.

Problem Statement

Given:

Code
arr[]

and an integer:

Code
k

Find the number of subsets whose sum equals:

Code
k

Return the count.

Example 1

Input

Code
arr = [1, 3, 2]
k = 3

Valid Subsets

Code
[3]
[1,2]

Output

Code
2

Example 2

Input

Code
arr = [4,2,3,1,2]
k = 4

Valid Subsets

Code
[4]
[2,2]
[3,1]

Output

Code
3

Example 3

Input

Code
arr = [10,20,30]
k = 25

No subset sums to 25.

Output

Code
0

Why Brute Force Fails

A subset can either:

  • Include an element

  • Exclude an element

For n elements:

Code
Total Subsets = 2^n

For:

Code
n = 40

we get:

Code
2^40 ≈ 1 trillion

Checking all subsets is impossible.

Complexity

Code
O(2^n)

This is too slow.

Key Observation

The constraint:

Code
n ≤ 40

suggests splitting the array into two halves.

Example:

Code
[4,2,3,1,2]

Split into:

Code
Left  = [4,2]
Right = [3,1,2]

Instead of generating:

Code
2^40

subsets, generate:

Code
2^20 + 2^20

subsets.

This is dramatically smaller.

Meet in the Middle Concept

Divide the array into two halves.

Code
Left Half
Right Half

Generate all subset sums for both halves.

Example:

Code
Left = [1,3]

Subset sums:

Code
0
1
3
4

For:

Code
Right = [2]

Subset sums:

Code
0
2

Now find combinations where:

Code
leftSum + rightSum = k

instead of checking all subsets directly.

Generating Subset Sums

Suppose:

Code
Left = [1,3]

Possible subsets:

Code
{}
{1}
{3}
{1,3}

Sums:

Code
0
1
3
4

Store them in a list.

Matching Target Sum

For every sum:

Code
x

from the left half, we need:

Code
k - x

from the right half.

If that value appears multiple times, all occurrences contribute to the answer.

Efficient Counting

Store frequencies of right-half subset sums.

Example:

Right Sums

Code
0
2
2
4

Frequency Map

Code
0 → 1
2 → 2
4 → 1

Now for each left sum:

Code
required = k - leftSum

Add:

Code
frequency(required)

to the answer.

Algorithm

Step 1

Split the array into:

  • Left Half

  • Right Half

Step 2

Generate all subset sums of the left half.

Step 3

Generate all subset sums of the right half.

Step 4

Store right-half sums in a HashMap.

Java
Map<Long,Integer>

to count frequencies.

Step 5

For every left sum:

Code
required = k - leftSum

If present in the map:

Code
answer += frequency(required)

Step 6

Return the answer.

Dry Run

Input

Code
arr = [1,3,2]
k = 3

Split

Code
Left  = [1]
Right = [3,2]

Left Sums

Subsets:

Code
{}
{1}

Sums:

Code
0
1

Right Sums

Subsets:

Code
{}
{3}
{2}
{3,2}

Sums:

Code
0
3
2
5

Frequency Map

Code
0 → 1
2 → 1
3 → 1
5 → 1

Matching

For:

Code
leftSum = 0

Need:

Code
3

Found once.

Answer:

Code
1

For:

Code
leftSum = 1

Need:

Code
2

Found once.

Answer:

Code
2

Final Answer

Code
2

Java Solution

Java
class Solution {

    private void generateSums(int[] arr,
                              int start,
                              int end,
                              long sum,
                              ArrayList<Long> sums) {

        if (start == end) {
            sums.add(sum);
            return;
        }

        generateSums(arr, start + 1, end,
                     sum, sums);

        generateSums(arr, start + 1, end,
                     sum + arr[start], sums);
    }

    public int countSubset(int[] arr, int k) {

        int n = arr.length;

        int mid = n / 2;

        ArrayList<Long> leftSums = new ArrayList<>();
        ArrayList<Long> rightSums = new ArrayList<>();

        generateSums(arr, 0, mid, 0, leftSums);

        generateSums(arr, mid, n, 0, rightSums);

        HashMap<Long, Integer> freq = new HashMap<>();

        for (long sum : rightSums) {
            freq.put(sum,
                freq.getOrDefault(sum, 0) + 1);
        }

        long answer = 0;

        for (long left : leftSums) {

            long required = (long) k - left;

            answer += freq.getOrDefault(required, 0);
        }

        return (int) answer;
    }
}

Why Use Long?

Although:

Code
arr[i] ≤ 10^7

we may sum up to:

Code
40 × 10^7

which can exceed integer limits.

Therefore:

Code
long

is safer for subset sums.

Complexity Analysis

Let:

Code
n = 40

Split:

Code
20 + 20

Generating Subset Sums

For each half:

Code
O(2^(n/2))

Building Frequency Map

Code
O(2^(n/2))

Matching

Code
O(2^(n/2))

Total Time Complexity

Code
O(2^(n/2))

which matches the expected complexity.

Space Complexity

Store subset sums:

Code
O(2^(n/2))

For:

Code
n = 40

this becomes:

Code
O(2^20)

which is manageable.

Why Meet in the Middle Works

Instead of exploring:

Code
2^40

subsets directly, we explore:

Code
2^20 + 2^20

subsets and combine the results efficiently.

This reduces the search space from:

Code
1,099,511,627,776

to approximately:

Code
2,097,152

operations.

That is the key idea behind Meet in the Middle.

Edge Cases

Empty Subset Equals Target

Code
arr = [1,2]
k = 0

Valid subset:

Code
{}

Answer:

Code
1

Negative Numbers

Code
arr = [-1,1]
k = 0

Subsets:

Code
{}
[-1,1]

Answer:

Code
2

The MITM approach naturally handles negative numbers.

No Valid Subset

Code
arr = [10,20,30]
k = 5

Answer:

Code
0

Conclusion

The Count Subset With Target Sum II problem is a classic application of the Meet in the Middle technique.

The key insight is:

Split the array into two halves, generate all subset sums separately, and efficiently combine them using a frequency map.

This transforms an impossible:

Code
O(2^n)

solution into:

Code
O(2^(n/2))

which is exactly what the constraints require.

Final Complexity

Code
Time Complexity  : O(2^(n/2))
Space Complexity : O(2^(n/2))

making it ideal for arrays of size up to 40.