TheAlgorithms/JavaScript · error · RangeError

Error size should be less than equal to 32

Error message

Error size should be less than equal to 32

What it means

generateSubSets iterates from 0 to 2^n - 1 using the bitmask (1 << n), so n > 32 both produces an astronomically large result set (>4 billion subsets) and overflows JS 32-bit bitwise shift behavior (1 << 32 === 1, corrupting the loop). The 32-element cap prevents hang/crash.

Source

Thrown at Bit-Manipulation/GenerateSubSets.js:14

/**
 * @function generateSubSets
 * @param {Array} inputArray
 * @returns {Array}
 * @example [1,2] -> [[],[1],[2],[1,2]]
 */

// The time complexity of this algorithm is BigO(2^n) where n is the length of array
function generateSubSets(inputArray) {
  if (!Array.isArray(inputArray)) {
    throw new Error('Provided input is not an array')
  }
  if (inputArray.length > 32) {
    throw new RangeError('Error size should be less than equal to 32')
  }
  let arrayLength = inputArray.length
  let subSets = []
  // loop till (2^n) - 1
  for (let i = 0; i < 1 << arrayLength; i++) {
    let subSet = []
    for (let j = 0; j < arrayLength; j++) {
      // 1 << j it shifts binary digit 1 by j positions and then we perform
      // and by AND operation we are checking whetheer jth bit
      // in i is set to 1 if result is non zero just add into set
      if (i & (1 << j)) {
        subSet.push(inputArray[j])
      }
    }
    subSets.push(subSet)
  }
  return subSets
}

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Reduce the input to 32 elements or fewer before calling.
  2. If you only need subset counts (not the subsets themselves), use the combinatorial 2^n formula instead.
  3. For genuinely large power sets, implement a streaming/generator approach with BigInt-indexed batching.

Example fix

// before
generateSubSets(bigArray) // bigArray.length === 50
// after
generateSubSets(bigArray.slice(0, 32))
Defensive patterns

Strategy: validation

Validate before calling

function subsetsBounded(arr, max = 32) {
  if (arr.length > max) {
    throw new RangeError(`Array too large (${arr.length} > ${max}) for power-set generation`);
  }
  return generateSubSets(arr);
}

Type guard

/** @param {unknown[]} arr @returns {boolean} */
const withinPowerSetLimit = arr => Array.isArray(arr) && arr.length <= 32;

Try / catch

try { return generateSubSets(arr); }
catch (e) {
  if (e instanceof RangeError && /less than equal to 32/.test(e.message)) {
    return generateSubSets(arr.slice(0, 32)); // or compute count via 2**n
  }
  throw e;
}

Prevention

When it happens

Trigger: Passing an array with 33 or more elements.

Common situations: Feeding a large dataset, a full wordlist, or an unfiltered collection expecting the full power set without realizing it is O(2^n).

Related errors


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