TheAlgorithms/C-Sharp · error · ArgumentOutOfRangeException

Vertex indices must be within valid range.

Error message

Vertex indices must be within valid range.

What it means

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).

Solutions

  1. Check that every vertex index passed to AddEdge satisfies 0 <= index < vertexCount used in the constructor
  2. Convert 1-based input vertex labels to 0-based (subtract 1) before calling AddEdge
  3. Validate/parsing external input ranges before building the graph
  4. Catch ArgumentOutOfRangeException at graph-build boundaries and report the offending index

Example fix

// before
var tarjan = new TarjanStronglyConnectedComponents(3);
tarjan.AddEdge(1, 3); // 3 out of range
// after
var tarjan = new TarjanStronglyConnectedComponents(4);
tarjan.AddEdge(1, 3);
Defensive patterns

Strategy: validation

Validate before calling

if (u < 0 || u >= vertexCount || v < 0 || v >= vertexCount) throw new ArgumentOutOfRangeException(nameof(u), $"Vertex index out of [0, {vertexCount}).");

Type guard

bool IsValidVertex(int v, int count) => v >= 0 && v < count;

Try / catch

try { graph.AddEdge(u, v); }
catch (ArgumentOutOfRangeException ex) { logger.LogError(ex, "Invalid vertex in edge ({U},{V})", u, v); }

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/969bec455369a6cb. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Graph/TarjanStronglyConnectedComponents.cs:44

        onStack = new bool[vertices];
        stack = new Stack<int>();
        sccs = new List<List<int>>();

        for (int i = 0; i < vertices; i++)
        {
            graph[i] = new List<int>();
            ids[i] = -1;
        }
    }

    /// <summary>
    /// Adds a directed edge from u to v.
    /// </summary>
    public void AddEdge(int u, int v)
    {
        if (u < 0 || u >= graph.Length || v < 0 || v >= graph.Length)
        {
            throw new ArgumentOutOfRangeException(nameof(u), "Vertex indices must be within valid range.");
        }

        graph[u].Add(v);
    }

    /// <summary>
    /// Finds all strongly connected components.
    /// </summary>
    /// <returns>List of SCCs, where each SCC is a list of vertex indices.</returns>
    public List<List<int>> FindSCCs()
    {
        for (int i = 0; i < graph.Length; i++)
        {
            if (ids[i] == -1)
            {
                Dfs(i);
            }
        }

View on GitHub (pinned to 96e2905cab)