1. Problem Understanding
The problem gives us an array called edge[], where every index represents a node (cell) in a directed graph.
Each node can have at most one outgoing edge.
Our task is to:
- Identify all cycles in the graph.
- Calculate the sum of node indices belonging to each cycle.
- Return the maximum cycle sum.
- If there is no cycle, return
-1.
Example:
Input: edge = [1, 2, 0, -1]
Output: 3Let's understand the array:
| Node | Outgoing edge |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 0 |
| 3 | -1 |
This represents:
0 → 1 → 2 → 0We return to node 0, so a cycle exists.
Cycle sum:
0 + 1 + 2 = 3Node 3 has no outgoing edge because its value is -1.
2. Understanding the Graph Concept
Before implementing the solution, let's understand what a directed graph is.
A graph contains:
- Vertices (Nodes): The individual cells.
- Edges: Connections between nodes.
- Directed edges: Connections that have a specific direction.
For example:
Directed graph
0
1
2
2 → 0 closes the cycle
The directed path returns to its starting node.
A cycle occurs when we follow the outgoing edges and eventually reach a node that is already part of the current path.
For this problem, we don't need a general graph adjacency list because each node has only one outgoing edge. The given array itself represents the graph.
3. What Algorithm Should We Use?
We can solve this problem using Graph Traversal with Visited Tracking and Path Indexing.
We maintain three important things:
- A visited array.
- A path index array.
- A variable to store the maximum cycle sum.
Let's understand why each one is required.
A. Visited Array
bool[] visited = new bool[n];This array tells us whether a node has already been visited.
For example:
visited = [true, true, true, false]This means:
- Node 0 is visited.
- Node 1 is visited.
- Node 2 is visited.
- Node 3 is not visited.
Why do we need it?
Without visited, we might process the same nodes repeatedly, resulting in unnecessary work.
B. Path Index Array
int[] pathIndex = new int[n];
Array.Fill(pathIndex, -1);This is the most important part of our cycle detection logic.
pathIndex[] stores the position of each node in the current traversal path.
Consider:
path = [0, 1, 2]The corresponding path indices are:
| Node | Path index |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
Suppose we reach node 1 again.
Since:
pathIndex[1] = 1We know that the cycle starts at position 1.
Therefore, the cycle is:
1 → 2 → 0 → 1For our example, if the path were [0, 1, 2] and the next node were 0, the cycle would start at position 0.
C. Maximum Sum
int maxSum = -1;This stores the highest cycle sum found so far.
We initialize it to -1 because the problem requires returning -1 when no cycle exists.
4. Cycle Detection – Understanding the Main Logic
This is the most important code:
while (current != -1 && !visited[current])The loop runs while:
- The current node is not
-1. - The current node has not already been visited.
Inside the loop:
visited[current] = true;
pathIndex[current] = path.Count;
path.Add(current);
current = edge[current];Let's understand each statement.
Step 1:
visited[current] = true;Mark the current node as visited.
Step 2:
pathIndex[current] = path.Count;Store the current node's position in the traversal path.
Step 3:
path.Add(current);Add the current node to our path.
Step 4:
current = edge[current];Move to the next node using the outgoing edge.
This continues until we reach -1 or a previously visited node.
5. Complete C# Code
Here is the complete implementation using the same method signature provided in the question.
class Solution {
public int largestSumCycle(int[] edge) {
int n = edge.Length;
// Track visited nodes
bool[] visited = new bool[n];
// Store the position of each node in the current path
int[] pathIndex = new int[n];
Array.Fill(pathIndex, -1);
int maxSum = -1;
// Start traversal from every unvisited node
for (int i = 0; i < n; i++) {
if (visited[i])
continue;
List<int> path = new List<int>();
int current = i;
// Traverse until no edge or an already visited node
while (current != -1 && !visited[current]) {
visited[current] = true;
pathIndex[current] = path.Count;
path.Add(current);
current = edge[current];
}
// Check whether the current node belongs
// to the current traversal path
if (current != -1 && pathIndex[current] != -1) {
int sum = 0;
// Calculate only the cycle nodes
for (int j = pathIndex[current]; j < path.Count; j++) {
sum += path[j];
}
maxSum = Math.Max(maxSum, sum);
}
// Reset path index for the next traversal
foreach (int node in path) {
pathIndex[node] = -1;
}
}
return maxSum;
}
}Note about integer range: The theoretical maximum cycle sum under the given constraints can exceed Int32.MaxValue. For complete numerical correctness in C#, use long for the sum and change the return type to long if the coding platform permits it. The code above follows your requested int signature.
6. Understanding the Complete Code – Line by Line
Step 1: Get the array size
int n = edge.Length;This returns the total number of nodes.
For example:
edge = [1, 2, 0, -1]
n = 4The nodes are 0, 1, 2, 3.
Step 2: Create the visited array
bool[] visited = new bool[n];Initially:
visited = [false, false, false, false]Whenever we visit a node, we mark it as true.
Step 3: Create the path index array
int[] pathIndex = new int[n];
Array.Fill(pathIndex, -1);Initially:
pathIndex = [-1, -1, -1, -1]Here, -1 means the node is not currently present in the traversal path.
Step 4: Start the traversal
for (int i = 0; i < n; i++) {
if (visited[i])
continue;We check every node.
If a node is already visited, we skip it.
Why?
Because its outgoing path has already been explored.
Step 5: Create a new traversal path
List<int> path = new List<int>();
int current = i;The list stores the nodes visited during the current traversal.
For example:
path = [0, 1, 2]Step 6: Traverse the graph
while (current != -1 && !visited[current])This checks whether traversal can continue.
If the current node is -1, there is no outgoing edge.
If the current node is already visited, we stop and check whether a cycle exists.
Step 7: Detect the cycle
if (current != -1 && pathIndex[current] != -1)This condition is extremely important.
It checks two things:
- We did not reach
-1. - The current node belongs to the current traversal path.
If both conditions are true, we found a cycle.
Step 8: Calculate the cycle sum
for (int j = pathIndex[current]; j < path.Count; j++) {
sum += path[j];
}We start from the position where the cycle begins and add all remaining nodes in the path.
We do not include nodes that appear before the cycle.
Step 9: Update maximum sum
maxSum = Math.Max(maxSum, sum);Compare the newly calculated cycle sum with the previous maximum.
Step 10: Reset the path index
foreach (int node in path) {
pathIndex[node] = -1;
}This prepares the path index array for the next traversal.
We reset pathIndex, but we do not reset visited.
7. Dry Run – Example 1
Input:
edge = [1, 2, 0, -1]Initially:
visited = [false, false, false, false]
pathIndex = [-1, -1, -1, -1]
maxSum = -1Iteration 1: Starting from node 0
Current node = 0
| Step | Current | Path | Next |
|---|---|---|---|
| 1 | 0 | [0] | 1 |
| 2 | 1 | [0, 1] | 2 |
| 3 | 2 | [0, 1, 2] | 0 |
Now we reach node 0 again.
Our path index array is:
pathIndex = [0, 1, 2, -1]Since pathIndex[0] = 0, a cycle exists.
Cycle:
0 → 1 → 2 → 0Calculate:
sum = 0 + 1 + 2
sum = 3Update:
maxSum = 3Iteration 2: Starting from node 1
Node 1 is already visited, so skip it.
Iteration 3: Starting from node 2
Node 2 is already visited, so skip it.
Iteration 4: Starting from node 3
Node 3 points to -1.
No cycle exists.
Final result:
Output: 3
8. Dry Run – Example 2
Input:
edge = [2, 0, -1, 2]Graph:
Connections
1
0
2
-1
3
2
Traversal from node 0:
0 → 2 → -1No cycle.
Traversal from node 1:
1 → 0Node 0 was already visited in a previous traversal.
But:
pathIndex[0] = -1Therefore, node 0 does not belong to the current path, and no cycle is detected.
Traversal from node 3:
3 → 2Node 2 was visited previously, but it is not part of the current path.
Again, no cycle.
Final result:
Output: -1
9. Why Do We Need Both visited[] and pathIndex[]?
This is the most important interview concept in this problem.
visited[] | pathIndex[] |
|---|---|
| Tracks whether a node was visited before. | Tracks whether a node belongs to the current path. |
| Prevents repeated traversal. | Helps identify a cycle. |
| Remains true after traversal. | Reset after each traversal. |
Consider:
Traversal 1: 0 → 1 → 2 → -1
Traversal 2: 3 → 2Node 2 was visited in the first traversal.
When traversal 2 reaches node 2:
visited[2] = true
pathIndex[2] = -1This is not a cycle because node 2 does not belong to the current traversal path.
Remember: Visiting an already visited node does not always mean a cycle exists. It must belong to the current path.
10. Complexity Analysis
| Complexity | Value | Explanation |
|---|---|---|
| Time Complexity | O(n) | Every node is visited at most once. |
| Auxiliary Space | O(n) | Visited array, path index array and traversal list. |
Why is the time complexity O(n)?
Suppose there are 100,000 nodes.
- Every node is processed at most once.
- Every node is added to a path at most once.
- Every path is reset only for its own nodes.
- We don't repeat graph traversal.
Therefore, total time complexity is O(n).
Final Summary
Largest Sum Cycle – Key Points
- Algorithm: Graph traversal with cycle detection.
visited[]: Tracks previously visited nodes.pathIndex[]: Identifies nodes in the current path.path: Stores the current traversal.maxSum: Stores the maximum cycle sum.- Time: O(n).
- Space: O(n).


Join the conversation! Your thoughts help the community grow.