TheAlgorithms/Go · error

ErrNegativeSum

ErrNegativeSum

Error message

negative sum is not allowed

What it means

A sentinel error (dynamic.ErrNegativeSum) returned by IsSubsetSum when the requested sum is negative; the subset-sum DP assumes non-negative integers and a non-negative target, so a negative sum is rejected by this generic guard before the matrix is built.

Source

Thrown at dynamic/subsetsum.go:13

//Given a set of non-negative integers, and a (positive) value sum,
//determine if there is a subset of the given set with sum
//equal to given sum.
// time complexity: O(n*sum)
// space complexity: O(n*sum)
//references: https://www.geeksforgeeks.org/subset-sum-problem-dp-25/

package dynamic

import "fmt"

var ErrInvalidPosition = fmt.Errorf("invalid position in subset")
var ErrNegativeSum = fmt.Errorf("negative sum is not allowed")

func IsSubsetSum(array []int, sum int) (bool, error) {
	if sum < 0 {
		//not allow negative sum
		return false, ErrNegativeSum
	}

	//create subset matrix
	arraySize := len(array)
	subset := make([][]bool, arraySize+1)
	for i := 0; i <= arraySize; i++ {
		subset[i] = make([]bool, sum+1)
	}

	for i := 0; i <= arraySize; i++ {
		//sum 0 is always true
		subset[i][0] = true
	}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Validate sum>=0 before calling
  2. Return false for negative sums at the call site if that matches your semantics
  3. Compare with errors.Is(err, ErrNegativeSum) for specific handling
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at dynamic/subsetsum.go:13 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/aea89199267608c3. Report an issue: GitHub.