Manuscript Offprint
arXiv:2611.02154Faster Algorithms for Disjoint Paths in DAGs and Two Disjoint Shortest Paths
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original. This text is shared under the same licence.
Abstract
For vertex-disjoint paths with prescribed endpoints in a directed acyclic graph (DAG), the -time pebbling algorithm of Fortune, Hopcroft, and Wyllie [TCS 1980] has remained the fastest for every for over four decades, even when the paths must be shortest. We break this bound for every with randomized algorithms running in expected time for every , where is the matrix multiplication exponent; this is . For two disjoint shortest paths, we find the paths as fast as we detect them: in expected linear time on DAGs and on undirected graphs with polynomially bounded integer weights, and in expected time on directed graphs whose cycles have positive weight, which on dense graphs is even for detection. All algorithms evaluate a polynomial whose monomials are the solutions: a new first-collision circuit speeds up the evaluation in DAGs, and a correlated extraction step at cuts crossed once by every path finds a solution at the cost of a constant number of evaluations.
*yangcao@psu.edu. Pennsylvania State University. †Jilin University. ‡Tsinghua University.
1 Introduction
In the vertex-disjoint paths problem (-DP), the input is a directed graph with vertices and edges and terminal pairs , and the task is to connect every pair by a path so that the paths are pairwise vertex-disjoint. In the disjoint shortest paths problem (-DSP), every path must in addition be a shortest path between its terminals. Already for two pairs, -DP is NP-hard on general directed graphs [FHW80, Lemma 3]. On directed acyclic graphs (DAGs) it is polynomial for every fixed [FHW80, Theorem 3], by a pebbling game that extends the two-path algorithm of [PS78]: a configuration records the current vertex of every path, and a move advances the earliest path along an edge. There are configurations and moves, and this bound, stated explicitly in [BNRZ21, Lemma 34] and [Epp95, Theorems 2 and 4], has remained the fastest for every , for -DP as well as for weighted -DSP [AVW24, Section 7].
[AVW24, Section 7, Open Problem 3] asks for an -time algorithm for -DSP in DAGs, for some fixed and some constant . The question includes -DP: giving every edge the difference of the topological positions of its endpoints makes every path between fixed endpoints shortest [AVW24, Proposition 54].
For two pairs, the shortest-path constraint makes the problem tractable beyond DAGs, and the fastest algorithms are algebraic. The circuits of [AVW24] detect two disjoint shortest paths in time on positive-weight DAGs and undirected graphs, and [CKS26] detect them in time on directed graphs whose cycles have positive weight. Finding the paths has remained a factor of about slower: the reporting algorithms of [AVW24] and of [BNRZ21], for unweighted undirected graphs, take time, and for directed graphs [BK17] gives a polynomial-time algorithm and [CKS26] report in time. [CKS26] ask whether reporting can match detection and whether directed 2-DSP admits an -time algorithm [CKS26, Section 6, Open Problems 1 and 2].
We improve both lines of work; Table 1 summarizes the bounds. All our algorithms evaluate a polynomial over a field of characteristic two whose monomials are the solutions, as the detectors of [AVW24] do, and two tools make this approach fast. The first is a circuit that evaluates the polynomial of disjoint paths in a DAG by subtracting intersecting tuples at their first collision (Theorem 4.1). The second is a correlated extraction step: at a cut that every path crosses at most once, a nonzero evaluation yields compatible pieces of one solution on both sides of the cut, at the cost of a constant number of evaluations (Lemma 3.4). The first tool breaks the pebbling bound in DAGs with superlinearly many edges; the second makes reporting as fast as detection in each of our models.
Theorem 1.1 (Disjoint paths in DAGs, informal version of Theorem 4.7). For every fixed and , -DSP on DAGs with real edge weights, and hence -DP on DAGs, can be solved by a randomized algorithm with one-sided error in expected time.
The pebbling bound exceeds the bound of Theorem 1.1 by a factor of for every and every fixed ; with , our bound is . Keeping one lightest copy of each parallel edge takes time by radix sort and leaves fewer than edges. This answers Open Problem 3 of [AVW24], which asks for time for some fixed and : the term only reads the input, and we obtain for every fixed .
| Problem | Previous (detect / report) | This paper | Thm. |
|---|---|---|---|
| k-DP, k-DSP in DAGs, | [FHW80] | 1.1 | |
| 2-DSP, DAGs and undirected | [AVW24] | 1.2 | |
| 2-DSP, directed | [CKS26] | 1.3 |
Table 1: Time bounds for finding the paths. For two pairs, the previous column lists detection and reporting separately; for three or more pairs, one bound covers both. Our bounds are expected times of randomized algorithms with one-sided error, each attained by one algorithm that decides feasibility and reports a solution. The previous two-path bounds for DAGs and undirected graphs assume positive weights; ours allow arbitrary real weights on DAGs and assume positive polynomially bounded integer weights on undirected graphs. Directed graphs have only positive-weight cycles; for negative weights, the directed bound uses the single-source shortest-path algorithm of [HLLZ26].
Under the k-Clique Hypothesis, k-DSP on unweighted DAGs requires time, where is the time to detect a k-clique in an -vertex graph [AVW24, Theorem 7 and Corollary 8]; for three pairs this lower bound is .
The algebraic core of Theorem 1.1 is Theorem 4.1, which computes the enumerating polynomial of the disjoint path tuples over every commutative ring and for arbitrary commodity subgraphs. Over the integers with every edge variable set to 1, it counts the vertex-disjoint tuples with prescribed terminal pairs with arithmetic operations, compared with in [Epp95, Theorem 4].
For two pairs, the extraction step finds the paths within the time of detection, and in directed graphs a faster detector also improves detection.
Theorem 1.2 (Linear-time 2-DSP, informal version of Theorem 5.12). On DAGs with real edge weights and on undirected graphs with positive polynomially bounded integer weights, two vertex-disjoint shortest paths for two prescribed terminal pairs can be found by a randomized algorithm with one-sided error in expected time.
Theorem 1.3 (Directed 2-DSP, informal version of Theorem 6.8). On directed graphs with real edge weights in which every cycle has positive weight, two vertex-disjoint shortest paths for two prescribed terminal pairs can be found by a randomized algorithm with one-sided error in expected time, for every fixed . Deciding whether they exist takes the same time.
For comparison, Theorem 1.2 matches the detection time of [AVW24] on DAGs and, for integer weights, on undirected graphs, and improves their reporting bound by a factor of . Our undirected reporting computes regional distances with the integer-weight single-source shortest-path algorithm of [Tho97] (Section 5.2), so for positive real weights we claim no linear bound, although the detector of [AVW24] is linear there. Theorem 1.3 answers the reporting question of [CKS26] for all real weights, and their question in the dense regime: for every fixed , choosing makes the bound when , so in this regime both detection and reporting improve on [CKS26] by a polynomial factor. The bound depends on the source-distance labelings only through Lemma 6.1. For nonnegative weights they take time [FT87]. For arbitrary real weights, Bellman–Ford [Bel58] takes time, and the Las Vegas algorithm of [HLLZ26] takes time with high probability, the latest in a line of algorithms faster than that began with [Fin23]; the labelings therefore never dominate the bound. Even for sparse graphs, the bound removes the logarithmic factor from the detection bound of [CKS26], whose all-pairs preprocessing [CKS26, Lemma 2.6] takes time with Fibonacci heaps while its remaining detector states cost [CKS26, Section 4.3], and it improves their reporting bound by a factor of . Theorem 1.2 answers the reporting question for DAGs and, in its integer-weight model, for undirected graphs.
1.2 Technical overview
All our algorithms encode the solutions as the monomials of a polynomial over a field of characteristic two: path tuples are weighted by the product of their edge variables, intersecting tuples cancel, and distinct disjoint tuples leave distinct squarefree monomials (Lemma 3.1). One random evaluation therefore decides feasibility. Two costs remain: the size of a circuit for , and the cost of turning a nonzero value into paths. Generic self-reduction fixes one edge at a time and repeats the evaluation, which loses a factor of about . We describe the circuits first, then the extraction step, and then how the reporting recursions stay within the cost of one evaluation.
Evaluation by first collisions. For two paths in a DAG, the detector of [AVW24] starts from the product of the two source-to-target path sums, which counts every pair of paths, and subtracts the intersecting pairs by their first intersection : such a pair splits into two prefixes that meet only at and two unconstrained suffixes [AVW24, Lemma 23]. For paths, a tuple can collide in many patterns, and tracking all positions is the pebbling game, which examines every edge once for each of the placements of the other paths. We keep the first-intersection principle and store no placements: we subtract the intersecting tuples, classified by their first collision in a fixed topological order. Let be this collision and the set of paths through . Before , the prefixes are disjoint except at itself. After , nothing is required: the paths through continue arbitrarily, and every other path continues from its last vertex by an edge that jumps over , unless it has already ended.
With more paths, the jumping edges are the new ingredient (Figure 2). A prefix table stores and the endpoints of the paths outside , so it has at most vertex coordinates instead of . The graph enters only when one coordinate is extended across by a jumping edge and a path sum, which costs over all choices of and of the other coordinates. The tables satisfy the same first-collision decomposition, so a topological sweep updates them with further operations. Both steps become matrix products, scheduled by divide and conquer over the topological order so that every product reads only final rows. For three paths, the extensions and the updates are batched across rows, which gives operations. For , each row is extended by matrix products as soon as it is final, and the updates of a pair table become rectangular matrix products once all but one endpoint outside the pair is fixed, which gives operations (Lemma 4.2 and Propositions 4.3 to 4.5).
Correlated extraction. All first derivatives of a circuit can be evaluated with constant-factor overhead [BS83], and a nonzero derivative shows that an edge lies in some solution. It does not show which edges lie in a common solution: contains all four variables but has no monomial , so choosing and independently can commit to an impossible pair (Figure 1).
We avoid this at a monotone cut, which every path crosses at most once: a topological prefix of a DAG, or a threshold of for two shortest paths in an undirected or directed graph. Fixing the noncut variables at the inherited evaluation point leaves a polynomial in the cut variables that is homogeneous and multilinear of degree , the number of paths whose terminals lie
(a) Incompatible marginals
| f | f' | |
|---|---|---|
| e | 0 | 1 |
| e' | 1 | 0 |
Rows and columns can be nonzero while their joint coefficient is zero.
(b) Compatible cut edges

Figure 1: Why extraction selects a joint coefficient. (a) The coefficient matrix of a quadratic cut polynomial: both and occur, but . Selecting the highlighted coefficient instead gives the compatible choice . (b) Splitting at these edges, illustrated for a DAG cut. By Lemma 3.2, a nonzero coefficient has an assignment with two nonzero child evaluations. The two child solutions can then be joined through the selected edges.
on opposite sides. Its coefficients factor across the cut: for every choice of cut edges,
where ranges over the at most assignments of the edges of to the crossing paths and are the polynomials of the two sides (Lemma 3.2). A nonzero coefficient thus yields an assignment whose two child evaluations are nonzero, and any two child solutions join through into a solution of the parent.
To find such a coefficient without expanding , we grow a set of selected variables. Setting every variable of to a common value makes the coefficient of the monomials containing the leading coefficient of a univariate restriction, and interpolating gradient evaluations reads it off for all candidate extensions of at once. After stages, , using an expected gradient evaluations (Lemma 3.3). For , the coefficients form the Hessian of , and one gradient exposes a nonzero row; for larger , repeated directional differentiation would introduce a factorial that vanishes in characteristic two, and interpolation avoids it. The temporary samples never replace , so every child inherits a nonzero evaluation (Lemma 3.4).
Paying for the recursion. Reporting cuts every region at a balanced monotone cut and continues on the children. For paths in a DAG, we cut at a vertex median and keep both children. The regions at each depth are disjoint and halve in size, so the superlinear circuit sizes sum geometrically over the recursion, and reporting costs a constant factor more than one evaluation (Proposition 4.6).
The two-path circuits of [AVW24] have linear size, so keeping both children would cost an extra logarithmic factor. Instead we recover one side without recursion. Once two compatible cut edges are selected, compare the routes through them with the routes that exchange them. Shortestness prevents the exchange from shortening both sides. A strict comparison on one side lets a common-sink reduction recover that side by a flow of value two; equality puts the relevant pieces in a common tight DAG, where the algorithm of [Tho12] reports them. At most one two-path region remains, and median cuts, with a two-boundary treatment of equal -values, shrink it geometrically (Sections 5.2 and 5.3).
In a directed graph the exchanged routes need not exist, so we keep both children and speed up the detector instead. On the regional shortest-path supports, the cancellation recurrence of [CKS26] enforces its reachability restrictions automatically, through zero path sums, and becomes a triangular matrix computation: finalize the earlier half of the states, multiply their contributions into the later half, and recurse (Lemma 6.5 and Figure 6). This gives regional circuits of size by a row schedule and by fast matrix multiplication (Lemma 6.6).
At a threshold of , the first path crosses in the increasing direction and the second in the decreasing direction, so the assignment of the two selected edges is forced and the selected coefficient is a single product of child evaluations. The circuit sizes of the children contract by a constant factor at balanced cuts, and an equality plateau is resolved after at most two boundary cuts (Lemma 6.7). Summing these sizes, together with the two source-distance computations, proves Theorem 1.3.
Related work. Generic ways to turn an algebraic detector into a search algorithm either isolate one solution or repeat the decision. The isolation lemma of [MVV87] makes a minimum-weight solution unique under random weights, which their matching algorithm uses to read off its edges. [BKK14] extract a witness of size with queries to an oracle that decides whether a given set contains a witness; since our solutions can have edges, its bound exceeds the detection time by a factor of . Our extraction step needs neither isolation nor repeated decisions: by Lemma 3.2, a nonzero coefficient at a monotone cut already determines compatible child instances, and the recursion then costs a constant factor more than one evaluation.
2 Preliminaries
Graphs have vertices and edges. A path contains its endpoints and repeats no vertex; for a vertex , the zero-edge path is a path from to . For a vertex set , is the induced subgraph, and hides factors depending only on .
2.1 Models of computation
Real edge weights are handled by unit-cost exact additions, subtractions, and comparisons of weight values; the only exception is the undirected case of Theorem 5.12, where the weights are positive integers bounded by and are stored in words. All other computation takes place on a word RAM with -bit words. Polynomial evaluations use a field with , whose elements fit in a constant number of words; field operations and uniform sampling of field elements take unit time. The constant in depends on the error exponent.
2.2 Circuits and polynomial identity testing
An arithmetic circuit, or straight-line program, over a commutative ring is division-free if it uses only additions, subtractions, multiplications, inputs, and constants of . Its size counts gates and input occurrences. A circuit computes a formal polynomial in its inputs, and the identities of this paper are identities of formal polynomials.
The enumerating polynomials of this paper are tested at one random point; the extraction steps evaluate further temporary points, which affect only the running time. By the Schwartz-Zippel lemma, a nonzero polynomial of degree over a field vanishes at a uniform point of with probability at most . The extraction steps also differentiate circuits.
Lemma 2.1 ([BS83]). Given a division-free circuit of size for a polynomial in variables and a point , all first partial derivatives at can be computed with operations and space.
2.3 Matrix multiplication
Some of our circuits contain matrix products, and all of them must be division-free, as Lemma 2.1 requires. We therefore let be the exponent of square matrix multiplication by bilinear algorithms with coefficients in . The bound of [ADV+25, DEK+26] applies to this definition: it is proved with tensors whose entries are 0 and 1, which can be considered over any field [ADV+25, Section 3.1]. A bilinear algorithm with coefficients in is a division-free straight-line program over every field . Hence, for every fixed , applying such an algorithm of exponent below recursively multiplies two matrices over with field operations, by a program constructed in time linear in its length. An by product, or an by product with , splits into square products.
3 Correlated extraction at monotone cuts
A nonzero polynomial evaluation certifies existence; reporting requires compatible choices. We obtain them by selecting a nonzero coefficient at a cut crossed at most once by each path. The cut factorization below turns this coefficient into two child instances with nonzero inherited evaluations. The extraction algorithm finds it without expanding the polynomial and works over every field.
Throughout this section, is a field with unit-cost operations and uniform sampling, is a directed or undirected graph with vertex set and edge set , and for each label , is a directed graph on whose arcs are orientations of edges of ; for directed , the only orientation of an edge is its own direction, so . Every edge of carries one variable , shared by all its orientations and all graphs . In the setting of Theorem 4.1, is the input DAG and are the commodity subgraphs; in Sections 5 and 6, and are the tight graphs of the two shortest-path systems.
A regional instance consists of a set , a label set , and terminals for . Its solutions are the tuples of pairwise vertex-disjoint paths such that is an path in ; a path contains its endpoints, so for the zero-edge path occupies . The regional polynomial is
where runs over the edges of underlying the arcs of and the sum ranges over the solutions. Let and . For , , and , the regional polynomial is the polynomial of Theorem 4.1.
Lemma 3.1 (Witness monomials). For every regional instance, distinct solutions have distinct squarefree monomials of degree at most , each with coefficient 1. Hence is a nonzero polynomial exactly when a solution exists, and then with probability at least for a uniform .
Proof. Vertex-disjoint paths share no edge, so the monomial of a solution is the product of the variables of the union of its edge sets, which is squarefree and has at most edges. If two labels share a terminal, no solution exists. Otherwise the union decomposes into vertex-disjoint paths of . The endpoints of each such path with an edge are the terminals of a unique label , which also fix its direction from to , and every zero-edge path is forced. Hence the monomial determines the solution. The last assertion is the Schwartz-Zippel lemma.
Monotone cuts. A partition of into a low side and a high side is a monotone cut of a regional instance if, for every , no path of contains two edges between and . The edges of between and are the cut edges; their variables are the cut variables, written , and all other variables of are noncut variables. A label is active if and lie on different sides. Let be the set of active labels and put . A path whose endpoints lie on one side crosses between the sides an even number of times, and a path whose endpoints lie on different sides an odd number of times. Hence every path in uses exactly one cut edge if is active and none otherwise.
Two kinds of monotone cuts occur. If is a DAG containing every , every path visits its vertices in increasing topological order, so a topological prefix and its complement form a monotone cut; Section 4.5 cuts at vertex medians. If a vertex coordinate is nondecreasing or nonincreasing along every path of each , a path cannot return across a threshold of that coordinate, so a threshold forms a monotone cut; Sections 5.3 and 6 cut at thresholds of the distance difference of the two shortest-path systems. In the second kind, different labels may cross in opposite directions.
For a set of cut edges, a bijection is feasible if, for every , the edge , oriented from the side of to the side of , is an arc of whose underlying edge is . Under a feasible , each active label has the pair on the side of and the pair on the side of . The low child is the regional instance on whose pairs are these pairs inside for together with the pairs of the inactive labels with terminals in ; the high child on is defined symmetrically. Let and be their polynomials.
The next lemma records the structure of at a monotone cut: after the noncut variables are fixed, it is a form of degree in the cut variables, and each coefficient is a sum of products of child evaluations.
Lemma 3.2 (Cut factorization). Let be a monotone cut of a regional instance . Fix values of all noncut variables, and let be with the cut variables left free. Then is homogeneous multilinear of degree , and every collection of cut edges satisfies
where ranges over the at most ! feasible bijections . In particular, if , then some feasible has and .
Proof. A solution of has exactly one cut edge on each active path and none on the other paths, and its paths share no edge. Its monomial is therefore a product of distinct cut variables and noncut variables. Since solutions contribute squarefree monomials, fixing the noncut variables and cancellation cannot create other cut monomials, even if a circuit for contains syntactic squares. This proves the first assertion.
A solution whose cut-edge set is determines by letting be the cut edge of . Since crosses once, it traverses from the side of to the side of as an arc of , so is feasible, the part of up to lies on the side of , and the part from lies on the side of . Every inactive path lies on one side. Hence splitting gives solutions of both children under . Conversely, joining solutions of the two children under one feasible through the arcs of gives walks in whose two pieces lie on different sides; these walks are paths. They are disjoint inside each side by the child conditions and across the sides because , and their cut-edge set is . The two maps are inverse. The edge sets of , and the cut are disjoint, so the weight of the joined solution is times the weights of the two child solutions.
Evaluating the noncut variables at and summing over gives the identity. A nonzero sum has a nonzero summand, and a nonzero product over a field has two nonzero factors.
It remains to find a set with without expanding . Separate first derivatives do not suffice: for , every variable occurs in a monomial, but the coefficient of is zero, so edges indicated by different derivatives need not belong to one solution. For , the coefficients of form its Hessian matrix, and a nonzero gradient entry at a random point exposes a nonzero row. The next lemma handles every . It finds the variables of a nonzero monomial one at a time: setting the variables already chosen to a common value turns the coefficient sought into the leading coefficient of a polynomial in , which a few gradient evaluations determine. Unlike repeated differentiation along a line, interpolation does not introduce the factor , which vanishes in characteristic two for .
Lemma 3.3 (Interpolated coefficient extraction). Let be a nonzero homogeneous multilinear polynomial of degree over a field with , computed by a division-free circuit of size , counting gates and input occurrences. A set of variables whose monomial has a nonzero coefficient in can be found, together with , using expected field operations and space.
Proof. Expand as over -sets of variables, where . For a set of variables, put . Then , is homogeneous multilinear of degree in the variables outside , for , and when . We maintain a set with , starting from ; if , one evaluation returns . Consider a stage with .
Recovering candidate coefficients. Fix distinct . For , let be evaluated with every variable in set to and every other variable set to . In , the term of has degree in , with equality exactly when . Hence has degree at most , and Lagrange interpolation at gives its leading coefficient:
Reverse-mode differentiation evaluates all first partial derivatives of the circuit at one point with operations and space [BS83]. The point is the same for all , so such evaluations, accumulated with the interpolation weights, give for all with operations. Since a degree- multilinear monomial uses distinct inputs, , so the interpolation-weight computation is included in this bound.
Extending the selected set. Sample the coordinates outside independently and uniformly. The polynomial is nonzero, multilinear, and of positive degree, so some is a nonzero polynomial of degree . By the Schwartz-Zippel lemma, it vanishes at with probability at most .
The event that all computed values vanish is detected and triggers fresh sampling of . Otherwise, add to any with , which certifies . After stages, and the last stage computes . Each stage needs an expected constant number of trials, and its gradient evaluations cost operations with space. The total expected cost is .
The two lemmas combine into one step of every reporting recursion in this paper. The recursions differ only in how they choose cuts and in which children they keep.
Lemma 3.4 (Correlated extraction step). Let be a monotone cut of a regional instance , let satisfy , and suppose that has a division-free circuit of size and . set of cut edges and a feasible bijection with and can be found using expected field operations and space, plus the evaluation at of the child polynomials for the at most feasible bijections. The computation never changes .
Proof. Substituting for the noncut inputs of the circuit of gives a circuit of size at most for the polynomial of Lemma 3.2. Its value at the cut coordinates of is , so , and Lemma 3.2 shows that is homogeneous multilinear of degree . Lemma 3.3 returns a set with ; it samples only temporary values of the cut variables. By Lemma 3.2, some feasible has two nonzero child evaluations at , and evaluating the children for every feasible finds one.
4 Disjoint paths in DAGs
The main algebraic result computes the enumerating polynomial of disjoint path tuples in commodity subgraphs of one DAG. Tight shortest-path subgraphs give -DSP; taking every commodity subgraph to be the input graph gives -DP.
Theorem 4.1. Fix an integer . Let be a DAG with vertices, edges, and a given topological order, let be spanning edge-subgraphs of , and let be vertex pairs, where is allowed. Assign an element of a commutative ring to every edge of , and let
where the sum ranges over all tuples of pairwise vertex-disjoint paths such that is an path in . With unit-cost ring operations, is computed by a division-free straight-line program with operations, which is constructed in time linear in its length and executed in space. If matrices over can be multiplied by a division-free straight-line program that is constructible in time linear in its length and uses operations for some , then operations suffice.
Proof. Lemma 4.2 gives the first-collision recurrences. Proposition 4.3 evaluates them with the general operation and space bounds, and Propositions 4.4 and 4.5 give the matrix multiplication bounds for and for , respectively.
The construction has four parts: the first-collision identity, its topological evaluation, and batched evaluations for three pairs and for every fixed . Section 4.5 then recovers paths from a nonzero evaluation and proves Theorem 4.7.
4.1 The first-event decomposition
We work in the setting of Theorem 4.1: is a DAG with an injective topological order are spanning edge-subgraphs of , and every edge carries one element of a commutative ring , shared by all subgraphs containing . If two pairs share a terminal, no tuple exists and . The weight of a path is , and the weight of a tuple of paths is the product of their weights. This convention loses no generality for subgraphs with smaller vertex sets: if a prescribed terminal is absent from its commodity subgraph, return ; otherwise add all missing vertices as isolated vertices.
Private terminals and path sums. Private terminals make every path start before and end after all real vertices. Then every path avoiding a real vertex has a last vertex before , and becomes the collision-free part of a product of path sums. Give commodity a private source and a private sink , and let consist of and the edges and , whose weights are the constant 1. Extend so that all private sources precede and all private sinks follow . Then is a weight-preserving bijection from the paths in to the paths in , and every vertex lying in two of the graphs is real. Every edge increases the order, so every walk is a path and visits its vertices in increasing order. For vertices of , let be the total weight of the paths in ; thus , and unless . Put .
Crossing kernels. The continuation of a path that avoids a collision is counted by a kernel. For a real vertex , a vertex of , and a vertex of , let the crossing kernel be the total weight of the paths in whose vertices other than all follow . If , the endpoint does not follow , so such a path is trivial and . If , no such path exists, because neither equals nor follows . Otherwise the path begins with an edge jumping over . Hence
Prefix tables. The collision-free prefixes are counted by the following tables. For with , a real vertex , and a tuple of vertices of , let be the total weight of the tuples such that is a path in for , is a path in for , and two paths intersect exactly in when and are disjoint otherwise. The table records only the meeting vertex and the current endpoint of every other path. It has at most entries, and has no second argument.
Extension across a collision. Applying the kernels to a table row extends the paths that avoid across , and multiplying by path sums from extends the paths through (Figure 2). For a tuple of vertices of , let be the set of tuples of paths such that is a path in . By distributivity, the total weight of is . A collision of is a vertex lying on at least two of its paths; collisions are real. For a real vertex and with , write and define
where ranges over tuples of vertices of . In particular, . In the terms of the overview, attaches the continuations of the paths avoiding to a row of prefixes, and also attaches the continuations of the paths through and sums over the label set .
The next lemma makes the overview precise: is the weight of the tuples whose first collision is w. Subtracting these tuples from all tuples gives recurrences in which each table row depends only on rows with earlier meeting vertices.

Figure 2: First-collision decomposition for and . The prefix table stores only the meeting vertex and the last vertex of path 3. Its continuation must jump over ; the three suffixes are counted independently by , , and . Curves crossing away from a marked vertex do not indicate a graph intersection.
Lemma 4.2 (First-event decomposition). For every endpoint tuple and real vertex , the tuples whose earliest collision is have total weight . Consequently, for as in the definition of , and for when and otherwise,
Moreover, with ,
These identities hold over every commutative ring.
Proof. Let have earliest collision , and let be the labels of the paths through . For , split at . For , split it at its last vertex , which exists because its private source precedes every real vertex. No two prefixes meet before , so the prefix tuple is counted by . The suffix of a label in is counted by ; every vertex of any other suffix after follows , so that suffix is counted by . The edge weights multiply to the weight of .
Conversely, take a prefix tuple counted by and suffixes counted by these factors. Concatenation gives paths because every edge increases the topological order. All vertices before belong to prefixes, which are disjoint there. The paths through have exactly the labels , and for the last vertex before is exactly . Thus the earliest collision is , and splitting recovers the chosen pieces. This weight-preserving bijection proves that their total weight is
For the endpoints defining , every vertex is at most , and exactly the labels in end at . Hence a tuple satisfies the table's intersection conditions exactly when it has no collision before . Each excluded tuple has one earliest collision ; subtracting their weights from gives
(1). At the private sinks , the desired tuples have no collision at all, so subtracting all first-collision classes gives (2). These are partitions of finite sets of weighted tuples and therefore hold over every commutative ring.
4.2 The row sweep
Lemma 4.2 computes each row from rows with earlier meeting vertices, so the rows can be finalized in topological order. Algorithm 1 does this. When it reaches , all rows with meeting vertex are final; it extends them across to the tensors , which costs one path-sum pass per fiber, and then adds to every later table entry. For a table entry with label set , meeting vertex , and endpoints , we write for the endpoint tuple with for and otherwise.
Algorithm 1 Row sweep
Input: the extended graphs with the order and the edge values . Output: .
-
Compute the path sums for all labels and vertices , and put .
-
Give every table entry an accumulator , and put .
-
For every real vertex , in increasing order:
(a) for every and , set , where ;
(b) for every , compute by applying the kernel transform of to the row along each coordinate , and put ;
(c) for every table entry with meeting vertex , add to , and add to .
- Return .
Proposition 4.3 (Row sweep). In the setting of Theorem 4.1, a division-free straight-line program with ring operations computes . The program is constructed in time linear in its length and can be executed in space.
Proof. The program is Algorithm 1. Every operation in it is an addition, subtraction, or multiplication whose pattern depends only on , the subgraphs, the terminals, and , so it is a straight-line program, constructed in time linear in its length. Since is fixed, the private vertices and edges change no bound, and we use and also for the sizes of the extended graph. We first show that the algorithm returns , and then bound the cost of each step.
When is reached, every has added to all entries with a later meeting vertex in step 3(c). Hence the accumulator of every entry with meeting vertex equals
and by (1), step 3(a) sets to its correct value. Since reads table entries only through the row of , every value is final when it is used, and at the end ; by (2), step 4 returns .
Next we bound the path sums of step 1. For fixed and , the values follow from and
evaluated in increasing order of ; this classifies the paths by their last edge , whose tail precedes . One pair costs operations, so step 1 costs operations and space.
We then show that one kernel transform costs operations. Fix , a label , and a vector indexed by the vertices of , and let . By the case formula for , for , , and for
One scan of computes y, and the recurrence
evaluated in increasing order of , gives the displayed value: accounts for the trivial path from , and the term of an edge accounts for the nontrivial paths with last edge , whose first vertices satisfy .
The tensor in step 3(b) has free coordinates. By distributivity, applying the kernel transform of along each coordinate in turn turns the row into the sum defining , and one coordinate pass transforms at most one-dimensional fibers. Summing over the vertices and the sets , step 3(b) costs
Given the tensors and the path sums, each value costs operations, so steps 3(a) and 3(c) cost per vertex , as there are table entries. Altogether, using ,
The path sums, tables, and accumulators occupy cells, using ; the tensors occupy cells and are discarded after .
4.3 Three pairs in matrix multiplication time
For , Proposition 4.3 gives operations. Its term comes from the per-row kernel transforms and its term from the updates; both become matrix products. The updates become products because each row changes a pair table by two outer products, and the kernel transforms become products because each crossing vector is a row of a product of a pair table with adjacency and path-sum matrices. A divide-and-conquer schedule over the order < forms each such product once all rows it reads are final.
Updates as outer products. Write and , and let denote the third label of a pair . For and , take and . The four event sets contribute the four terms of
The first, third, and fourth sets contain and contribute the factor . Hence
Thus row changes the table by the sum of two outer products of vectors indexed by and by .
Crossing vectors as products. Index matrices by the vertices of the extended graph in the order <. Let be the weighted adjacency matrix of , whose entry sums over the parallel edges of , and let be the matrix of path sums. For a pair with third label , let be the matrix with entries for real and , and zero otherwise. Define
Comparing with the case formula for , equals for , 0 for , and for , because then
Moreover for , since unless and unless .
Batching the updates. These products cannot be formed all at once, because the rows depend on each other: row of a pair table is final only after every earlier row has sent its update, and the update sent by row uses the crossing vectors of row . The row sweep respects this dependence by processing one row at a time, which leaves no room for fast matrix multiplication. Algorithm 2 batches the updates by divide and conquer over the order (Figure 3). Once the rows of the first half of an interval are final, the updates that they send to the rows of the second half are known together, and by the outer-product form their sum is a single matrix product. The crossing vectors that these updates read are again products of final blocks. Every ordered pair is separated by exactly one call, so every update is sent exactly once, and since the cost is dominated by the top level of the recursion.
The schedule Algorithm 2 sweeps the real vertices by divide and conquer. It keeps accumulators for all entries and , and the matrices and restricted to the real vertices. Its cross updates use, for a target pair with third label , the factor matrices
(a) Pair table
(b) Batched update


Figure 3: The cross update of Algorithm 2 for a pair table at a call on . (a) Rows and columns of in the order <; only entries below the dashed diagonal, with , are read. After the call on , the rows in are final (blue). Each final row changes every later row by two outer products, so all updates from to the rows in (purple) are known at once; the entries with (light) are filled but never read. (b) The sum of these updates is one product of an and a matrix. Column of and holds the row factors and , and row of and holds the column factors and . The updates within and within are made by the two recursive calls.
A call on an interval of real vertices assumes that the accumulators of every contain the contributions of all real . It finalizes all rows and computes and for all in .
Algorithm 2 SOLVE(I) for three pairs, on an interval of real vertices
-
If , finalize the row of w by (1) and return.
-
Split into a first half and a second half , and call SOLVE().
-
For each pair with third label , compute the crossing blocks
-
For each target pair , add to the accumulators of the entries with and , and add to the accumulator of for all and .
-
Call SOLVE( ).
Proposition 4.4 (Three pairs). Suppose that and that matrices over can be multiplied by a division-free straight-line program that is constructible in time linear in its length and uses operations for some . Then a division-free straight-line program with operations computes . It is constructed in time linear in its length and stores ring elements in addition to the workspace of the multiplication program.
Proof. The program forms , computes the path-sum matrices, runs Algorithm 2 on all real vertices, and evaluates (2). Rectangular products are tiled into square blocks: a product of an and a matrix with costs operations. We first compute the path sums, then show that Algorithm 2 meets its specification, and finally count its operations.
Split the ordered index set into a first half and a second half . A path from to has a unique edge from to , because its vertices increase, and no path leads from to . Hence
and are the path-sum matrices of the subgraphs induced by the two halves, since a path between two vertices of one half stays in that half. Recursing on both halves, with base case , the products at depth cost , which decreases geometrically in because ; the path sums cost operations.
Next we verify the two computations of a call on with . The first crossing identity holds because for and every follows every . For the second, unless and unless , so the sum defining runs over ; the block was computed by the call on , and the rows are final. For the cross updates, every precedes every , so the outer-product form of applies, and for
where and . Every factor is available when it is formed: uses and , and equals for , zero for , and for , all of which are final or were computed for in . The value uses , the path sums, and for the three pairs . Entries with are never read.
We then show by induction on that a call meets its specification. If , the assumption says that the accumulators of contain the contributions of all real , so (1) finalizes the row of . Otherwise the call on meets its specification by induction. After step 4, the accumulators of every contain the contributions of all and of all , which is the assumption of the call on . Every ordered pair of real vertices is added exactly once, at the unique call with and . The entries of and for in lie in , , or , and they are computed by the call on , step 3, and the call on , respectively.
The accumulators start at zero, so the call on all real vertices meets its assumption, and afterwards every table entry is final. The values need , since . For each pair ,
which costs , and (2) gives with further operations.
Finally we count the operations of Algorithm 2. A call on vertices performs constantly many products of shapes , , and , costing , and forms their factors with operations. The calls at depth number at most and have at most vertices each, so depth costs
operations for the products and for the factors. Since , the products sum to and the factors to . The leaves, the direct updates of , and the final step cost . With the operations for and the operations for the path sums, this gives . The matrices and the accumulators occupy cells, and the factors of a call can be released before its second recursive call.
4.4 Fixed in matrix multiplication time
For , the row extensions of Proposition 4.3 can be computed in full when their rows are finalized; unlike for three pairs, this costs no more than the target bound. The remaining bottleneck is updating the pair tables. Fixing all but one outsider endpoint makes each update a matrix product, even when the extension tensor depends on the destination vertex.
Use for the weighted adjacency matrix of , as above, and include all private vertices in endpoint indices. For each real , form the matrices from their defining case formula: their columns are the identity on rows , their column is zero, and
Apply these matrices along the outsider coordinates of a finalized row to obtain the entire tensor . Invalid prefix indices are zero; the extension tensors include endpoints on either side of and at the private sinks.
For a target pair , a source event , and endpoints , the contribution of to is
where has coordinate for and coordinate for . At a split into , take and . If , define factors with the entire outsider tuple as a column index:
If , choose , which exists since . Fix for all and define
Since , the tensor has no coordinate, so each product sums exactly the contribution of over . Destination masks are imposed when the products are added to the accumulators.
Proposition 4.5 (Fixed- batching). Fix . Under the matrix multiplication hypothesis of Proposition 4.4, a division-free straight-line program with ring operations computes . It is constructed in time linear in its length and stores ring elements in addition to the workspace of the multiplication program.
Proof. The program forms the matrices , computes the path sums by the block recursion in Proposition 4.4, initializes all accumulators to zero, runs Algorithm 3 on the real vertices, and evaluates (2). As in Proposition 4.3, the private vertices change no bound, and below also bounds the extended index sets up to a constant factor.
The correctness invariant is the one used for Algorithm 2: on entry to a call on , every accumulator in contains the contributions of all real vertices preceding . A singleton therefore finalizes its rows by Lemma 4.2 and (1). The kernel formula and distributivity show that its
Algorithm 3 SOLVE(I) for fixed , on an interval of real vertices
-
If , finalize every row by (1), form the matrices , compute and retain every tensor by coordinate transforms, and return.
-
Split into a first half and a second half , and call SOLVE().
-
For each target pair and event , add the product defined above to the corresponding accumulators in , retaining only entries with for every ; when , do this for every fixed tuple .
-
For every , , and table entry with , add directly to its accumulator.
-
Call SOLVE().
coordinate transforms compute exactly . At a nontrivial call, induction makes all rows and all extension tensors with final before any cross update. The displayed factorizations give exactly the contributions of these rows to the pair tables; step 4 gives exactly their contributions to the other tables. This establishes the invariant for . Every ordered pair is used at its unique split with and , so no contribution is omitted or repeated. Every factor is available: is precomputed, and was computed in full at the leaf of , including all future endpoints. Only legal destination entries are read in finalizing rows. After the recursion, all terms are available, and (2) returns .
Forming the adjacency matrices and path sums costs operations. Each leaf forms its kernels with operations. If , one coordinate transform is a product of an matrix and an matrix, after zero padding. Splitting its rows into blocks of costs operations. For use a direct vector-matrix product costing ; for the tensor is the scalar . Over all leaves and event sets the kernels and transforms therefore cost
since and .
Consider a call on vertices, padding its halves to size . For the product has shape , costing by square tiling. For , each of the fixed tuples gives a product of shape , costing . These cases exhaust all event sets: , and ; in the last three, the chosen removes the only free outsider coordinate from , whatever its dependence on . There are choices of and , so the products at depth cost
Their sum is . Forming factors, accumulating the tiled outputs, and applying the masks cost per call and hence overall, which is absorbed because . For fixed , the direct updates have destination entries and possible earlier rows, so their total cost is . Row finalization costs , and the root sum costs .
All tables, accumulators, and retained tensors together use cells. Kernels and coordinate-transform buffers are reused between leaves. Products are tiled and accumulated one block at a time, and the factors of a call are released before its second recursive call, so temporary storage satisfies the same bound, apart from the workspace of the multiplication program. The schedule, masks, and indices depend only on the input graphs and the order, and every arithmetic step is an addition, subtraction, or multiplication, so emitting the program takes time linear in its length. □
4.5 Reporting a solution
We now use the regional instances and monotone cuts of Section 3 in the setting of Theorem 4.1, with a field in place of . Adding, for each , a new isolated vertex carrying a zero-edge pair for commodity changes neither the solutions nor of a regional instance. With this padding, Propositions 4.3 to 4.5 give a division-free circuit for , constructed in time linear in its size, of size with
for . When the matrix multiplication bound is used, the extraction below differentiates this circuit, so we assume that the matrix multiplication program of Proposition 4.4 computes the product as an identity of formal polynomials and is constructible in time linear in its length; the bilinear algorithms of Section 2 used in Theorem 4.7 have both properties.
Let be the first vertices of in the order , and . This is a monotone cut, and every path in visits its vertices in increasing order, so no path exists for a label with and . Hence, if , every active label has and , the cut edges used by solutions go from to , and under a feasible the low child has the pairs and the high child the pairs for .
The reporting algorithm keeps both children of every cut. The regional circuits have superlinear size and the regions halve, so the costs decrease geometrically with the recursion depth.
Algorithm 4 REPORTDAG(), for a regional instance with
-
If , return the empty tuple. If , return the zero-edge path of the unique label in .
-
Split into the vertex-median cut . By Lemma 3.4, applied to the circuit of , find a set of cut edges and a feasible bijection with .
-
Call REPORTDAG on the low and the high child under , and join the returned tuples through the edges .
Proposition 4.6 (Reporting). In the setting of Theorem 4.1 over a field with , there is a randomized algorithm that returns either NO or a solution. It never returns an invalid tuple, always returns NO when no solution exists, and returns a solution with probability at least otherwise. Its expected running time is ; under the hypothesis of Proposition 4.4, it is .
Proof. The algorithm reduces parallel edges, tests at a uniform point , returns NO if the value is zero, and otherwise runs Algorithm 4 on the input instance. We first describe the reduction and the root test, then show that Algorithm 4 returns a solution, and finally bound its running time.
For each ordered vertex pair and each label , keep one edge from to that belongs to , if any, and delete the other edges; every kept edge retains its memberships in all subgraphs. With an endpoint-indexed table this takes time and leaves at most edges. A solution uses at most one edge from to , which can be replaced by the edge kept for its label, and every solution of the reduced instance is a solution of the original one, so the existence of solutions is preserved, although the polynomial changes. All polynomials below refer to the reduced instance, and denotes its edge count. The root test evaluates with the program of Proposition 4.3, Proposition 4.4, or Proposition 4.5; by Lemma 3.1, it returns NO always when no solution exists and with probability at most otherwise.
Next we show by induction on that a call on a regional instance with returns a solution of , where is restricted to the variables of . If , the empty tuple is the solution. If , the invariant forces with , and the zero-edge path is a solution. Otherwise is a monotone cut with , and the circuit of has size , so Lemma 3.4 applies. Both children satisfy the invariant and have fewer vertices than , so by induction they return solutions, and by Lemma 3.2 joining them through gives a solution of . Together with the root test, this shows that the algorithm never returns an invalid tuple, returns NO when no solution exists, and returns a solution with probability at least otherwise. The samples of Lemma 3.3 never replace , so after the root test randomness affects only the running time.
Finally we bound the running time. Conditional on the history, the expected cost of a call on , including the circuit, the extraction, the at most child evaluations, and the partition, is , since and give child circuits of total size . The regions at recursion depth are vertex-disjoint, their graphs are edge-disjoint, and each has at most vertices. Hence, using , , and ,
Summing over gives , which also dominates the partition cost and the reduction. Under the hypothesis of Proposition 4.4, put ; the same argument gives
and the terms sum to over the depths, because the reduced instance has at most edges; with the reduction this gives . These bounds hold for every recursion tree, so linearity of expectation gives the claimed expected running time.
We now prove the formal version of Theorem 1.1.
Theorem 4.7 (Disjoint paths in DAGs, formal version of Theorem 1.1). Fix and . On a DAG with vertices, edges, and real edge weights, -DSP can be solved by a randomized algorithm in expected
time, for every fixed . The algorithm never returns an invalid tuple, returns NO on every infeasible instance, and reports a solution with probability at least on every feasible instance. Decision with the same one-sided error has the same worst-case time bound. These guarantees also hold for k-DP in DAGs.
Proof. We reduce both problems to the setting of Theorem 4.1 and apply Proposition 4.6 over a field of polynomial size. First keep one lightest copy of every set of parallel edges, which takes time by radix sorting the edges by their endpoints. A shortest path through a parallel class can use a lightest copy, so feasibility is unchanged, and afterwards . For -DSP, compute by topological dynamic programming with exact operations, and let consist of the edges with and . Along a path of from to the labels telescope to length , and every edge of a shortest path is tight because its prefixes are shortest; hence the paths in are exactly the shortest ones. For -DP, put .
Use with , so that , , and field elements fit in -bit words for fixed and . By Section 2, a bilinear algorithm with coefficients in multiplies matrices over as an identity of formal polynomials with operations, so the hypothesis of Proposition 4.4 holds with . Proposition 4.6 gives the reporting algorithm. For decision, evaluate at a uniform with the program of Proposition 4.4 or Proposition 4.5 and answer according to whether it is nonzero; Lemma 3.1 bounds the error.
5 Two disjoint shortest paths in linear time
To obtain linear reporting time from a linear-size circuit, the recursion must leave at most one unresolved two-path region. The key is to recover one side of a two-active cut directly, using shortest-path comparisons to enforce the prescribed pairing. We first establish the regional circuits and recursion invariant, then prove this one-sided recovery and its linear total cost.
5.1 Regional circuits and the recursive schedule
This subsection specializes the regional polynomial of Section 3 to two shortest paths, gives it circuits of linear size on DAGs and undirected graphs (Lemma 5.2), and states the recursive schedule shared by the three two-path reporting algorithms; Section 6 gives the circuits for directed graphs. Every region keeps the tight graphs of the whole instance, so its shortest paths are tight for the global labels (Lemma 5.1) and the cancellation identities of [AVW24] remain valid with regional terminals. All reporting algorithms evaluate these circuits at one point sampled at the root (3).
We use the characteristic-two field and arithmetic model of Section 2. The field-size choice for the error guarantee is given in Lemma 5.11.
We begin with the shortest-path subgraphs used by both algorithms. For , let be the graph of edges tight with respect to the source-distance labels
Thus a directed edge belongs to when and . In an undirected graph, each physical edge is oriented in every tight direction satisfying the same finite-distance condition. Each is acyclic: it is a subgraph of the input DAG in the DAG case, positive weights orient undirected tight edges by increasing distance, and a directed tight cycle would have total weight zero.
A region in the recursion has terminal pairs and . The th regional paths are the paths in . We attach one variable to every physical edge, so that the regional polynomial of Section 3 with reads
where the sum ranges over vertex-disjoint regional path pairs, the solutions of . By Lemma 3.1, distinct pairs contribute distinct squarefree monomials, and exactly when has a solution. The circuits below start from products of path sums, which also count intersecting pairs. The identities of [AVW24] remove these terms by cancellation: an involution swaps subpaths between intersection vertices, which keeps the multiset of edges, so two matched terms carry the same monomial and sum to zero in characteristic two.
The algorithms of Section 5.2 compute shortest paths inside a region. The next lemma shows that such paths are tight for the global labels, and that on monotone intervals regional and global shortest paths agree.
Lemma 5.1 (Regional shortest-path closure). Suppose precedes on a path in . Every shortest path contained in is tight for . If is an interval of a coordinate monotone on , every globally shortest path stays in , and the global and regional shortest-path polynomials between and agree.
Proof. We compare every path with the inherited part of the given -path, whose length telescopes to because its edges are tight. The triangle inequality gives
so the inherited path is globally shortest. It lies in , hence , and every shortest path in is globally shortest. Prefixing any globally shortest path by an shortest path gives a walk of length , that is, a shortest walk to . In a DAG this walk cannot repeat a vertex; in the other models, deleting a repeated positive-weight cycle would shorten it. Hence the walk is a path and each of its edges is tight for , which proves the first assertion. If the region is an interval of a monotone coordinate, such a path lies in , so the coordinate is monotone along it, and the path cannot leave the interval and later return. Thus the globally shortest paths are exactly the shortest paths in , and the two shortest-path polynomials agree.
The next lemma provides the circuits evaluated by the DAG and undirected algorithms. Its proof checks that the identities of [AVW24] survive the passage to regional terminals.
Lemma 5.2 (Regional cancellation circuits). For a DAG or an undirected graph, has a division-free arithmetic circuit over a characteristic-two field of size , where and . The statement holds for all regional terminals produced by the algorithms below, including zero-edge terminal pairs.
Proof. If , the th path has zero edges and is the path-sum polynomial for the other pair in . If both paths have zero edges, is 1 when their vertices are distinct and 0 otherwise. A terminal shared by the two pairs also makes . Each case has a circuit of size , since a path sum in the acyclic graph takes one pass in topological order.
Hence assume that both paths contain an edge and the boundary vertices required to be disjoint are distinct.
For the remaining regions we use the identities of [AVW24] that compute the polynomial of two disjoint shortest paths: the source-linkage and first-intersection identities [AVW24, Lemmas 22 and 23] for DAGs, and in addition the agreeing- and disagreeing-pair identities [AVW24, Lemmas 30, 36, 38, and 39] for undirected graphs. Lemma A.1 in Appendix A shows that they hold with , , and the shortest-path graphs replaced by , , and : regional paths are shortest paths of , and every exchange of subpaths in the proofs of [AVW24] stays in . The same lemma evaluates the identities with additions and multiplications, which proves the claimed circuit size.
We also use the linear-time algorithm of [Tho12] that, given a DAG and two prescribed terminal pairs, reports two vertex-disjoint paths or determines that none exist.
We use one random assignment sampled at the root and maintain the invariant
for the unique active region in the linear algorithms and for every active region in the directed recursion. A nonzero value certifies that has a solution. The root is the only place where polynomial identity testing may reject a feasible instance. Every later recursive choice proceeds only to subinstances whose evaluated factors are nonzero.
Algorithm 5 is the recursive schedule shared by the two-path reporting algorithms. It applies Lemma 3.4 at monotone cuts, and the three algorithms differ in how they choose cuts and in which children of a two-active cut they keep; a cut is zero-, one-, or two-active according to its number of active pairs. In a DAG the cuts are prefixes of a topological order. In undirected and directed graphs they are thresholds of a difference of the labelings and (Sections 5.3 and 6), which is nondecreasing along the edges of and nonincreasing along those of . Every region is then a union of consecutive -levels, and the th regional paths take their -values in the terminal range between the values at and . A plateau is the set of vertices of a region with one common -value, and it is heavy if it contains more than half of the region. A median threshold leaves at most three quarters of the vertices on each side unless the region has a heavy plateau, which is then split off by cuts at its two boundaries. If the two terminal ranges are disjoint, the pairs cannot meet. If they meet in a single value, the paths can meet only on the plateau of that value, and the plateau base case of Lemma 5.9 resolves the region in linear time by a reduction to two prescribed paths in one DAG.
Algorithm 5 RECURSIVEREPORT(), for a regional instance with two terminal pairs and
-
If a path has zero edges or two terminals coincide, resolve directly. In a distance-difference region, report the two pairs independently if their terminal ranges are disjoint, and apply the plateau base case if the ranges meet in one value.
-
Choose a median monotone cut of .
-
If no pair is active, recurse on the side that contains both pairs, or report the two pairs separately.
-
If one pair is active, select its crossing edge by Lemma 3.4, report the path of the single-path child, and recurse on the two-path child.
-
If both pairs are active, select by Lemma 3.4 two cut edges and an assignment whose two child evaluations at are nonzero. In a DAG or an undirected graph, report one side, or both, as in Section 5.2, and recurse on any remaining child; in a directed graph, recurse on both children.
-
If a retained child is a heavy plateau, cut its other boundary next; a finite two-path plateau is resolved by the plateau base case, and only exterior children continue.
-
Join the returned paths through the selected cut edges.
5.2 Recovering one side without recursion
This subsection proves Proposition 5.5 for DAG cuts and its undirected counterpart Lemma 5.6. Once Lemma 3.4 has selected an assignment with two nonzero child evaluations at a two-active cut, the path pieces on one side of the cut can be reported in linear time without recursion, or the entire pair can be reported. Section 5.3 uses this to keep at most one two-path child per call. Reporting a side directly is a prescribed-pair problem: the two pieces lie in the different shortest-path DAGs and , and each must end at its own endpoint of a selected cut edge. The key idea is to compare the selected solution with the two cross routes that exchange the selected cut edges (Figure 4). Shortestness prevents the exchange from shortening both sides. On a side where it strictly lengthens the routes, a common sink with suitable attachment weights steers each source to its own endpoint, so a flow of value 2 that ignores the pairing reports that side.
Fix an assignment selected by Lemma 3.4, so both child evaluations are nonzero.
Handle the zero-edge and repeated-terminal cases of Lemma 5.2 before applying the common-sink construction. Hence every side considered below has two nonempty prescribed pairs with distinct boundary vertices.
Throughout this subsection, a difference of extended distances is used only when the two operands are not both , with and for finite .
5.2.1 DAG cuts
In this subsection, belongs to path 1, to path 2, and lie on the low side of a DAG topological cut while lie on its high side. For the current terminals , define
Thus is the extra cost of reaching from rather than from , and is the extra cost of leaving toward rather than toward . The two nonzero child factors provide the corresponding path pieces incident to , so , , , and are finite and every difference below is well defined. Hence and , so whenever one of the comparisons below is an equality, all four distances in that comparison are finite.
Two routes through the selected edges. The selected solution sends path 1 through and path 2 through . The cross routes use the other edge: the route reaches , crosses , and continues from , while the route reaches , crosses , and continues from (Figure 4(a)). Passing to the cross routes exchanges the endpoints of the pieces on each side of the cut. On the low side, the length becomes , a change of ; on the high side, the change is . Each cross route connects a prescribed pair, so the total change is not negative, and the exchange cannot shorten both sides. The next lemma records this dichotomy and its equality case. A side on which the exchange strictly lengthens the routes, such as the low side when , is reported by Lemma 5.4. If neither side is strict, the exchange is free on both sides, both selected edges are tight for both labelings, and the prescribed-pair algorithm of [Tho12] finishes.
Lemma 5.3 (Cross-route dichotomy). At least one of
(a) DAG cut

(b) Undirected cut

Figure 4: Selected path pieces (solid) and cross routes (dashed). Blue denotes pair 1, orange pair 2; arrows indicate traversal direction. In (a), the cross routes exchange e and f in their forward directions. In (b), pair 2 crosses from high to low, and each cross route uses the other selected edge backwards. The low- and high-side length changes are respectively and in (a), and and in (b). The sum cannot be negative, since each cross route connects a prescribed pair. Dashed routes need not be disjoint; crossings without marked vertices are schematic.
holds. If neither comparison is strict in the displayed direction, both are equalities and both e and f are tight in and .
Proof. Put . The selected edges and their feasible child paths are tight, so
We first compare both sums of differences with . Expanding and with these two identities, the edge weights cancel, and
The two inequalities are the triangle inequalities for the cross routes: the route through connects to , and the route through connects to . The left side lies in and the right side in , so the chain is well defined.
If and , the allowed extended values force all four values to be finite, and adding the two inequalities contradicts the chain. This proves the dichotomy. If neither comparison is strict in the displayed direction, then and , the four values are again finite, and the chain forces . Hence both comparisons are equalities, and both inequalities in the chain are equalities, so both cross routes have their prescribed shortest length. By Lemma 5.1, the route for pair 2 makes tight in , and the route for pair 1 makes tight in . Each edge was already tight for its selected pair, as required.
The next lemma reports a side on which the exchange strictly lengthens the routes.
Lemma 5.4 (Common-sink reduction). If , the two disjoint shortest low-side path pieces ending at can be reported in time. If , the two high-side pieces can be reported within the same bound.
Proof. We prove the low-side statement by making the endpoint pairing follow from shortestness. Attach both boundary vertices to one sink, choosing the two attachment weights so that each source strictly prefers its designated boundary vertex. Since the low side is a topological prefix, every path ending at or lies in it, so the regional distances below are also low-side distances. Double all edge weights in the low side, add a new sink , and add edges and of respective weights . Put
Rearranging , the strict potential inequality is in the extended order. Doubling ensures that, for integer inputs, the open interval contains an integer.
To force the pairing, when both endpoints are finite, choose ; if only the lower endpoint is finite, choose ; if only the upper endpoint is finite, choose ; if and , choose . Set
Then and , and both are integers when the input weights are integers. Moreover, , and in each case lies strictly between and because :
After doubling, the shortest route through has length , and the one through has length . Hence
so every shortest path enters through , and every shortest path through . Compute distance-to- labels in linear time, by topological dynamic programming for a DAG or by undirected integer-weight single-source shortest paths [Tho97]. Form the DAG of tight edges, split every vertex except into a unit-capacity in/out pair, and connect a super-source to with unit capacities. Feasibility of the low-side child supplies a flow of value 2, which two augmentations find in linear time: by the strict preferences just proved, the child pieces followed by and are shortest routes to , so all their edges are tight. Conversely, in a flow of value 2, the unit path through is a tight, hence shortest, path, so it enters through ; the path through enters through . Deleting yields disjoint shortest and paths. By Lemma 5.1, they lie in , respectively. For undirected positive-integer inputs, let bound the finite regional distances. Then the finite values of and lie in , so and , and the attachment weights fit in one RAM word. In a DAG, the real attachment weights take a constant number of exact operations. The high-side statement follows by reversing the DAG on the high side and applying the same construction to and boundary vertices : after the reversal, distances from are the original distances to , so becomes the low-side hypothesis.
Double equality. Suppose both comparisons of Lemma 5.3 are equalities. Then the condition of Lemma 5.4 is empty: no attachment weights make prefer while prefers , and a flow could pair with . Instead, we build one DAG in which every path and every path is shortest, and call the prescribed-pair algorithm of [Tho12]. By Lemma 5.3, both selected edges are tight in and . On the low side , topological closure keeps all four source-to-boundary distances inside , and
Double the weights and attach to a common sink with positive weights satisfying . The distance from a low-side vertex to is then
The triangle inequality gives and , so neither port reaches more cheaply through the other port. For and , the two terms of the minimum coincide because . Therefore
Thus the child paths lie in the common -tight DAG, since each realizes the drop of between its endpoints. Any tight path satisfies
and the same calculation holds for . Hence the prescribed-pair DAG algorithm of [Tho12], run on this DAG, returns disjoint shortest and paths, which lie in and by Lemma 5.1. Repeating on the reversed high side, the algorithm of [Tho12] returns both sides, which join through .
Combining the three cases gives the main result of this subsection.
Proposition 5.5 (One-sided reporting). For every assignment selected at a two-active DAG cut with two nonzero child evaluations, one complete side can be reported in time, or the entire pair can be reported within the same bound. At most one two-path child remains unresolved.
Proof. The four distance labels defining and take linear time by topological dynamic programming. By Lemma 5.3, a strict displayed inequality invokes Lemma 5.4 on the corresponding side, and only the opposite child remains. If neither is strict, the common-tight equality construction reports both sides. Concatenation through the selected crossing edges is valid by Lemma 3.2.
5.2.2 Undirected cuts
At an undirected distance-difference cut, path 1 crosses from the low side to the high side and path 2 from the high side to the low side (Section 5.3), so each side contains the beginning of one path and the end of the other. Orient a selected cut pair by
Reverse the low suffix of path 2 and the high suffix of path 1. The low-side paths run from to and from to ; after the reversal, the high-side paths run from to and from to . Define
Each side now carries two pieces that run from terminals to the cut, with sources on the low side and on the high side, and play the roles of . The cross routes traverse the other selected edge backwards (Figure 4(b)), which is legal because the graph is undirected. One new point arises: a shortest route in between two low-side vertices may pass through the high side, so restricting to one side can change distances. The lemma therefore also checks that the order needed by the common-sink construction survives this restriction.
Lemma 5.6 (Undirected one-sided reporting). At least one of and holds. On a side satisfying its weak inequality, restriction to that side preserves the order needed by the common-sink construction. A strict local order reports the side by a flow of value 2; local equality reduces to two prescribed vertex-disjoint paths in one common DAG. Hence Proposition 5.5 holds for an undirected distance-difference cut.
Proof. Cross-route comparison. Suppose both inequalities fail strictly. Since and are finite, forces both values to be finite, as in the proof of Lemma 5.3; the same holds for . Traverse backwards in the cross route from to , and traverse backwards in the cross route from to :
As in Lemma 5.3, the low-side exchange changes the total length by and the high-side exchange by . The sum of the cross-route lengths minus the two prescribed distances is therefore
a contradiction.
Suppose , and let be the low-side induced region. For , put
We claim that . The child paths lie in and are shortest in , so they preserve the two source-to-boundary distances and in , while the cross distances and can only increase from to . This gives the outer inequalities. The middle one is rearranged.
For positive attachment weights , put
the distance from to a new sink attached to and after doubling the weights of . Orient from to only if and ; positive weights make this a DAG.
Strict local order. If , choose by Lemma 5.4, with in place of . As there, every shortest path enters through and every shortest path through . The child paths then supply a flow of value 2, whose pieces have the required endpoint distances.
Local equality. Suppose . Since and , this value is finite. Choose positive integer weights with . The triangle inequalities and , together with the coincidence of the two terms of the minimum at and at , give
The child paths belong to this common DAG, and any tight path satisfies
with the same identity for . Hence the prescribed-pair DAG algorithm of [Tho12] returns shortest and paths.
Two undirected single-source shortest-path computations give all values in linear time [Tho97]; the high-side case is symmetric. Reversing a returned path piece restores its original orientation. One side satisfies its weak inequality, and the corresponding construction reports that side in linear time. This proves Proposition 5.5 for an undirected distance-difference cut.
5.3 The recursion is linear
This subsection completes the proof of Theorem 5.12. By Proposition 5.5 and its undirected counterpart Lemma 5.6, every cut of the reporting recursion leaves at most one two-path child, so it suffices that this child shrinks geometrically and that each region is handled in time linear in its size. We first make the number of edges of every region linear in its number of vertices by subdividing edges, and then treat DAGs and undirected graphs in turn.
Each region stores compact vertex and internal-adjacency lists obtained while partitioning its parent. Timestamped arrays avoid reinitializing entries at every recursive call, and data used by the common-sink construction are discarded before recursion. Returned subpaths and selected cut edges are stored in concatenation trees and flattened once at the end, so each path prefix is stored once.
Lemma 5.7 (Sparsity after edge subdivision). Replace every edge of weight by a private vertex and the two-edge path , with each new edge of weight . Expansion and contraction give a bijection between original path pairs and expanded path pairs, preserve vertex-disjointness, and multiply every path length by two. Moreover, every induced region of the expanded graph satisfies .
Proof. Every original path expands uniquely, and every path between original vertices in the expanded graph contracts uniquely because each has degree two and is incident only to the two halves of . Lengths double, so shortest paths correspond. Private subdivision vertices cannot create or remove an intersection between two expanded original-terminal paths.
Every expanded edge is incident to a subdivision vertex. Assign each regional edge to such an endpoint. Every subdivision vertex receives at most two edges, whence
□
5.3.1 DAGs
Fix a topological order of the expanded DAG. At an unresolved region, cut at a median vertex of the full regional order. Algorithm 5, together with Proposition 5.5, leaves at most one two-path child.
Lemma 5.8 (DAG recurrence). The DAG algorithm has expected running time and uses storage cells.
Proof. Every unresolved child contains at most vertices. By Lemma 5.7, its induced graph and cancellation circuit have size . Circuit construction, coefficient extraction, the at most two assignment tests, common-sink construction, flow, and path reporting require a constant expected number of linear passes. Therefore
Only one child survives. Releasing the parent circuit and temporary flow arrays before recursion gives peak space.
5.3.2 Undirected graphs
If some is disconnected from , the instance is infeasible. If the two terminal pairs lie in different connected components, report their shortest paths independently. Otherwise restrict the instance to their common component; all values below are then finite.
For the expanded undirected graph define
If an edge is oriented tightly in , the triangle inequality for gives ; on the inequality is reversed. A nonvertex threshold therefore is a monotone cut in the sense of Section 3. If an - or -edge has , it is tight in both systems with the same orientation. Hence the two tight graphs induce the same DAG on every equality plateau.
Choose a median of the multiset of -values in and put
If , cut immediately below . If , cut immediately above . In either case both sides contain at most vertices. Otherwise ; cut at one boundary of this heavy plateau. If the plateau is retained, the next call cuts at its other boundary. After at most two such cuts the remaining region is an exterior with fewer than vertices or the plateau itself.
The single-value plateau base case occurs when the two terminal ranges have only one common -value; the corresponding plateau may contain many vertices. The following lemma gives the exact reduction and reconstruction bound.
Lemma 5.9 (Single-value plateau base case). Let
and suppose . Put , and suppose is a DAG. In time, one can either report a path pair in when one path avoids , or construct an auxiliary instance on with two prescribed terminal pairs and size . Every solution of the auxiliary instance lifts to a solution in in time. Over all plateau leaves of the separator recursion, the total reduction and lifting cost is .
Proof. A common vertex of two paths in has a -value in , so every possible intersection lies in . Search for an path for each . If one exists, combine it with an arbitrary path for the other pair in . The resulting pair is disjoint because the first path contains no vertex of .
Entry and exit attachments. Assume now that every path in visits . For , define the possible first and last plateau vertices by
Add private vertices , edges for , and edges for . Denote the resulting DAG by .
Any path in meets in one contiguous segment by -monotonicity. Its first and last plateau vertices therefore define an path in . Conversely, an path selects an entry , an exit , and a path in . Join this plateau segment to witnessing exterior paths for the two selected attachments.
This lifting preserves disjointness. The auxiliary paths are disjoint on , and every exterior witness avoids internally. Moreover, at most one path has a nonempty exterior below : otherwise and , contradicting . The symmetric argument applies above . Hence exterior pieces of the two paths cannot intersect. Within each path, the prefix, plateau segment, and suffix occupy strictly ordered -ranges. All lifted edges belong to , so both lifted paths remain shortest.
Construction and cost. When , the set is found by one forward reachability scan from through , followed by a scan of edges entering ; when , its unique first plateau vertex is . The reverse rule from gives . Store one predecessor or successor per reached exterior vertex. These four forests recover the exterior witnesses only for the entries and exits selected by the auxiliary solution.
The prescribed-pair DAG algorithm of [Tho12] reports the paths in in time. Each plateau vertex creates at most four attachment edges, so constructing , solving it, and following the selected forest paths costs . Plateau leaves are disjoint regions of the separator partition; summing their vertex lists, edge lists, attachment edges, and four forests gives .
Lemma 5.10 (Undirected recurrence). The undirected algorithm has expected running time and uses words of space.
Proof. The active-count cases are handled exactly as in the DAG algorithm, using Lemma 5.6 at a two-active cut and Lemma 5.9 at a single-value plateau base case. Deterministic linear selection finds , and each cut uses a constant expected number of linear circuit evaluations, shortest-path computations, differentiation sweeps, assignment tests, and common-sink constructions. The single-source shortest-path calls take linear time [Tho97].
Grouping a balanced cut or a two-boundary heavy phase gives one of the recurrences
Both solve to . By the final assertion of Lemma 5.9, the total cost of all single-value plateau base cases is linear. Depth-first execution releases all temporary data of the parent before entering the unique child, proving the space bound.
Lemma 5.11 (Randomization and output verification). Let be the number of vertices of the expanded graph in the linear algorithms and the input size in the directed algorithm of Section 6. For every constant , a field of size at least makes the feasible-instance false-negative probability at most . Internal cut sampling changes only the expected running time. Every reported pair is valid.
Proof. Two vertex-disjoint paths use fewer edges than the graph has vertices, so the root polynomial has degree at most : the expanded graph has vertices, and in the directed algorithm the degree is at most . Schwartz-Zippel bounds the probability that the root evaluation vanishes by . All internal sampling is the detected retry of Lemma 3.3 and affects only the expected running time.
Finally, contract every subdivision vertex in the linear algorithms, and verify the endpoints, edge membership, total lengths, and vertex-disjointness of the two output paths in linear time. Thus randomization can cause only a false NO, never an invalid witness.
We now prove the formal version of Theorem 1.2.
Theorem 5.12 (Linear-time 2-DSP, formal version of Theorem 1.2). Let have vertices, edges, and four distinct terminals. Suppose is either a DAG with arbitrary real edge weights, or an undirected graph with positive integer edge weights bounded by . In the respective computational models of Section 2, for every constant , there is a randomized algorithm using expected time and storage cells that never returns an invalid pair, returns NO on every infeasible instance, and reports two vertex-disjoint shortest paths with probability at least on every feasible instance. Under a feasibility promise, root resampling gives a Las Vegas algorithm with the same expected running time.
Proof. Lemmas 5.7, 5.8, 5.10 and 5.11 give the running time, space, and error guarantees. Under a feasibility promise, root resampling succeeds with probability and therefore takes a constant expected number of trials.
6 Two disjoint shortest paths in directed graphs
This section proves Theorem 6.8. The undirected one-sided argument used cross routes traversing the selected edges in reverse. A directed graph need not contain these routes, so here we retain both children of a cut. This is affordable because the detector has superlinear regional cost: splitting a region decreases the sum of its children's costs by a constant factor. The remaining task is to build the regional detector cheaply.
We do this using only the two source-distance labelings. On the regional shortest-path supports, the cancellation recurrence of [CKS26] becomes a triangular matrix computation: each column uses only earlier columns. Evaluating one column at a time gives gates; batching earlier-to-later contributions gives gates. We first justify the recurrence, then give both evaluation schedules, and finally sum their costs over the reporting recursion.
The algorithm needs the two source-distance labelings. The next lemma computes them within the claimed time, also for negative weights.
Lemma 6.1 (Source distances). Let be a directed graph with vertices, edges, no parallel edges, and real edge weights in which every directed cycle has positive total weight, and let be a vertex. The labeling , together with a shortest-path tree, can be computed in expected time, and the output is always correct.
Proof. A labeling equals if , is finite exactly on the vertices reachable from , for every edge with finite, and every reachable vertex has an incoming edge with . Indeed, the edge inequalities, applied along a shortest path, give . Conversely, fix one such tight incoming edge for every reachable vertex other than , and follow the fixed edges backwards from . The walk never repeats a vertex, since a repeated vertex would close a cycle of tight edges, whose weight telescopes to zero, whereas every cycle has positive weight. It can stop only at , and reversed it is an path of weight ; hence . These conditions, and the tree formed by the tight edges, are checked in time.
First restrict to the vertices reachable from in time, and give every other vertex the label . The restricted graph has vertices and edges, since every vertex other than has an incoming edge from the search tree. On it, run the Bellman–Ford algorithm [Bel58] and the Las Vegas algorithm of [HLLZ26] alternately, one step at a time, verify every labeling that either returns, and stop at the first verified labeling. Bellman–Ford returns the distances within steps. With high probability, in particular with probability at least , the algorithm of [HLLZ26] returns the distances within steps. The expected number of steps is therefore at most , and the total expected time is .
Let be the input sizes. The preprocessing has three phases.
-
Delete self-loops, which are positive-weight cycles and never lie on a shortest path, and keep one minimum-weight copy of every set of parallel edges; only such copies can be tight, and vertex-disjointness does not distinguish parallel copies.
-
Compute the source-distance labels for , together with their shortest-path trees, by Lemma 6.1, in expected time; for nonnegative weights, Dijkstra's algorithm with Fibonacci heaps takes time [FT87]. These two labelings are the only distances used by the algorithm.
-
If for some , the instance is infeasible. If the two terminal pairs lie in different weak components, the two shortest-path trees report their paths. Otherwise retain their common weak component and write for its sizes; then because the component is weakly connected, , and because no self-loops or parallel edges remain.
Every tight shortest-path graph is acyclic because every directed cycle has positive total weight, whereas the weight of a directed cycle of edges tight for telescopes to zero.
Delete every vertex with , since no prescribed path can use it. On the remaining vertices, extend the distance-difference coordinate by
Thus vertices reached only from sit at the bottom of the extended order, and vertices reached only from at the top.
The next lemma is the directed counterpart of the monotonicity used for undirected graphs in Section 5.3. It makes thresholds of monotone cuts in the sense of Section 3 and forces the crossing-edge assignment at each of them.
Lemma 6.2 (Directed distance-difference separator). The coordinate is nondecreasing on and nonincreasing on , including in the extended order. Every finite equality plateau is a common DAG. At a strict nonvertex threshold, the first path crosses on a strictly increasing edge and the second on a strictly decreasing edge, so the two cut-edge sets are disjoint and their assignment to the terminal pairs is forced.
Proof. If and are finite, then
where the equality is the tightness of for and the inequality is the directed triangle inequality along . Thus . For with finite, exchanging the roles of and gives , hence . It remains to treat infinite values. Both endpoints of an -edge have finite , so neither has . Along an -edge, reachability from can change only from false to true, so if one of the two values is , then . On an -edge the value does not occur, reachability from can change only from false to true, and a value forces .
Let with . Then are finite, and equality at a finite value in the displayed inequality gives , so the edge is tight in both and . The same computation with and exchanged shows that every -edge inside the plateau lies in . A directed cycle of finite equality edges would be tight for and would have total weight zero, so each finite plateau is acyclic.
Finally, consider a strict nonvertex threshold. An -path crossing it uses an edge whose tail lies below and whose head lies above the threshold, so strictly increases along this edge; by the first step, an -path crosses on an edge along which strictly decreases. No edge has both properties, so the two cut-edge sets are disjoint, and the direction of a cut edge determines its terminal pair.
6.1 Aligned regions and their supports
Call an instance aligned when for an interval of the extended line and, for each , the endpoints occur in this order on an -path. Its supports are the subgraphs formed by the vertices and edges of paths in . Thus the th paths of the instance are exactly the paths of , and the supports are the only parts of the tight graphs that the regional polynomial sees. Both supports are acyclic as subgraphs of . Every vertex of lies on an path, so is the unique source of , and is its unique sink. The edges of are recognized from , and one forward search from and one backward search from construct in time.
The detector of [CKS26] exchanges subpaths between the two terminal pairs. In Lemma 6.4 below, a piece of a first path and a piece of a second path both run from a vertex to a vertex , and the cancellation swaps their segments; the segment taken from must then be a path of , and conversely. The following lemma shows that the two supports agree on every segment they share, so these exchanges stay inside and without any further distance information.
Lemma 6.3 (Shared segments). Let , let be formed by the vertices and edges of paths in , and suppose that reaches in both and . Then and have the same paths, namely the shortest paths of contained in .
Proof. Fix . An path exists in , and its tight edges give weight . The triangle inequality gives the reverse bound , so this path, and every other path of , is shortest.
Conversely, let be any globally shortest path. Prefix it by a shortest path. The resulting walk has length ; a repeated vertex would create a positive-weight cycle that could be deleted to shorten it. Thus every edge of is tight for . Since , join to an path and a path of . This is a walk in the acyclic graph , hence a path, so .
6.2 A causal matrix form of the cancellation recurrence
This subsection expresses for an aligned instance through auxiliary states collected in a matrix . The main identity (Lemma 6.4) writes every state through and the path matrices of the supports, and Lemma 6.5 shows that each column of depends only on earlier columns in a topological order of .
Boundary instances need no recurrence. If , the th path has zero edges and is the path sum of the other pair in ; if both paths have zero edges, is 1 when their vertices differ and 0 otherwise; and a terminal shared by the two pairs gives . Each case costs one path-sum pass. Fix now an aligned instance with four distinct terminals and two nonempty paths. Index rows and columns by , let be the matrix with entry at every edge of and zero elsewhere, and let
Since is acyclic, is nilpotent, and . The entry sums the monomials of the walks of with edges, which are paths by acyclicity. Hence is the sum of the monomials over the paths of , with . Put and ; a path of and a path of can share only vertices of and edges of .
The auxiliary states of the recurrence fix the first path's source and the second path's sink and vary the two remaining endpoints. For and , define
where ranges over the paths of , over the paths of , and the pair must satisfy ; an empty path at a vertex has vertex set . Thus the two paths are disjoint, except that they may share the free endpoint when . The output state has disjoint vertex sets, because , and therefore no shared edge, so
The recurrence uses the diagonal states for and the edge states for . Collect them in the matrix indexed by , with
(a) Exchange the two r-t segments

(b) Fixed point: one shared edge

Figure 5: The involution in Lemma 6.4. The first path runs from to (blue), and the second from to (orange). In (a), is the last common vertex before on the blue prefix; the two segments lie in both supports by Lemma 6.3. Exchanging them preserves the monomial, so distinct paired configurations cancel in characteristic two. In (b), both segments are the same edge. These fixed points survive with the squared edge weight, giving the term .
and all other entries zero. Column of thus consists of the states whose second endpoint is . A diagonal state counts two paths that meet exactly at , the first ending and the second starting there. An edge state arises from configurations in which both paths traverse the common edge , and the factor records the two traversals.
Figure 5 illustrates the identity behind the recurrence. The product counts all pairs of an path of and an path of , so in characteristic two is this product plus the contribution of the pairs that meet. Cut a meeting pair at the first vertex of its first path that lies on its second path, not counting a shared endpoint. This gives four pieces: from to and from to on the first path, and from to and from to on the second. The pieces and are counted by and , and the pair , which meets only at , by the diagonal state . This product ignores one constraint, namely that avoids before . Swapping the last common segment of and cancels the violating quadruples in pairs, and the swap stays in the supports by Lemma 6.3. The only unpaired violations are those in which and enter through one common edge , and they are counted by the edge state . Altogether, the meeting pairs with first intersection contribute .
The next identity is the first-intersection cancellation of [CKS26, Section 4], specialized to the two supports. Its proof needs only acyclicity and Lemma 6.3; in particular, every sum ranges over all of and , and the restrictions to admissible intersections are carried by the path matrices themselves. For instance, a vertex that does not reach in contributes nothing, because . This uniformity over all states is what turns the recurrence into a matrix product.
Lemma 6.4 (First-intersection identity). For every and ,
Proof. Put , and let denote the sum of the path-product monomials of a family . The product counts all path pairs. The desired pairs may meet only in ; in characteristic two, adding the contribution of all other pairs removes them.
First-intersection classes. Let be the first vertex of the first path that lies on the second path outside . Split the paths into
For fixed , let contain all such quadruples with the indicated endpoints and supports, subject only to . Then
Acyclicity makes and paths. Call a quadruple good when , and bad otherwise, with families . Splitting at the first intersection gives a monomial-preserving bijection onto : vertices of before avoid both and , since is contained in the last vertex of the first path. Conversely these two avoidance conditions make the first forbidden intersection of the joined pair.
Cancellation. For a bad quadruple, let be the last vertex of before lying on . Both supports contain an path, so Lemma 6.3 allows us to exchange the two segments:
Each concatenation stays in its support and is a path by acyclicity. The new second path avoids before : its -prefix already did, and its -suffix does because is a path. The image is bad with the same last shared vertex . Indeed, the interior of avoids by simplicity and avoids by the choice of . Applying again therefore exchanges the same segments back. The map preserves the multiset of edges, so nonfixed quadruples cancel in pairs.
Fixed points. A fixed point has . This segment has no interior shared vertex by the choice of , hence is one common edge . Removing its two traversals leaves an path of , a pair counted by , and a path of . Conversely, these pieces reconstruct a fixed point: inserting the common edge preserves disjointness of the middle pair before , and acyclicity makes both concatenations paths. Thus
The first equality uses cancellation and the fixed-point bijection; the second is the definition of . Since , characteristic two gives
using the diagonal term and the common-edge terms that constitute column of . Summing over counts every unwanted pair once and proves the identity.
Only some states are needed: the diagonal states, the edge states, and the output state. For a state in column of , the first argument in Lemma 6.4 is itself or the tail of an edge of . Since unless reaches in , only first intersections before in a topological order of contribute. Thus column of depends only on earlier columns, and can be filled column by column, as in forward substitution for a triangular system. The following accumulated sums collect the contributions of the earlier columns: row of is row of with the middle index restricted to vertices before .
Order by a topological order of . For and , define the accumulated sums
Lemma 6.5 (Causal recurrence). For every and every ,
and
In particular, column of is determined by , and the columns of .
Proof. Apply Lemma 6.4; in each case, the structural zeros of cut the sum over down to the stated range. For the diagonal state, , and unless precedes or equals in ; hence the sum ranges exactly over . For the edge state, , and unless , while because is an edge of ; hence again only contributes. For the output state, because the terminals are distinct, and the sum over all is the entry , since has no nonzero entry outside the columns . The final assertion holds because involves only the columns of .
6.3 Two evaluation schedules
Throughout this subsection, fix and put . By Section 2, two matrices over are multiplied with field operations, so an by product, or an by product with , splits into square products and costs operations.
Lemma 6.5 reduces the regional detector to computing the entries and in the order . Writing for the vertices of , the definition of reads
and the states in column of are computed from the row . Thus column feeds every later row, but only after it is final. This is the dependence pattern of the three-pair schedule of Section 4.3, with the columns of in the role of the finished table rows and the rows of in the role of the accumulators. The first schedule is forward substitution: it computes one row of at a time by a path-sum pass over , which costs per row; the second batches rows by divide and conquer and fast matrix multiplication. It splits the indices into a lower half and an upper half (Figure 6). Once all columns in are final, their entire contribution to the rows in is one product of three rectangular matrices, and the contributions within and within are handled recursively. Every pair is separated at exactly one node of this recursion. A node whose halves have indices multiplies matrices with dimensions and , and since , the cost of the recursion is dominated by its top level.
Lemma 6.6 (Directed circuit for a region). Given and , the polynomial of an aligned instance has division-free straight-line circuits of size and, for every fixed , of size . Each circuit is constructed in time linear in its size, and its structure is determined by , the terminals, and .

-
SOLVECOLUMNS(L): its columns become final.
-
Add their contribution to :
- SOLVECOLUMNS(H) with these contributions.
Figure 6: The causal matrix schedule. A source column contributes to target row only for , below the dashed diagonal. The dark rectangle batches the contributions from the first half into the second half ; lighter rectangles are batches at deeper recursion levels. Each ordered pair is processed exactly once, after its source column is final and before its target row is used. The rectangles depict dependency pairs, rather than submatrices of the final output.
Proof. We evaluate the quantities of Lemma 6.5 in the order , once row by row and once by divide and conquer, and count the gates of each schedule.
Construct and in time. By Lemma 6.5, it suffices to compute the needed entries of and , the entries and for in the order , filling each column of as soon as its states are known, and finally the root expression. Every index set and every order used below is determined by and , and no step tests a field value.
The first schedule evaluates rows by path-sum passes.
- For each , one pass over in topological order computes the row by
Analogous passes compute the row , the row , and the columns and . These passes use gates.
- Process in the order . At that time every column of is known, and a scan of and gives
for all with gates. Put for every other . One pass over in topological order then computes
for all . Lemma 6.5 now gives the states in column of with gates each.
- Evaluate the root expression from the row and the column .
The last-edge recurrence verifies the row pass. Induct along : every edge of has , so the induction hypothesis applies to , and the computed entry satisfies
Since for with and otherwise, the right-hand side is .
Each costs gates, and the root expression costs more. With the initial passes, the row schedule has gates.
The second schedule batches the earlier-to-later contributions. Let ; simple graphs have , so the support construction is within the bound.
Path matrices. For each , order by a topological order of followed by the vertices outside , so that is strictly upper triangular and is unit upper triangular; the reordering is a relabeling of rows and columns. In characteristic two, a block upper triangular matrix with unit-triangular diagonal blocks satisfies
where the sign of the upper right block disappears in characteristic two. The diagonal blocks of a unit upper triangular matrix are again unit upper triangular. Recursing on the two diagonal blocks computes with operations and no division.
Let enumerate . For an index interval , the procedure SOLVECOLUMNS() does the following.
-
If , it computes the states in column of from the current row by Lemma 6.5.
-
Otherwise it splits into a lower half and an upper half , calls SOLVECOLUMNS(), adds
to the rows , and calls SOLVECOLUMNS(). Here and denote the vertex sets indexed by and .
Starting from , call SOLVECOLUMNS().
Causality of SOLVECOLUMNS. For indices , exactly one call has and , namely the call on the smallest interval of the recursion that contains both; the product at that call adds exactly the terms with and . At that call the column of is final because SOLVECOLUMNS() has returned, and has not yet been processed. Hence each term of is added exactly once before is processed, as Lemma 6.5 requires.
Cost of SOLVECOLUMNS. A call on an interval of size multiplies an by an matrix and then an by an matrix, using operations. There are such calls, so the intervals of size cost in total. Summing over gives , since makes the sum geometric.
The base calls cost , and the root expression costs . Together with the path-matrix construction and , the circuit therefore has gates.
6.4 The reporting recursion
We now check that Algorithm 5 applies to aligned instances: thresholds of have forced crossing-edge assignments, and every cut produces aligned children.
For an aligned instance, put , , and . By Lemma 6.2, every vertex of an th path has its -value in . A feasible -path excludes and a feasible -path excludes , so contains neither infinite value. If , the two path ranges are disjoint, and arbitrary shortest paths for the two terminal pairs are vertex-disjoint. If is a singleton, Lemmas 5.9 and 6.2 apply: its value is finite, so Lemma 6.2 makes its plateau a common DAG, as Lemma 5.9 requires. That lemma uses the full graphs , which are available from and .
Consider a threshold between consecutive extended -values. Since is monotone along every th path, the th pair is active exactly when the threshold lies in the interior of its interval . With two active pairs, Lemma 3.2 gives a squarefree quadratic cut polynomial. For and , the child terminal pairs are below the cut and above it. The edge directions in Lemma 6.2 determine the edge-to-pair assignment, so the sum in Lemma 3.2 has at most one term, and exactly one for the edge pair returned by Lemma 3.4, since its coefficient is nonzero:
where and are the sides below and above the threshold and is the forced assignment. Thus Lemma 3.4 selects two nonzero child evaluations directly.
The remaining active-count cases follow Algorithm 5. Hence every strict cut produces at most two aligned two-path children and preserves the nonzero-evaluation invariant.
The next lemma bounds the total cost: the circuit size of a region contracts by a constant factor from the region to its recursive children, so the root circuit dominates.
Lemma 6.7 (Directed recursion cost). After the two source-distance computations, the directed reporting recursion takes expected time and storage cells with the row schedule of Lemma 6.6, and, for every fixed , expected time and storage cells with its matrix schedule.
Proof. Balancing the regions. Treat a heavy plateau as one phase. Sort the vertices once by extended . Every region is a union of consecutive -levels. For a region , choose a median of its vertex -values and put
and let be the plateau of . The cut is chosen as follows.
-
Balanced cut. If , cut immediately below ; if , cut immediately above it. In either case every child has at most vertices, since for a median.
-
Heavy finite plateau. Otherwise . For finite , process at most the two boundary cuts of the plateau . A surviving two-path child on is a base case by Lemmas 5.9 and 6.2; every other recursive child lies in .
-
Infinite plateau. For , no -path uses , because on , and for , no -path uses . Thus one boundary cut invokes a zero- or one-active case and leaves no two-path child on an infinite plateau.
Let be for the row schedule and with for the matrix schedule. By Lemmas 3.4 and 6.6, the expected work at a cut, including the child evaluations (at most ) and the regional scans, is ; for the matrix schedule this uses .
Contraction of the cost. The recursive children have disjoint vertex sets and disjoint internal edge sets, and every child of a balanced cut has at most vertices. Hence, at a balanced cut,
The recursive children of a heavy-plateau phase lie outside and contain fewer than vertices in total. Bounding the largest child by this total in the two estimates gives .
Total time and space. A heavy-plateau phase performs at most two cuts, hence costs . Plateau leaves cost in total by Lemma 5.9. Induction over balanced cuts and grouped heavy-plateau phases, using the contraction estimate, gives total expected work, since the potentials of the regions at successive levels of the grouped recursion decrease geometrically. The component preprocessing gives , so for the row schedule, and for the matrix schedule. The one-time ordering is absorbed in both bounds.
Depth-first execution releases a parent circuit before constructing a child, and unvisited siblings have disjoint region lists. The largest live circuit has gates, and the gradient evaluations of Lemma 3.3 store field elements per gate, which gives the storage bounds.
We now prove the formal version of Theorem 1.3.
Theorem 6.8 (Directed 2-DSP, formal version of Theorem 1.3). Let be a directed graph with vertices, edges, four distinct terminals, and real edge weights. Suppose every directed cycle has positive total weight. In the computational model of Section 2, for every constant and every fixed , there is a randomized algorithm using expected
time and storage cells that never returns an invalid pair, returns NO on every infeasible instance, and reports two vertex-disjoint shortest paths with probability at least on every feasible instance. Evaluating only the root circuit decides feasibility within the same time bound.
Proof. Compute and by Lemma 6.1 in expected time, since at most edges remain after parallel edges are merged, and use the row schedule if and the matrix schedule otherwise. At each strict cut, Lemmas 3.2, 3.4 and 6.2 preserve nonzero subinstance evaluations; disjoint terminal ranges and single-value plateaus are base cases. The reporting recursion costs by Lemma 6.7, and Lemma 5.11 gives the one-sided error guarantee.
A Regional instances of the cancellation identities
This appendix completes the proof of Lemma 5.2. The polynomial of two disjoint shortest paths is computed in [AVW24] for the whole graph, with two terminal pairs and the graphs whose paths are exactly the shortest ones. We show that the same identities compute the regional polynomial of every region produced by the algorithms of Section 5, with the same circuit size.
Fix such a region with terminal pairs and . By the first part of the proof of Lemma 5.2, we may assume that both paths contain an edge and that the boundary vertices required to be disjoint are distinct. We apply the identities of [AVW24] with , , and replaced by , , and . Every object in these identities is then defined from and alone:
-
the path sums of the paths and of the paths in ;
-
for each vertex , the set of vertices such that is an arc of both and , and the set of vertices such that is an arc of and is an arc of ;
-
the source linkages , the target linkages , and the polynomials of [AVW24, Lemmas 22, 36, and 38], which are sums of products of these path sums and edge variables.
In particular, no distance to a regional terminal is needed: a vertex on no path of has and contributes nothing, and the only distances used are the global labels that define and .
Lemma A.1 (Regional transfer). With these substitutions, the identities of [AVW24, Lemmas 22 and 23] compute for every region of a DAG, and together with the identities of [AVW24, Lemmas 30, 36, 38, and 39] they compute for every region of an undirected graph. Evaluating them uses additions and multiplications over the field, and the circuit is constructed in time.
Proof. Apart from counting identities that hold for any two directed graphs, such as the inclusion-exclusion over first edges behind [AVW24, Lemmas 21 and 36], the proofs in [AVW24, Section 4] use the graphs only through four properties. We first verify each of them for , and then account for the cost.
The first property is that every path of is a shortest path of , and that a walk of from to is such a path. For , every arc is tight for , so an path of has length , which equals by the triangle inequality, as in the proof of Lemma 5.1. Hence it is a shortest path of , and so is each of its subpaths. A walk of repeats no vertex, because is acyclic. This also holds for DAGs with arbitrary real weights, since a DAG has no cycle at all.
The second property is that is acyclic, which the path-sum recurrences use. The graph is a subgraph of the acyclic graph .
The third property, used only for undirected graphs, is [AVW24, Proposition 24]: if three vertices appear in some order on a shortest path of , then on every shortest path of through all three, the middle one lies between the other two. This is a statement about shortest paths of , and by the first property it applies to all regional paths and their subpaths.
The fourth property is the exchange of subpaths. Let and be an path of and an path of that both visit vertices and . If both visit before , the proofs exchange and [AVW24, Lemma 14]. In undirected graphs, if visits before and visits before , they exchange with the reversal of , and with the reversal of
[AVW24, proof of Lemma 33]. In either case the two exchanged pieces are shortest paths of by the first property, so they have the same length, and the exchanged walk from to has length and uses only vertices of . Prefix by a shortest path. The result is an walk of length . A repeated vertex would contradict acyclicity in a DAG and, in an undirected graph, would close a cycle of positive weight whose deletion gives a shorter walk. Hence the walk is a shortest path, each of its edges is tight for , and is an path of . Every exchanged physical edge already lies on or , and a reversed edge carries the same variable , so the multiset of edge variables is unchanged.
Every step in the proofs of the cited lemmas is a decomposition of a pair of paths at a vertex or at a common edge, which needs the first property; a statement about the order of vertices along shortest paths, which needs the third; or an involution that exchanges subpaths, which needs the fourth. All pieces lie in , so the boundary of is never crossed, and the identities hold for .
It remains to bound the cost. The global labels and the tight graphs are computed once at the root, and each region receives its vertex and adjacency lists from its parent, so is available in time. A topological order of is found by depth-first search in time, without sorting distance values. The path sums and follow by forward and backward dynamic programming in this order. For each vertex , one scan of its incident edges determines and . As in the proof of [AVW24, Theorem 1], then takes operations by [AVW24, Lemma 22], and in an undirected graph so do and by [AVW24, Lemmas 36 and 38]. The sums of [AVW24, Lemmas 23, 30, and 39] add further operations. All operations are additions and multiplications; in characteristic two, subtraction is addition.
References
[ADV+25] Josh Alman, Ran Duan, Virginia Vassilevska Williams, Yinzhan Xu, Zixuan Xu, and Renfei Zhou. More asymmetry yields faster matrix multiplication. In SODA, 2025. Full version arXiv:2404.16349v3, 2026.
[AVW24] Shyan Akmal, Virginia Vassilevska Williams, and Nicole Wein. Detecting disjoint shortest paths in linear time and more. In ICALP, volume 297 of LIPIcs, pages 9:1–9:17, 2024. Full version: arXiv:2404.15916.
[Bel58] Richard Bellman. On a routing problem. Quarterly of Applied Mathematics, 16(1):87–90, 1958.
[BK17] Kristof Berczi and Yusuke Kobayashi. The directed disjoint shortest paths problem. In ESA, volume 87 of LIPIcs, pages 13:1–13:13, 2017.
[BKK14] Andreas Björklund, Petteri Kaski, and Łukasz Kowalik. Fast witness extraction using a decision oracle. In Algorithms – ESA 2014, volume 8737 of Lecture Notes in Computer Science, pages 149–160, 2014.
[BNRZ21] Matthias Bentert, André Nichterlein, Malte Renken, and Philipp Zschoche. Using a geometric lens to find disjoint shortest paths. In ICALP, volume 198 of LIPIcs, pages 26:1–26:14, 2021.
[BS83] Walter Baur and Volker Strassen. The complexity of partial derivatives. Theoretical Computer Science, 22(3):317–330, 1983.
[CKS26] Keerti Choudhary, Amit Kumar, and Lakshay Saggi. Efficient algorithms for the disjoint shortest paths problem and its extensions. In ITCS, volume 362 of LIPIcs, pages 39:1–39:23, 2026.
[DEK 26] Emilien Dupont, Marvin Eisenberger, Borislav Kozlovskii, Abbas Mehrabian, Francisco J. R. Ruiz, Abigail See, Renfei Zhou, Josh Alman, Virginia Vassilevska Williams, and Matej Balog. Improving the matrix multiplication exponent with modern optimization and AlphaEvolve. arXiv:2608.16884, 2026.
[Epp95] David Eppstein. Finding common ancestors and disjoint paths in DAGs. Technical Report 95-52, Department of Information and Computer Science, University of California, Irvine, 1995.
[FHW80] Steven Fortune, John Hopcroft, and James Wyllie. The directed subgraph homeomorphism problem. Theoretical Computer Science, 10(2):111–121, 1980.
[Fin23] Jeremy T. Fineman. Single-source shortest paths with negative real weights in time, 2023. arXiv:2311.02520.
[FT87] Michael L. Fredman and Robert Endre Tarjan. Fibonacci heaps and their uses in improved network optimization algorithms. Journal of the ACM, 34(3):596–615, 1987.
[HLLZ26] Isaac M. Hair, George Z. Li, Jason Li, and Junkai Zhang. Bellman-Ford in almost-linear time. arXiv:2607.19346, 2026.
[MVV87] Ketan Mulmuley, Umesh V. Vazirani, and Vijay V. Vazirani. Matching is as easy as matrix inversion. Combinatorica, 7(1):105–113, 1987.
[PS78] Yehoshua Perl and Yossi Shiloach. Finding two disjoint paths between two pairs of vertices in a graph. Journal of the ACM, 25(1):1–9, 1978.
[Tho97] Mikkel Thorup. Undirected single-source shortest paths in linear time. In 38th Annual Symposium on Foundations of Computer Science, pages 12–21. IEEE, 1997.
[Tho12] Torsten Tholey. Linear time algorithms for two disjoint paths problems on directed acyclic graphs. Theoretical Computer Science, 465:35–48, 2012.
AI methodology statement
We used Claude Opus 5.5 (Anthropic) and GPT-6 Astra (OpenAI) to assist with literature review, the design and analysis of the algorithms, computational checks on small instances, and manuscript drafting. These tools materially affected all sections, in particular the algorithms and proofs of Sections 3 to 6 and Appendix A. The authors verified the correctness and originality of all content, including references.