{"record":{"id":"4bf2f1089ef18fc5","repo":"TheAlgorithms/Java","slug":"adjacencylist-size-must-equal-vertexcount","errorCode":null,"errorMessage":"adjacencyList size must equal vertexCount","messagePattern":"adjacencyList size must equal vertexCount","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/graph/TarjanBridges.java","lineNumber":57,"sourceCode":"     * an integer in the range {@code [0, vertexCount)}. For each undirected edge (u, v),\n     * v must appear in {@code adjacencyList.get(u)} and u must appear in\n     * {@code adjacencyList.get(v)}.</p>\n     *\n     * @param vertexCount   the total number of vertices in the graph (must be non-negative)\n     * @param adjacencyList the adjacency list representation of the graph; must contain\n     *                      exactly {@code vertexCount} entries (one per vertex)\n     * @return a list of bridge edges, where each bridge is represented as an {@code int[]}\n     *         of length 2 with {@code edge[0] < edge[1]}; returns an empty list if no bridges exist\n     * @throws IllegalArgumentException if {@code vertexCount} is negative, or if\n     *                                  {@code adjacencyList} is null or its size does not match\n     *                                  {@code vertexCount}\n     */\n    public static List<int[]> findBridges(int vertexCount, List<List<Integer>> adjacencyList) {\n        if (vertexCount < 0) {\n            throw new IllegalArgumentException(\"vertexCount must be non-negative\");\n        }\n        if (adjacencyList == null || adjacencyList.size() != vertexCount) {\n            throw new IllegalArgumentException(\"adjacencyList size must equal vertexCount\");\n        }\n\n        List<int[]> bridges = new ArrayList<>();\n\n        if (vertexCount == 0) {\n            return bridges;\n        }\n\n        BridgeFinder finder = new BridgeFinder(vertexCount, adjacencyList, bridges);\n\n        // Run DFS from every unvisited vertex to handle disconnected graphs\n        for (int i = 0; i < vertexCount; i++) {\n            if (!finder.visited[i]) {\n                finder.dfs(i, -1);\n            }\n        }\n\n        return bridges;","sourceCodeStart":39,"sourceCodeEnd":75,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/graph/TarjanBridges.java#L39-L75","documentation":"TarjanBridges.findBridges requires the adjacencyList size to exactly equal vertexCount because each vertex 0..vertexCount-1 must have a corresponding list entry it can index. A mismatch means the graph representation is internally inconsistent — the algorithm would either skip vertices or hit IndexOutOfBoundsException mid-DFS. The check fails fast up front instead of letting the DFS corrupt state.","triggerScenarios":"Calling findBridges(vertexCount, adjacencyList) where adjacencyList.size() != vertexCount — e.g. vertexCount=5 but the list has 4 or 6 entries, or passing a null adjacencyList. Also triggered when a graph builder adds/removes vertices after the count was captured.","commonSituations":"Building the adjacency list in a loop with an off-by-one (e.g. adding vertices 0..n-1 but initializing the list with n+1 slots), deserializing a graph where isolated vertices were omitted as empty lists, or refactoring vertex indexing (0-based vs 1-based) without updating the count.","solutions":["Verify adjacencyList.size() == vertexCount immediately before the call, e.g. assert adjacencyList.size() == vertexCount or an explicit if-check.","Ensure every vertex in [0, vertexCount) has an entry — add empty lists for isolated vertices (Collections.nCopies(vertexCount, List.of()) as a starter).","If you build the list by appending, derive vertexCount from the list: findBridges(adjacencyList.size(), adjacencyList).","If the list legitimately has extra slots (e.g. 1-based indexing), strip the unused slot or shift to 0-based before calling."],"exampleFix":"// before\nList<List<Integer>> adj = new ArrayList<>();\nfor (int v = 0; v <= n; v++) adj.add(neighbors(v)); // off-by-one\nTarjanBridges.findBridges(n, adj);\n\n// after\nList<List<Integer>> adj = new ArrayList<>();\nfor (int v = 0; v < n; v++) adj.add(neighbors(v)); // exactly n entries\nTarjanBridges.findBridges(adj.size(), adj);","handlingStrategy":"validation","validationCode":"if (adjacencyList == null || adjacencyList.size() != vertexCount) {\n    throw new IllegalArgumentException(\n        \"adjacencyList size (\" + (adjacencyList == null ? \"null\" : adjacencyList.size())\n        + \") must equal vertexCount (\" + vertexCount + \")\");\n}\nTarjanBridges.findBridges(vertexCount, adjacencyList);","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Derive vertexCount from adjacencyList.size() rather than tracking a separate variable that can drift.","When building the list, add an entry for every vertex index including isolated ones (empty list).","Use Collections.nCopies(vertexCount, new ArrayList<>()) to pre-size the list correctly before populating edges."],"tags":["graph","validation","argument-mismatch","tarjan","adjacency-list"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}