TheAlgorithms/JavaScript · error · Error

The sum must be non-negative.

Error message

The sum must be non-negative.

What it means

Thrown by NumberOfSubsetSum(array, sum) (plain Error) when sum < 0. The dynamic-programming table is indexed 0..sum, so a negative sum would construct an invalid range; the guard rejects it before allocation.

Source

Thrown at Dynamic-Programming/NumberOfSubsetEqualToGivenSum.js:11

/*
Given an array of positive integers and a value sum,
determine the total number of the subset with sum
equal to the given sum.
*/
/*
  Given solution is O(n*sum) Time complexity and O(sum) Space complexity
*/
function NumberOfSubsetSum(array, sum) {
  if (sum < 0) {
    throw new Error('The sum must be non-negative.')
  }

  if (!array.every((num) => num > 0)) {
    throw new Error('All of the inputs of the array must be positive.')
  }
  const dp = [] // create an dp array where dp[i] denote number of subset with sum equal to i
  for (let i = 1; i <= sum; i++) {
    dp[i] = 0
  }
  dp[0] = 1 // since sum equal to 0 is always possible with no element in subset

  for (let i = 0; i < array.length; i++) {
    for (let j = sum; j >= array[i]; j--) {
      if (j - array[i] >= 0) {
        dp[j] += dp[j - array[i]]
      }
    }
  }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Clamp the target to >= 0, or treat negative targets as a distinct 'no subsets' case returning 0.
  2. Validate sum >= 0 at the call site before invoking.
  3. Stop using -1 as a sentinel for 'unset'; use null/undefined and branch explicitly.
  4. Recompute targets from fresh inputs after upstream subtractions.

Example fix

// before
const count = NumberOfSubsetSum(arr, target) // throws if target < 0

// after
if (target < 0) return 0
const count = NumberOfSubsetSum(arr, target)
Defensive patterns

Strategy: validation

Validate before calling

function safeSubsetSum(arr, sum) {
  if (sum < 0) return 0 // or throw a domain-specific error
  return NumberOfSubsetSum(arr, sum)
}

Type guard

const isNonNegative = (n) => typeof n === 'number' && n >= 0

Try / catch

try {
  return NumberOfSubsetSum(arr, sum)
} catch (e) {
  if (e instanceof Error && /non-negative/i.test(e.message)) return 0
  throw e
}

Prevention

When it happens

Trigger: NumberOfSubsetSum(arr, -5); passing a target derived from subtraction that went negative; defaulting sum to -1 as a 'no target' sentinel.

Common situations: Targets computed as (a - b) where b > a; user input parsed as negative; reused variable left at -1 from an initialization.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/3ef574912bf9f6a3. Report an issue: GitHub.