TheAlgorithms/JavaScript · error · Error

Index out of bounds. The maximum index can be length-1

Error message

Index out of bounds. The maximum index can be length-1

What it means

Thrown by ensureIndexWithinBounds() inside UnionFind when any passed index is greater than or equal to the internal length n given at construction. The data structures (id, sz arrays) are sized to n, so indices must stay in [0, n-1]. Notably the guard only checks the upper bound; negative indices pass through silently and would index from the end of the array, producing corrupt results rather than an error.

Source

Thrown at Search/UnionFind.js:82

    q = key(q)
    ensureIndexWithinBounds(p, q)
    const i = this.find(p)
    const j = this.find(q)
    if (i === j) return
    if (sz[i] < sz[j]) {
      id[i] = j
      sz[j] += sz[i]
    } else {
      id[j] = i
      sz[i] += sz[j]
    }
    cnt--
  }
  function ensureIndexWithinBounds(args) {
    for (let i = arguments.length - 1; i >= 0; i--) {
      const p = arguments[i]
      if (p >= length)
        throw new Error(
          'Index out of bounds. The maximum index can be length-1'
        )
    }
  }
}

export { UnionFind }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Use a key function to remap external indices: new UnionFind(n, (a) => a - 1).
  2. Ensure all indices passed to find/union are in [0, n-1].
  3. Add your own lower-bound check since this guard ignores negatives: if (i < 0 || i >= n) throw.

Example fix

// before
const uf = new UnionFind(graphNodeCount)
uf.union(edge[0], edge[1]) // edges are 1-based

// after
const uf = new UnionFind(graphNodeCount, (a) => a - 1)
uf.union(edge[0], edge[1])
Defensive patterns

Strategy: validation

Validate before calling

function makeUnionFind(n) {
  const uf = new UnionFind(n)
  const safe = (i) => {
    if (!Number.isInteger(i) || i < 0 || i >= n) {
      throw new RangeError(`index ${i} out of [0, ${n - 1}]`)
    }
    return i
  }
  return {
    find: (i) => uf.find(safe(i)),
    union: (a, b) => uf.union(safe(a), safe(b)),
  }
}

Type guard

function isInBounds(n, i) {
  return Number.isInteger(i) && i >= 0 && i < n
}

Try / catch

try {
  uf.find(idx)
} catch (e) {
  if (e.message.includes('Index out of bounds')) {
    console.warn('Skipping out-of-range union-find index', idx)
  } else throw e
}

Prevention

When it happens

Trigger: Calling find/union with an index >= n (e.g. new UnionFind(5) then .find(5) or .find(10)). Off-by-one when caller indices are 1-based and the structure was built 0-based without a key mapper.

Common situations: 1-based external indices fed to a 0-based UnionFind; loops using <= n instead of < n; union of node ids read from a graph whose node numbering starts at 1.

Related errors


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