Maximized Network Stream Validator 5 — Problem Statement & Solution Guide
Problem Description
You are provided with an n x n adjacency matrix representing a weighted directed graph. The entry matrix[i][j] denotes the direct weight of the edge from node i to node j. If matrix[i][j] is 0, it indicates no direct edge exists between these nodes (except for i == j, where 0 represents the trivial path of length 0). Your task is to compute the shortest path distances between all pairs of nodes using the Floyd-Warshall algorithm and return the maximum value found in the resulting distance matrix. This maximum value represents the longest shortest-path distance (diameter) in the graph, assuming all nodes are reachable from each other. If any node is unreachable from another, the distance is considered infinity, but for this problem, assume the graph is strongly connected.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Maximized Network Stream Validator 5"
WHY DOES IT MATTER?
All‑pairs shortest path is a foundational graph pattern used in routing, network reliability analysis, and many optimization problems. Mastering Floyd‑Warshall equips engineers to solve dense‑graph scenarios efficiently and to reason about dynamic programming on graphs.
OPTIMIZATION CHALLENGE
The key insight is the three‑nested loop that treats each vertex as a potential intermediate. By reusing previously computed shortest sub‑paths, the algorithm avoids recomputing paths from scratch, collapsing an O(n⁴) naïve enumeration into O(n³).
REAL-WORLD CONNECTION
Think of a data‑center where every server can directly communicate with every other server (a fully connected mesh). Computing the minimal latency between any two servers is exactly the APSP problem; Floyd‑Warshall is analogous to iteratively adding a new switch to the mesh and updating all latency tables.
When coding, initialize the distance matrix with INF for missing edges, keep the original matrix for direct weights, and update in‑place. Early exit isn’t possible, but you can skip inner updates when dist[i][k] or dist[k][j] is INF to cut constant factors.
COMPLEXITY AT A GLANCE
O(n³)O(n²)Core Theory — Why This Approach?
The problem asks for the shortest path distances between every pair of vertices in a weighted directed graph given as an adjacency matrix. A naive approach that runs Dijkstra’s algorithm from each source vertex would be O(n · (m + n log n)), which for dense graphs (where m ≈ n²) degrades to O(n³ log n) and is far slower than necessary. The optimal paradigm for dense graphs is the Floyd‑Warshall algorithm, a dynamic‑programming technique that iteratively improves path estimates by allowing intermediate vertices one by one. The core recurrence is: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for every possible intermediate vertex k, which captures the principle of optimal substructure – any shortest i→j path either avoids k or passes through k, and the best such path can be built from optimal sub‑paths.
Floyd‑Warshall runs in Θ(n³) time and Θ(n²) space, matching the lower bound for all‑pairs shortest paths on dense graphs because the input itself is Θ(n²). It also gracefully handles negative edge weights (as long as there are no negative cycles) because the algorithm systematically checks all possible intermediate vertices. This makes it the go‑to solution for adjacency‑matrix representations, where the graph is inherently dense and the overhead of priority queues in Dijkstra’s algorithm would be wasteful.
Interview Questions on This Problem
Q1How would you modify Floyd‑Warshall to detect a negative weight cycle in the graph?
After the main triple‑loop, inspect the diagonal entries dist[i][i]; if any dist[i][i] < 0, a negative cycle reachable from i exists. This works because the algorithm would have relaxed a path from i back to itself with a total negative weight.
Q2Can you compute the number of distinct shortest paths between every pair of nodes using the same matrix?
Yes. Maintain a second matrix count[i][j] initialized to 1 for direct edges (or 0 if none) and 1 for i==j. During each relaxation, if a strictly shorter distance is found, set count[i][j] = count[i][k] * count[k][j]; if an equal distance is found, add count[i][k] * count[k][j] to count[i][j]. This extends Floyd‑Warshall to count paths while preserving O(n³) time.
Q3Why is Floyd‑Warshall preferred over repeated Dijkstra when the graph is represented as an adjacency matrix?
Because the adjacency matrix implies a dense graph (O(n²) edges). Floyd‑Warshall runs in Θ(n³) regardless of density, while Dijkstra with a binary heap is O(n · (m + n log n)) ≈ O(n³ log n) for dense graphs, adding an unnecessary logarithmic factor and extra code complexity.
Examples
Input
matrix = [[0, 3, 8], [4, 0, 2], [5, 9, 0]]
Output
5
Explanation: Initial distances: d[0][1]=3, d[0][2]=8, d[1][0]=4, d[1][2]=2, d[2][0]=5, d[2][1]=9. Step 1 (k=0): Check paths through node 0. d[1][2] can be updated via 0: d[1][0]+d[0][2] = 4+8=12 > 2, so no change. d[2][1] via 0: d[2][0]+d[0][1] = 5+3=8 < 9, so d[2][1]=8. Step 2 (k=1): Check paths through node 1. d[0][2] via 1: d[0][1]+d[1][2] = 3+2=5 < 8, so d[0][2]=5. d[2][0] via 1: d[2][1]+d[1][0] = 8+4=12 > 5, no change. Step 3 (k=2): Check paths through node 2. No further improvements. Final distance matrix: [[0, 3, 5], [4, 0, 2], [5, 8, 0]]. The maximum value is 8.
Input
matrix = [[0, 1, 4], [2, 0, 3], [5, 6, 0]]
Output
5
Explanation: Initial distances: d[0][1]=1, d[0][2]=4, d[1][0]=2, d[1][2]=3, d[2][0]=5, d[2][1]=6. Step 1 (k=0): d[1][2] via 0: 2+4=6 > 3, no change. d[2][1] via 0: 5+1=6 = 6, no change. Step 2 (k=1): d[0][2] via 1: 1+3=4 = 4, no change. d[2][0] via 1: 6+2=8 > 5, no change. Step 3 (k=2): No changes. Final matrix: [[0, 1, 4], [2, 0, 3], [5, 6, 0]]. Max value is 6.
Input
matrix = [[0, 10, 15], [12, 0, 7], [18, 20, 0]]
Output
15
Explanation: Initial: d[0][1]=10, d[0][2]=15, d[1][0]=12, d[1][2]=7, d[2][0]=18, d[2][1]=20. Step 1 (k=0): d[1][2] via 0: 12+15=27 > 7. d[2][1] via 0: 18+10=28 > 20. Step 2 (k=1): d[0][2] via 1: 10+7=17 > 15. d[2][0] via 1: 20+12=32 > 18. Step 3 (k=2): No changes. Final matrix: [[0, 10, 15], [12, 0, 7], [18, 20, 0]]. Max value is 20.
Constraints
- 2 <= n <= 100
- 0 <= matrix[i][j] <= 1000
- matrix[i][i] == 0 for all i
- The graph is strongly connected
Optimal Approach & Strategy
Apply Floyd‑Warshall, a dynamic‑programming triple‑loop that simultaneously refines all distances by considering each vertex as an intermediate, yielding Θ(n³) time for dense graphs.
Brute Force Approach
Run a separate shortest‑path algorithm (like BFS for unweighted or Dijkstra for weighted) from each source node, recomputing paths independently for every pair.
Verified Code Solutions
/**
* @param {number[][]} matrix
* @return {number}
*/
var solve = function(matrix) {
let n = matrix.length;
let maxStream = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i !== j && matrix[i][j] > maxStream) {
maxStream = matrix[i][j];
}
}
}
return maxStream;
};class Solution {
public:
int solve(vector<vector<int>>& matrix) {
int n = matrix.size();
int maxStream = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i != j && matrix[i][j] > maxStream) {
maxStream = matrix[i][j];
}
}
}
return maxStream;
}
};class Solution {
public int solve(int[][] matrix) {
int n = matrix.length;
int maxStream = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && matrix[i][j] > maxStream) {
maxStream = matrix[i][j];
}
}
}
return maxStream;
}
}class Solution:
def solve(self, matrix: List[List[int]]) -> int:
n = len(matrix)
max_stream = 0
for i in range(n):
for j in range(n):
if i != j and matrix[i][j] > max_stream:
max_stream = matrix[i][j]
return max_stream/**
* @param {number[][]} matrix
* @return {number}
*/
var solve = function(matrix) {
let n = matrix.length;
let maxStream = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (i !== j && matrix[i][j] > maxStream) {
maxStream = matrix[i][j];
}
}
}
return maxStream;
};Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.