Enumerate Directed Paths between the End Labels

Quick Overview

Enumerate Directed Paths between the End Labels. Given a directed acyclic adjacency-list graph on labels 0 through n-1, return every path beginning at 0 and ending at n-1.

Enumerate Directed Paths between the End Labels

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Given a directed acyclic adjacency-list graph on labels 0 through n-1, return every path beginning at 0 and ending at n-1. Return the paths in any order, preserving vertex order inside each path. ```cpp class Solution { public: vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph); }; ``` ### Examples **Example 1:** ```text graph = [[1,2],[2],[]] One valid output: [[0,1,2],[0,2]] Explanation: The middle vertex is optional through the direct edge. ``` **Example 2:** ```text graph = [[1],[],[]] Output: [] Explanation: Vertex2 cannot be reached from0. ``` ### Constraints - The DAG contains n vertices with 2 <= n <=15. - Neighbor labels are in [0,n-1], with no self-edge and no duplicate within a neighbor list. ### Contract considerations Preserve directed adjacency and unrestricted outer-list ordering. ```hint Read the boundary condition Why can a global visited set discard distinct valid paths? ``` ### What a Strong Answer Covers Preserve directed adjacency and unrestricted outer-list ordering. ### Follow-up Questions Optional practice extension: How could reverse reachability identify branches that cannot reach the destination?

Overview: Enumerate Directed Paths between the End Labels. Given a directed acyclic adjacency-list graph on labels 0 through n-1, return every path beginning at 0 and ending at n-1.

Amazon logo
Amazon
Source window: 0–6 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Given a directed acyclic adjacency-list graph on labels 0 through n-1, return every path beginning at 0 and ending at n-1. Return the paths in any order, preserving vertex order inside each path.

class Solution {
public:
    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph);
};

Examples

Example 1:

graph = [[1,2],[2],[]]
One valid output: [[0,1,2],[0,2]]
Explanation: The middle vertex is optional through the direct edge.

Example 2:

graph = [[1],[],[]]
Output: []
Explanation: Vertex2 cannot be reached from0.

Constraints

  • The DAG contains n vertices with 2 <= n <=15.
  • Neighbor labels are in [0,n-1], with no self-edge and no duplicate within a neighbor list.

Contract considerations

Preserve directed adjacency and unrestricted outer-list ordering.

What a Strong Answer Covers Guidance

Preserve directed adjacency and unrestricted outer-list ordering.

Follow-up Questions Guidance

Optional practice extension: How could reverse reachability identify branches that cannot reach the destination?