{"record":{"id":"99995c67f9b116f7","repo":"TheAlgorithms/JavaScript","slug":"index-out-of-bounds-the-maximum-index-can-be-leng","errorCode":null,"errorMessage":"Index out of bounds. The maximum index can be length-1","messagePattern":"Index out of bounds\\. The maximum index can be length-1","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"Search/UnionFind.js","lineNumber":82,"sourceCode":"    q = key(q)\n    ensureIndexWithinBounds(p, q)\n    const i = this.find(p)\n    const j = this.find(q)\n    if (i === j) return\n    if (sz[i] < sz[j]) {\n      id[i] = j\n      sz[j] += sz[i]\n    } else {\n      id[j] = i\n      sz[i] += sz[j]\n    }\n    cnt--\n  }\n  function ensureIndexWithinBounds(args) {\n    for (let i = arguments.length - 1; i >= 0; i--) {\n      const p = arguments[i]\n      if (p >= length)\n        throw new Error(\n          'Index out of bounds. The maximum index can be length-1'\n        )\n    }\n  }\n}\n\nexport { UnionFind }\n","sourceCodeStart":64,"sourceCodeEnd":90,"githubUrl":"https://github.com/TheAlgorithms/JavaScript/blob/5c39e87a9a31f279c60f830ad74a845e4788a517/Search/UnionFind.js#L64-L90","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Use a key function to remap external indices: new UnionFind(n, (a) => a - 1).","Ensure all indices passed to find/union are in [0, n-1].","Add your own lower-bound check since this guard ignores negatives: if (i < 0 || i >= n) throw."],"exampleFix":"// before\nconst uf = new UnionFind(graphNodeCount)\nuf.union(edge[0], edge[1]) // edges are 1-based\n\n// after\nconst uf = new UnionFind(graphNodeCount, (a) => a - 1)\nuf.union(edge[0], edge[1])","handlingStrategy":"validation","validationCode":"function makeUnionFind(n) {\n  const uf = new UnionFind(n)\n  const safe = (i) => {\n    if (!Number.isInteger(i) || i < 0 || i >= n) {\n      throw new RangeError(`index ${i} out of [0, ${n - 1}]`)\n    }\n    return i\n  }\n  return {\n    find: (i) => uf.find(safe(i)),\n    union: (a, b) => uf.union(safe(a), safe(b)),\n  }\n}","typeGuard":"function isInBounds(n, i) {\n  return Number.isInteger(i) && i >= 0 && i < n\n}","tryCatchPattern":"try {\n  uf.find(idx)\n} catch (e) {\n  if (e.message.includes('Index out of bounds')) {\n    console.warn('Skipping out-of-range union-find index', idx)\n  } else throw e\n}","preventionTips":["Remember this guard ignores negative indices — add your own lower-bound check.","Use a key mapper for 1-based external indices.","Size the UnionFind to maxIndex + 1, not maxIndex."],"tags":["bounds-check","union-find","off-by-one","input-validation"],"backgroundTag":null,"analyzedSha":"5c39e87a9a31f279c60f830ad74a845e4788a517","analyzedAt":"2026-08-13T04:54:54.474Z","schemaVersion":2},"datasetVersion":"2026-08-13T09:17:06.757Z"}