Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Subset Sum Implementation in Java

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Subset Sum runs in O(n*S) time and O(n*S) space, in Java as in every other language.
  • ✓java.util.BitSet is the right packed container: set(0), or(other), get(target), all over a long[] internally.
  • ✓boolean[], never Boolean[] or List<Boolean>, and the descending for (int s = target; s >= x; s--).
  • ✓The Java trap: BitSet reports three different sizes and grows behind your back. size() is the allocated capacity rounded up to a multiple of 64, length() is highest-set-bit + 1, and cardinality() counts set bits, so for (int i = 0; i < bits.size(); i++) walks padding bits that were never yours.
  • ✓A boolean[] cell is one byte, so a million-cell row is 1 MB, which overflows a typical per-core L2 and streams from L3 with a hardware prefetcher that handles the sequential descending sweep well.

What Subset Sum actually is

Subset Sum asks: given n non-negative integers and a target S, is there a subset that adds to exactly S? The standard solution is a boolean DP over (items considered) x (0..S): reachable[s] is true when s can be formed from the items seen so far. Time O(n*S), space O(S) with a rolling row. That S in the bound is the value, not the input size, so this is pseudo-polynomial and only practical when S is small. Engineers reach for it in partitioning and load balancing, making change from fixed denominations, budget/knapsack feasibility checks, and as the canonical reduction target in NP-hardness proofs.

Subset Sum in Java: what you actually reach for

java.util.BitSet is the right packed container: set(0), or(other), get(target), all over a long[] internally. It has no shift method, so the shift-or step is either a walk with nextSetBit writing shifted.set(i + x), or you switch to java.math.BigInteger, which does expose shiftLeft(int) and or(BigInteger). For the plain table, boolean[] is the default and is one byte per element in HotSpot. Streams add nothing here; IntStream.range with a stateful boolean[] is worse than the plain loop.

Java implementation

boolean[], never Boolean[] or List<Boolean>, and the descending for (int s = target; s >= x; s--). Reviewers reject int[][] dp = new int[n][target + 1] when one row suffices, reject Arrays.fill inside the item loop, and expect Objects.requireNonNull(nums) plus an explicit target guard before allocating. The method takes int[], returns boolean, and must not sort the caller's array in place; if you need sorted input, clone it and say so in the javadoc.
java
import java.util.BitSet;
import java.util.Objects;

public final class SubsetSum {
    private SubsetSum() {}

    public static boolean solve(int[] nums, int target) {
        Objects.requireNonNull(nums);
        if (target < 0) return false;
        boolean[] reachable = new boolean[target + 1];
        reachable[0] = true;
        for (int x : nums) {
            if (x <= 0 || x > target) continue;
            for (int s = target; s >= x; s--) {
                if (reachable[s - x]) reachable[s] = true;
            }
            if (reachable[target]) return true;
        }
        return reachable[target];
    }

    public static boolean solveBits(int[] nums, int target) {
        BitSet bits = new BitSet(target + 1);
        bits.set(0);
        for (int x : nums) {
            if (x <= 0 || x > target) continue;
            BitSet shifted = new BitSet(target + 1);
            for (int s = bits.nextSetBit(0); s >= 0 && s + x <= target; s = bits.nextSetBit(s + 1)) {
                shifted.set(s + x);
            }
            bits.or(shifted);
            if (bits.get(target)) return true;
        }
        return bits.get(target);
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Java-specific trap

BitSet reports three different sizes and grows behind your back. size() is the allocated capacity rounded up to a multiple of 64, length() is highest-set-bit + 1, and cardinality() counts set bits, so for (int i = 0; i < bits.size(); i++) walks padding bits that were never yours. Worse, new BitSet(target + 1) is only a hint: set(target + 5) silently expands the set rather than throwing, and because or() widens the receiver to the wider operand, an unmasked shift-or ends up holding memory proportional to the total of all items instead of to target.

Performance in Java, beyond the O(n*S)

A boolean[] cell is one byte, so a million-cell row is 1 MB, which overflows a typical per-core L2 and streams from L3 with a hardware prefetcher that handles the sequential descending sweep well. A Boolean[] cell is instead a reference to one of the two cached Boolean.TRUE/FALSE singletons, since autoboxing goes through Boolean.valueOf, so it costs 4 or 8 bytes per cell rather than one and every read is a pointer dereference instead of a byte load; there is no per-cell allocation and no GC pressure, so what you pay is footprint and indirection, typically a few times slower rather than an order of magnitude. The JIT removes the array bounds check only once the loop is hot and the range is provable, so the 5-10x step change lands after C2 compiles the method a few thousand iterations in: always warm up before timing or you measure the interpreter. BitSet.or works 64 bits at a time, but BitSet has no shift, so building the shifted operand costs an O(set bits) nextSetBit walk plus an allocation per item and the packed or() cannot pay for it: measured at n=400 and target=200k the BitSet formulation runs about 4x slower than the plain boolean[] row. Use boolean[] for the DP, and reach for BigInteger.shiftLeft/or if you want a genuinely word-parallel shift-or in the standard library. The asymptotic cost is the same in every language, O(n*S) time and O(n*S) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Subset Sum between languages.

Real-World Applications

Subset Sum applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Subset Sum helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Subset Sum appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Subset Sum over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Subset Sum to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

Frequently Asked Questions

Which Java type or library should I use for Subset Sum?

java.util.BitSet is the right packed container: set(0), or(other), get(target), all over a long[] internally. It has no shift method, so the shift-or step is either a walk with nextSetBit writing shifted.set(i + x), or you switch to java.math.BigInteger, which does expose shiftLeft(int) and or(BigInteger). For the plain table, boolean[] is the default and is one byte per element in HotSpot. Streams add nothing here; IntStream.range with a stateful boolean[] is worse than the plain loop.

What is the most common Java mistake when implementing Subset Sum?

BitSet reports three different sizes and grows behind your back. size() is the allocated capacity rounded up to a multiple of 64, length() is highest-set-bit + 1, and cardinality() counts set bits, so for (int i = 0; i < bits.size(); i++) walks padding bits that were never yours. Worse, new BitSet(target + 1) is only a hint: set(target + 5) silently expands the set rather than throwing, and because or() widens the receiver to the wider operand, an unmasked shift-or ends up holding memory proportional to the total of all items instead of to target.

How does Subset Sum actually perform in Java?

A boolean[] cell is one byte, so a million-cell row is 1 MB, which overflows a typical per-core L2 and streams from L3 with a hardware prefetcher that handles the sequential descending sweep well. A Boolean[] cell is instead a reference to one of the two cached Boolean.TRUE/FALSE singletons, since autoboxing goes through Boolean.valueOf, so it costs 4 or 8 bytes per cell rather than one and every read is a pointer dereference instead of a byte load; there is no per-cell allocation and no GC pressure, so what you pay is footprint and indirection, typically a few times slower rather than an order of magnitude. The JIT removes the array bounds check only once the loop is hot and the range is provable, so the 5-10x step change lands after C2 compiles the method a few thousand iterations in: always warm up before timing or you measure the interpreter. BitSet.or works 64 bits at a time, but BitSet has no shift, so building the shifted operand costs an O(set bits) nextSetBit walk plus an allocation per item and the packed or() cannot pay for it: measured at n=400 and target=200k the BitSet formulation runs about 4x slower than the plain boolean[] row. Use boolean[] for the DP, and reach for BigInteger.shiftLeft/or if you want a genuinely word-parallel shift-or in the standard library. Time complexity is O(n*S) and space is O(n*S).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.