Imagine you are managing a network of servers and want to know how long it takes for a signal to reach all servers starting from one source server.
You are given a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from u to v. There are n nodes labeled from 1 to n. Starting from node k, return the time it takes for all nodes to receive the signal. If it is impossible for all nodes to receive the signal, return -1.
1 ≤ n ≤ 10^51 ≤ times.length ≤ 10^5times[i].length == 31 ≤ u, v ≤ n1 ≤ w ≤ 100All edges are directed
Edge cases: No edges in times → output -1 (nodes unreachable)Single node network (n=1) → output 0 (signal already at node)Graph with cycles → algorithm must avoid infinite loops
</>
IDE
def network_delay_time(times: list[list[int]], n: int, k: int) -> int:public int networkDelayTime(int[][] times, int n, int k)int networkDelayTime(vector<vector<int>>& times, int n, int k)function networkDelayTime(times, n, k)
def network_delay_time(times, n, k):
# Write your solution here
pass
class Solution {
public int networkDelayTime(int[][] times, int n, int k) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
// Write your solution here
return 0;
}
function networkDelayTime(times, n, k) {
// Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: -1 when nodes are reachableIncorrectly marking reachable nodes as unreachable due to wrong distance initialization or update.✅ Initialize distances properly and update only when shorter path found; check max distance after processing.
Wrong: Too large value (e.g., 10 instead of 2)Greedy approach picking first edge without exploring all paths.✅ Implement full Dijkstra with priority queue and relax edges properly.
Wrong: 0 or wrong value for single nodeNot handling single node base case correctly.✅ Return 0 immediately if n=1.
Wrong: Infinite loop or stack overflowNot handling cycles properly in DFS or recursion.✅ Use priority queue and distance checks to avoid revisiting nodes unnecessarily.
Wrong: Timeout on large inputUsing brute force DFS or Bellman-Ford instead of efficient Dijkstra.✅ Use min-heap priority queue to achieve O(E log N) complexity.
✓
Test Cases
Focus on handling graphs with no edges and single node cases correctly.
Beware of greedy approaches and off-by-one errors in indexing.
Optimize your solution using a priority queue to handle large inputs efficiently.
Starting at node 2, signal reaches node 1 and 3 in 1 unit time, then node 4 in 2 units time.
💡 Think about shortest path from the start node to all others.
💡 Use Dijkstra's algorithm with a priority queue to find minimum travel times.
💡 Track the maximum shortest distance to any node; that is the answer.
Why it failed: Incorrect output means shortest path calculation is wrong; ensure you update distances only if new path is shorter and use a min-heap or priority queue.
✓ Correctly computed shortest paths and maximum delay.
Graph has a cycle 1->2->3->1; shortest times are 0,1,2 respectively; algorithm must avoid infinite loops.
💡 Check how your algorithm handles cycles in the graph.
💡 Use a priority queue and update distances only if shorter to avoid infinite loops.
💡 Do not revisit nodes if no shorter path is found.
Why it failed: Infinite recursion or wrong output means cycles not handled; fix by using a priority queue and distance checks to prevent revisiting longer paths.
✓ Correctly handles cycles without infinite loops.
Off-by-one errors in indexing or distance updates can cause wrong max delay; correct max delay is sum of weights along path.
💡 Check indexing carefully when updating distances.
💡 Ensure distances array is 1-based or properly aligned with node labels.
💡 Max delay is max distance among all nodes reachable from k.
Why it failed: Output less than 15 means off-by-one or incorrect max distance calculation; fix indexing and max distance logic.
✓ Correctly computes max delay with proper indexing.
t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
Expectednull
⏱ Performance - must finish in 2000ms
Test with n=100000 nodes and up to 100000 edges; O(E log N) Dijkstra must complete within 2 seconds.
💡 Use a priority queue (min-heap) to achieve O(E log N) complexity.
💡 Avoid repeated unnecessary relaxations and use adjacency list.
💡 Brute force DFS or Bellman-Ford will time out on this input.
Why it failed: TLE indicates algorithm is not O(E log N); fix by implementing Dijkstra with min-heap priority queue.
✓ Algorithm runs within time limit using efficient Dijkstra implementation.
Practice
(1/5)
1. You are given a list of courses and their prerequisite pairs. You need to determine if it is possible to finish all courses without running into a circular dependency. Which algorithmic approach guarantees an optimal solution to detect such cycles in the course dependency graph?
easy
A. Perform a topological sort using Kahn's Algorithm (BFS) to detect cycles by checking if all nodes can be processed.
B. Use a brute force approach that tries all possible course orders to find a valid sequence.
C. Apply dynamic programming to count the number of ways to complete courses without cycles.
D. Use a greedy algorithm that always picks the course with the fewest prerequisites first.
Solution
Step 1: Understand the problem as cycle detection in a directed graph
The problem requires detecting if a cycle exists in the course prerequisite graph, which invalidates any course order.
Step 2: Identify the algorithm that detects cycles efficiently
Kahn's Algorithm performs a topological sort using BFS and in-degree counts. If all nodes are processed, no cycle exists; otherwise, a cycle is detected.
Final Answer:
Option A -> Option A
Quick Check:
Topological sort with BFS is the standard cycle detection method for this problem [OK]
Hint: Topological sort detects cycles by processing all nodes [OK]
Common Mistakes:
Greedy approach fails on complex dependencies
Dynamic programming is not suited for cycle detection
Brute force is inefficient and impractical
2. Consider the following code snippet that finds the smallest set of vertices to reach all nodes in a DAG. Given n = 4 and edges = [[0,1],[1,2],[2,3]], what is the final returned list?
easy
A. [0]
B. [3]
C. [0, 1]
D. [1]
Solution
Step 1: Initialize in-degree and queue
Nodes: 0,1,2,3; in-degree: [0,1,1,1]. Only node 0 has zero in-degree, so queue = [0], result = [0].
Step 2: Process queue
Pop 0, decrement in-degree of 1 to 0, enqueue 1. Pop 1, decrement in-degree of 2 to 0, enqueue 2. Pop 2, decrement in-degree of 3 to 0, enqueue 3. Pop 3, no neighbors.
Final Answer:
Option A -> Option A
Quick Check:
Only node 0 has zero in-degree initially, so result is [0] [OK]
Hint: Only nodes with zero in-degree initially are in the result [OK]
Common Mistakes:
Returning nodes that become zero in-degree later
Returning all nodes visited in BFS
Confusing final queue state with result
3. What is the time complexity of the optimal Kahn's Algorithm solution for the Course Schedule problem, given V courses and E prerequisite pairs?
medium
A. O(V + E) because each node and edge is processed once in BFS
B. O(V * E) due to nested loops over nodes and edges
C. O(V^2) because each node might be checked against all others
D. O(E) only, since edges dominate the processing time
Solution
Step 1: Identify operations on nodes and edges
Each node is enqueued and dequeued once; each edge is visited once when decrementing in-degree.
Step 2: Combine to get total complexity
Total time is proportional to number of nodes plus number of edges -> O(V + E).
Final Answer:
Option A -> Option A
Quick Check:
Standard BFS topological sort runs in linear time relative to graph size [OK]
Hint: Each edge and node processed once -> O(V + E) [OK]
Common Mistakes:
Assuming nested loops cause O(V*E)
Confusing dense graph worst case with typical complexity
Ignoring that BFS processes nodes once
4. What is the time complexity of the Union-Find based algorithm to check if a graph with V vertices and E edges is bipartite?
medium
A. O(V^2) because each union operation can take linear time
B. O(V + E log V) due to sorting edges before union
C. O((V + E) α(V)) where α is the inverse Ackermann function
D. O(V + E) because union-find operations are constant time
Solution
Step 1: Identify number of union-find operations
Each edge triggers at most one union operation, so total operations are O(E).
Step 2: Analyze union-find operation complexity
Union-Find with path compression and union by rank has amortized time O(α(V)) per operation, where α is inverse Ackermann function.
Final Answer:
Option C -> Option C
Quick Check:
Union-Find complexity is near-linear, not quadratic or logarithmic [OK]
Hint: Union-Find operations are almost constant time amortized [OK]
Common Mistakes:
Assuming union is linear time
Confusing sorting necessity
Ignoring inverse Ackermann function
5. Suppose the problem is modified so that islands can be connected diagonally as well (8-direction connectivity). Which of the following changes to the DFS approach correctly counts islands under this new rule?
hard
A. Add diagonal neighbors (r+1,c+1), (r+1,c-1), (r-1,c+1), (r-1,c-1) to the DFS calls in addition to the four cardinal directions.
B. Keep the DFS calls unchanged but count diagonally adjacent '1's separately after DFS completes.
C. Use BFS instead of DFS without changing neighbor directions, as BFS handles diagonal connectivity automatically.
D. Modify the grid to mark diagonal neighbors as '1' before running the original DFS.
Solution
Step 1: Understand the new connectivity rule
Islands now connect horizontally, vertically, and diagonally, so DFS must explore all 8 neighbors.
Step 2: Modify DFS to include diagonal neighbors
Add recursive DFS calls for (r+1,c+1), (r+1,c-1), (r-1,c+1), and (r-1,c-1) along with the original four directions.
Final Answer:
Option A -> Option A
Quick Check:
Only adding diagonal neighbors to DFS ensures correct island counting with 8-direction connectivity [OK]
Hint: Add diagonal neighbors to DFS for 8-direction connectivity [OK]
Common Mistakes:
Assuming BFS handles diagonals without code change
Counting diagonals separately after DFS
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.