Subset Sum Implementation in Rust
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 Rust as in every other language.
- ✓std has no bit set. The two honest choices are vec![false; target + 1] (a Vec<bool>, one byte per cell) or a hand-rolled Vec<u64> word array where you set bit s with w[s >> 6] |= 1 << (s & 63).
- ✓Take &[u64] or &[u32], not Vec<T> by value, and index with usize. The sweep is written for s in (x..=target).rev(); a reviewer rejects (0..=target).rev() with an inner if s >= x as wasted iterations.
- ✓The Rust trap: usize subtraction is the one that bites. dp[s - x] with s < x does not produce a negative index: usize underflows, and the failure mode differs by build profile.
- ✓Vec<bool> is one byte per cell with a bounds check on every index; LLVM hoists that check only when it can prove the range, which the (x..=target).rev() form helps it do, while slice iteration removes it entirely.
What Subset Sum actually is
Subset Sum in Rust: what you actually reach for
Rust implementation
pub fn subset_sum(nums: &[u64], target: usize) -> bool {
let mut reachable = vec![false; target + 1];
reachable[0] = true;
for &x in nums {
let x = x as usize;
if x == 0 || x > target {
continue;
}
for s in (x..=target).rev() {
if reachable[s - x] {
reachable[s] = true;
}
}
if reachable[target] {
return true;
}
}
reachable[target]
}
pub fn subset_sum_words(nums: &[u64], target: usize) -> bool {
let words = target / 64 + 1;
let mut bits = vec![0u64; words];
bits[0] = 1;
for &x in nums {
let x = x as usize;
if x == 0 || x > target {
continue;
}
let (word, off) = (x / 64, x % 64);
for i in (word..words).rev() {
let mut v = bits[i - word] << off;
if off > 0 && i > word {
v |= bits[i - word - 1] >> (64 - off);
}
bits[i] |= v;
}
}
(bits[target / 64] >> (target % 64)) & 1 == 1
}
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 FreeThe Rust-specific trap
Performance in Rust, beyond the O(n*S)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Subset Sum?
std has no bit set. The two honest choices are vec![false; target + 1] (a Vec<bool>, one byte per cell) or a hand-rolled Vec<u64> word array where you set bit s with w[s >> 6] |= 1 << (s & 63). For a packaged bit set the ecosystem standard is fixedbitset::FixedBitSet or bitvec::vec::BitVec; fixedbitset tends to win for DP because it is a thin wrapper over a word Vec with union_with and ones(), without bitvec's proxy-reference machinery. std::collections::HashSet<u64> is only reasonable when reachable sums stay sparse.
What is the most common Rust mistake when implementing Subset Sum?
usize subtraction is the one that bites. dp[s - x] with s < x does not produce a negative index: usize underflows, and the failure mode differs by build profile. A debug build panics with 'attempt to subtract with overflow' at the subtraction; a release build wraps to about 1.8e19 and then panics later on the bounds check, so cargo test and the shipped binary blame different lines. The mirror problem is accumulation: let total: u64 = nums.iter().sum() wraps silently in release, so use checked_add or widen to u128 before comparing against the target.
How does Subset Sum actually perform in Rust?
Vec<bool> is one byte per cell with a bounds check on every index; LLVM hoists that check only when it can prove the range, which the (x..=target).rev() form helps it do, while slice iteration removes it entirely. The word-packed variant advances 64 candidate sums per OR, so the machine performs target/64 word operations per item instead of target byte operations, typically a 20-60x wall-clock win at the same O(n*S). Building with -C target-cpu=native lets LLVM auto-vectorise the Vec<u64> OR loop into wide stores. Time complexity is O(n*S) and space is O(n*S).
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 trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.