{
  "id": "kosaraju-sharir-algorithm",
  "title": "Kosaraju–Sharir Algorithm",
  "lang": "en",
  "source_lang": "en",
  "summary": "The Kosaraju–Sharir algorithm finds the strongly connected components of a directed graph using two depth-first search passes, with linear running time for adjacency-list representations.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Kosaraju's algorithm",
    "Kosaraju–Sharir strongly connected components algorithm",
    "two-pass strongly connected components algorithm"
  ],
  "generated_at": "2026-11-05",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/kosaraju-sharir-algorithm/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/kosaraju-sharir-algorithm/",
      "json": "https://aiwiki.page/zh/kosaraju-sharir-algorithm.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "The Kosaraju–Sharir algorithm is a graph algorithm that partitions a directed graph into its strongly connected components: maximal sets of vertices in which every vertex can reach every other by following directed edges. It performs two passes of depth-first search (DFS), one on the original graph and one on the graph with all edges reversed. The order established by the first pass ensures that each search tree in the second pass identifies exactly one component. For a graph represented by adjacency lists, its running time is \\(O(|V|+|E|)\\)."
    },
    {
      "heading": "Problem and terminology",
      "text": "Let \\(G=(V,E)\\) be a finite directed graph, where \\(V\\) is the vertex set and \\(E\\) is the edge set. Two vertices \\(u\\) and \\(v\\) belong to the same strongly connected component if both of the following hold:\n\n- There is a directed path from \\(u\\) to \\(v\\).\n- There is a directed path from \\(v\\) to \\(u\\).\n\nPaths of length zero are allowed, so every vertex belongs to a component, including an isolated vertex. Mutual reachability is an equivalence relation, and the components therefore form a unique partition of \\(V\\).\n\nThe transpose graph, written \\(G^{T}\\), has the same vertices as \\(G\\), with every edge reversed:\n\n\\[G^{T}=(V,E^{T}), \\qquad E^{T}=\\{(v,u):(u,v)\\in E\\}.\\]\n\nTransposing a graph preserves its strongly connected components: reversing paths exchanges the two reachability conditions without changing which pairs satisfy both.\n\nThe algorithm is named after S. Rao Kosaraju and Micha Sharir. Its defining feature is the use of DFS finishing order to coordinate two graph traversals."
    },
    {
      "heading": "Algorithm",
      "text": "There are two symmetric versions of the algorithm. One searches \\(G\\) first and \\(G^{T}\\) second; the other searches \\(G^{T}\\) first and \\(G\\) second. Both are correct, provided that the second pass processes vertices in decreasing finishing-time order from the first pass.\n\nThe following description uses \\(G\\) first.\n\nFirst pass: record finishing order\n\nRun a complete DFS on \\(G\\), starting a new search from any unvisited vertex whenever necessary. When the search finishes exploring all outgoing edges of a vertex, append that vertex to a list.\n\nThis produces vertices in increasing order of DFS finishing time. Reading the list backward gives decreasing finishing-time order, also called reverse postorder.\n\nThe list must record completion, not discovery. A vertex is appended only after all recursive searches initiated from it have returned.\n\nSecond pass: collect components\n\nReset the visited state, then scan vertices in reverse order of the finishing list. Whenever an unvisited vertex is encountered, start a DFS from it in \\(G^{T}\\).\n\nEvery previously unvisited vertex reached by that search belongs to one strongly connected component. Assign all such vertices the same component identifier, then continue scanning the list.\n\nThe second pass maintains one global visited or component-label array. Vertices assigned to an earlier component are not explored again.\n\nPseudocode\n\nThe following pseudocode uses recursive DFS and integer component identifiers:\n\nKosarajuSharir(G):\n    GT = transpose(G)\n    visited = array indexed by vertices, initially false\n    finish = empty list\n\n    procedure FirstDFS(v):\n        visited[v] = true\n        for each w in G.out_neighbors(v):\n            if not visited[w]:\n                FirstDFS(w)\n        finish.append(v)\n\n    for each vertex v in G:\n        if not visited[v]:\n            FirstDFS(v)\n\n    component = array indexed by vertices, initially UNASSIGNED\n    count = 0\n\n    procedure SecondDFS(v, id):\n        component[v] = id\n        for each w in GT.out_neighbors(v):\n            if component[w] == UNASSIGNED:\n                SecondDFS(w, id)\n\n    for each v in reverse(finish):\n        if component[v] == UNASSIGNED:\n            SecondDFS(v, count)\n            count = count + 1\n\n    return component, count\n\nFor any two vertices \\(u\\) and \\(v\\), equality of their returned component identifiers means that they are mutually reachable. The numerical identifiers themselves are not unique: they can depend on vertex and adjacency-list iteration order."
    },
    {
      "heading": "Why it works",
      "text": "The condensation graph\n\nContract each strongly connected component into a single vertex, retaining edges between distinct components. The resulting condensation graph is a directed acyclic graph (DAG).\n\nIt cannot contain a directed cycle: components on such a cycle would all be mutually reachable and would therefore constitute one larger strongly connected component.\n\nThe algorithm effectively uses finishing times to arrange these component vertices in a topological order, without knowing the components in advance.\n\nThe finishing-time property\n\nLet \\(f(v)\\) be the finishing time of vertex \\(v\\) in the first DFS pass. For a component \\(C\\), define\n\n\\[F(C)=\\max_{v\\in C} f(v).\\]\n\nIf there is an edge from a component \\(C\\) to a distinct component \\(D\\), then\n\n\\[F(C)>F(D).\\]\n\nTo see why, consider which component is discovered first:\n\n- If \\(C\\) is discovered first, its DFS can reach all vertices of \\(C\\) and, through the intercomponent edge, all vertices of \\(D\\). These vertices finish before the DFS call at the first-discovered vertex in \\(C\\) finishes.\n- If \\(D\\) is discovered first, its search cannot reach \\(C\\), because an edge from \\(C\\) to \\(D\\) together with a path back would place them in the same component. The search through \\(D\\) therefore finishes before \\(C\\) is discovered.\n\nThus, the maximum finishing times decrease along every edge between distinct components.\n\nWhy each second-pass search finds exactly one component\n\nThe component containing the unassigned vertex with greatest finishing time has no incoming edge from another unassigned component in \\(G\\). Such an incoming edge would contradict the finishing-time inequality.\n\nAfter transposition, that component has no outgoing edge to another unassigned component. A search in \\(G^{T}\\) therefore cannot leave it for an unassigned component. At the same time, transposition preserves strong connectivity, so the search reaches every vertex within it.\n\nAfter this component is labeled, the same argument applies to the remaining unassigned components. Repeating the process finds the entire partition.\n\nThis reasoning does not imply that every vertex of one component finishes before every vertex of another. It is the maximum finishing time of each component that provides the necessary ordering."
    },
    {
      "heading": "Example",
      "text": "Consider a graph with edges\n\n\\[a\\to b,\\quad b\\to a,\\quad b\\to c,\\quad c\\to d,\\quad d\\to c,\\quad d\\to e.\\]\n\nIts strongly connected components are\n\n\\[\\{a,b\\},\\qquad \\{c,d\\},\\qquad \\{e\\}.\\]\n\nThe condensation graph is a chain:\n\n\\[\\{a,b\\}\\longrightarrow\\{c,d\\}\\longrightarrow\\{e\\}.\\]\n\nA first-pass DFS beginning at \\(a\\), with neighbors explored in the order implied by the displayed edges, can produce the finishing list\n\n\\[[e,d,c,b,a].\\]\n\nThe second pass reads this list backward and searches the transpose:\n\n- Starting at \\(a\\), it reaches \\(a\\) and \\(b\\).\n- Starting at the next unassigned vertex, \\(c\\), it reaches \\(c\\) and \\(d\\). Any edges to the already assigned component are ignored.\n- Starting at \\(e\\), it collects only \\(e\\).\n\nWith this orientation of the two passes, components are discovered in topological order of the original condensation graph. Searching \\(G^{T}\\) first and \\(G\\) second produces the reverse component order."
    },
    {
      "heading": "Complexity and implementation",
      "text": "With an adjacency-list representation, building the transpose takes \\(O(|V|+|E|)\\) time. Each DFS pass visits every vertex once and examines every edge once. The overall time complexity is therefore\n\n\\[O(|V|+|E|).\\]\n\nThe auxiliary space complexity depends on graph storage:\n\n- Visited state, component labels, the finishing list, and the DFS stack require \\(O(|V|)\\) space.\n- Materializing a separate transpose requires \\(O(|V|+|E|)\\) additional space.\n- If incoming and outgoing adjacency lists already exist, or a reverse view is available, the traversal requires only \\(O(|V|)\\) auxiliary space beyond the graph representation.\n\nFor an adjacency-matrix representation, enumerating neighbors typically makes the running time \\(O(|V|^2)\\).\n\nRecursive and iterative implementations\n\nA recursive implementation is compact, but a DFS tree may have depth \\(|V|\\). On large or path-like graphs, this can exceed the available call stack.\n\nAn iterative implementation can use an explicit stack. The first pass must preserve true DFS finishing order, usually by storing a frame containing a vertex and its next unexplored neighbor, or by using explicit entry and exit events. Merely recording vertices when first pushed does not compute the required order.\n\nIn the second pass, only reachability within the unassigned subgraph matters. DFS can therefore be replaced by breadth-first search without changing the resulting components.\n\nCommon implementation errors\n\nTypical errors include:\n\n- Recording discovery order instead of finishing order.\n- Reading the finishing list forward rather than backward.\n- Using the same edge orientation in both passes.\n- Failing to reset visited state between passes.\n- Starting the first pass from only one vertex, leaving unreachable regions unprocessed.\n- Clearing second-pass visited state between components, allowing already assigned vertices to be collected again.\n\nSelf-loops and parallel edges do not require special treatment for correctness, although parallel edges increase the number of edge examinations."
    },
    {
      "heading": "Applications and related algorithms",
      "text": "Strongly connected components expose mutually dependent regions in directed systems. Applications include grouping recursive dependencies in a compiler, organizing state graphs in model checking, and reducing a graph to its acyclic condensation for subsequent processing. Component labels answer mutual-reachability queries directly, but they do not by themselves answer arbitrary one-way reachability queries.\n\nThe algorithm also supports solving 2-satisfiability through an implication graph: a formula is unsatisfiable exactly when some variable and its negation belong to the same strongly connected component.\n\nTarjan's strongly connected components algorithm solves the same problem in \\(O(|V|+|E|)\\) time using one DFS pass, an active-vertex stack, and low-link values. Unlike the standard Kosaraju–Sharir implementation, it does not need a separate transpose. The two-pass method instead offers a direct separation between computing an ordering and extracting components.\n\nKosaraju–Sharir is a static-graph algorithm: it computes components for a fixed graph. Maintaining components efficiently as edges are inserted or deleted requires dynamic algorithms rather than simply retaining the original finishing order."
    }
  ],
  "links": [
    "algorithm",
    "directed-graph",
    "strongly-connected-component",
    "depth-first-search",
    "pseudocode",
    "directed-acyclic-graph",
    "adjacency-list",
    "time-complexity",
    "space-complexity",
    "call-stack",
    "stack-data-type",
    "breadth-first-search",
    "compiler",
    "model-checking"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}