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

Partition Equal Subset Sum Implementation in Go

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

  • ✓Partition Equal Subset Sum runs in O(n*S) time and O(S) space, in Go as in every other language.
  • ✓`make([]bool, target+1)` is the default table - one byte per cell, and because the slice holds no pointers it lands in a noscan span the collector never walks.
  • ✓Reviewers want the function pure and its allocation explicit: `make([]bool, target+1)` with the length stated up front, no `append` in the hot loop, and no `map[int]bool` standing in for a dense contiguous range.
  • ✓The Go trap: `prev := dp` snapshots nothing. A slice is a three-word header, so `prev` and `dp` share one backing array and the 'previous row' mutates underneath you - the two-row DP that is correct in Swift, where value semantics copy on write, is silently wrong here.
  • ✓The Go compiler eliminates far fewer bounds checks than LLVM does, so `dp[j]` and `dp[j-n]` each cost a compare-and-branch unless you hand it a proof - the usual moves are a `_ = dp[target]` hint before the loop or reslicing to the exact length.

What Partition Equal Subset Sum actually is

Can an array of positive integers be split into two groups with identical sums? It is subset-sum in disguise: an odd total is an immediate no, otherwise ask whether any subset reaches target = total/2. Engineers meet it balancing work across two identical workers or splitting a two-way shard. The answer is a one-dimensional boolean table over reachable sums, filled backwards so each number is spent once - O(n*S) time, O(S) space. It is pseudo-polynomial: cost tracks the sum, not the count, so 40 numbers summing to a billion is hopeless while 10,000 numbers summing to 20,000 is a 10^8-cell fill: milliseconds in Rust, Go, Java or C#, and tens of seconds in a plain CPython loop - pseudo-polynomial means tractable, not free.

Partition Equal Subset Sum in Go: what you actually reach for

`make([]bool, target+1)` is the default table - one byte per cell, and because the slice holds no pointers it lands in a noscan span the collector never walks. Go also ships a genuine big-integer bitset in `math/big`: `(*big.Int).Lsh(x *Int, n uint)`, `(*big.Int).Or(x, y *Int)` and `(*big.Int).Bit(i int) uint` express the shift-or fold directly, and because those take a mutating receiver you can reuse one scratch value instead of allocating per step. `math/bits.OnesCount64` counts a hand-rolled `[]uint64`. Nothing in `container/*` fits.

Go implementation

Reviewers want the function pure and its allocation explicit: `make([]bool, target+1)` with the length stated up front, no `append` in the hot loop, and no `map[int]bool` standing in for a dense contiguous range. Returning a slice that aliases an internal buffer gets rejected - return the `bool`. The descending `for j := target; j >= n; j--` is preferred over anything clever. gofmt and `go vet` settle style, so review attention goes almost entirely to the aliasing question.
go
package partition

import "math/big"

func sum(nums []int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

// CanPartition reports whether nums splits into two equal-sum subsets.
func CanPartition(nums []int) bool {
	total := sum(nums)
	if total%2 != 0 {
		return false
	}
	target := total / 2

	dp := make([]bool, target+1) // pointer-free, so it lands in a noscan span
	dp[0] = true
	for _, n := range nums {
		if n > target {
			return false
		}
		for j := target; j >= n; j-- {
			if dp[j-n] {
				dp[j] = true
			}
		}
		if dp[target] {
			return true
		}
	}
	return dp[target]
}

// CanPartitionBig folds with math/big as a packed bitset. Lsh and Or take a
// mutating receiver, so one reused scratch value stops the per-item allocation.
func CanPartitionBig(nums []int) bool {
	total := sum(nums)
	if total%2 != 0 {
		return false
	}
	bits := big.NewInt(1)
	scratch := new(big.Int)
	for _, n := range nums {
		scratch.Lsh(bits, uint(n))
		bits.Or(bits, scratch)
	}
	return bits.Bit(total/2) == 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 Free

The Go-specific trap

`prev := dp` snapshots nothing. A slice is a three-word header, so `prev` and `dp` share one backing array and the 'previous row' mutates underneath you - the two-row DP that is correct in Swift, where value semantics copy on write, is silently wrong here. Java and C# share Go's hazard exactly - `boolean[] prev = dp` aliases one array - so only Swift is the contrast; there the mirror-image cost is n hidden deep copies. `copy(prev, dp)` is the fix, and it copies `min(len(prev), len(dp))` elements, so a `prev` built with the wrong length truncates without an error. `append` has the same shape: below cap it writes into the shared array, above cap it stops sharing, so the bug appears and vanishes with input size.

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

The Go compiler eliminates far fewer bounds checks than LLVM does, so `dp[j]` and `dp[j-n]` each cost a compare-and-branch unless you hand it a proof - the usual moves are a `_ = dp[target]` hint before the loop or reslicing to the exact length. There is no JIT warmup, so the first call runs at full speed and a naive benchmark is honest, but there is also no autovectorisation of the byte loop. `math/big` allocates inside `Lsh` whenever the result outgrows the receiver's capacity, which is why the scratch value is reused. The asymptotic cost is the same in every language, O(n*S) time and O(S) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Partition Equal Subset Sum between languages.

Real-World Applications

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

Interview Tips & Practice

Partition Equal 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 Partition Equal 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 Partition Equal Subset Sum to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Partition Equal Subset Sum?

`make([]bool, target+1)` is the default table - one byte per cell, and because the slice holds no pointers it lands in a noscan span the collector never walks. Go also ships a genuine big-integer bitset in `math/big`: `(*big.Int).Lsh(x *Int, n uint)`, `(*big.Int).Or(x, y *Int)` and `(*big.Int).Bit(i int) uint` express the shift-or fold directly, and because those take a mutating receiver you can reuse one scratch value instead of allocating per step. `math/bits.OnesCount64` counts a hand-rolled `[]uint64`. Nothing in `container/*` fits.

What is the most common Go mistake when implementing Partition Equal Subset Sum?

`prev := dp` snapshots nothing. A slice is a three-word header, so `prev` and `dp` share one backing array and the 'previous row' mutates underneath you - the two-row DP that is correct in Swift, where value semantics copy on write, is silently wrong here. Java and C# share Go's hazard exactly - `boolean[] prev = dp` aliases one array - so only Swift is the contrast; there the mirror-image cost is n hidden deep copies. `copy(prev, dp)` is the fix, and it copies `min(len(prev), len(dp))` elements, so a `prev` built with the wrong length truncates without an error. `append` has the same shape: below cap it writes into the shared array, above cap it stops sharing, so the bug appears and vanishes with input size.

How does Partition Equal Subset Sum actually perform in Go?

The Go compiler eliminates far fewer bounds checks than LLVM does, so `dp[j]` and `dp[j-n]` each cost a compare-and-branch unless you hand it a proof - the usual moves are a `_ = dp[target]` hint before the loop or reslicing to the exact length. There is no JIT warmup, so the first call runs at full speed and a naive benchmark is honest, but there is also no autovectorisation of the byte loop. `math/big` allocates inside `Lsh` whenever the result outgrows the receiver's capacity, which is why the scratch value is reused. Time complexity is O(n*S) and space is O(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

Before paying for Devin, check its student and free-tier options on Noizz.

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.