{"record":{"id":"969bec455369a6cb","repo":"TheAlgorithms/C-Sharp","slug":"vertex-indices-must-be-within-valid-range","errorCode":null,"errorMessage":"Vertex indices must be within valid range.","messagePattern":"Vertex indices must be within valid range\\.","errorType":"exception","errorClass":"ArgumentOutOfRangeException","httpStatus":null,"severity":"error","filePath":"Algorithms/Graph/TarjanStronglyConnectedComponents.cs","lineNumber":44,"sourceCode":"        onStack = new bool[vertices];\n        stack = new Stack<int>();\n        sccs = new List<List<int>>();\n\n        for (int i = 0; i < vertices; i++)\n        {\n            graph[i] = new List<int>();\n            ids[i] = -1;\n        }\n    }\n\n    /// <summary>\n    /// Adds a directed edge from u to v.\n    /// </summary>\n    public void AddEdge(int u, int v)\n    {\n        if (u < 0 || u >= graph.Length || v < 0 || v >= graph.Length)\n        {\n            throw new ArgumentOutOfRangeException(nameof(u), \"Vertex indices must be within valid range.\");\n        }\n\n        graph[u].Add(v);\n    }\n\n    /// <summary>\n    /// Finds all strongly connected components.\n    /// </summary>\n    /// <returns>List of SCCs, where each SCC is a list of vertex indices.</returns>\n    public List<List<int>> FindSCCs()\n    {\n        for (int i = 0; i < graph.Length; i++)\n        {\n            if (ids[i] == -1)\n            {\n                Dfs(i);\n            }\n        }","sourceCodeStart":26,"sourceCodeEnd":62,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Graph/TarjanStronglyConnectedComponents.cs#L26-L62","documentation":"TarjanStronglyConnectedComponents.AddEdge validates that both vertex indices u and v are within [0, graph.Length) before adding the adjacency entry. Throwing ArgumentOutOfRangeException with the message 'Vertex indices must be within valid range.' signals that a caller passed an index outside the graph's declared vertex count (either negative or >= number of vertices).","triggerScenarios":"Calling AddEdge(u, v) with u < 0, v < 0, u >= graph vertex count, or v >= vertex count. In tests, this happens when vertices are 1-based while the graph is 0-based, or when AddEdge is called with vertices beyond the constructor's vertexCount argument.","commonSituations":"Building a graph from input data where vertex IDs come from external sources (files, user input) without remapping to 0-based indices; off-by-one loops (i <= n instead of i < n); constructing a graph with too few vertices then adding edges for more.","solutions":["Check that every vertex index passed to AddEdge satisfies 0 <= index < vertexCount used in the constructor","Convert 1-based input vertex labels to 0-based (subtract 1) before calling AddEdge","Validate/parsing external input ranges before building the graph","Catch ArgumentOutOfRangeException at graph-build boundaries and report the offending index"],"exampleFix":"// before\nvar tarjan = new TarjanStronglyConnectedComponents(3);\ntarjan.AddEdge(1, 3); // 3 out of range\n// after\nvar tarjan = new TarjanStronglyConnectedComponents(4);\ntarjan.AddEdge(1, 3);","handlingStrategy":"validation","validationCode":"if (u < 0 || u >= vertexCount || v < 0 || v >= vertexCount) throw new ArgumentOutOfRangeException(nameof(u), $\"Vertex index out of [0, {vertexCount}).\");","typeGuard":"bool IsValidVertex(int v, int count) => v >= 0 && v < count;","tryCatchPattern":"try { graph.AddEdge(u, v); }\ncatch (ArgumentOutOfRangeException ex) { logger.LogError(ex, \"Invalid vertex in edge ({U},{V})\", u, v); }","preventionTips":["Always derive vertex indices from 0-based loops (for i in 0..count-1)","Convert 1-based external labels before AddEdge","Validate vertex IDs from user/file input at ingestion time"],"tags":["csharp","graph","argument-out-of-range"],"backgroundTag":"value-out-of-range","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}