Path With Minimum Effort

medium

Given an R × C grid heights, travel from the top-left (0,0) to the bottom-right (R-1, C-1) moving 4-directionally. A route's effort is the maximum absolute height difference between consecutive cells. Return the minimum effort. (This is the same minimax path as minimum effort, approached here with union-find.)

Hints

Think of adjacent cells as edges weighted by their height difference.
Add edges cheapest-first (union-find) until the two corners connect.
The weight of the connecting edge is the minimum effort.

Common doubts

Adding edges in increasing weight, the corners join exactly when the cheapest bottleneck route becomes possible; that last edge is its largest step.
The minimax path between two nodes uses only MST edges, and its bottleneck is the heaviest MST edge on the path between them.
Both are O(RC log RC). Union-find (Kruskal) is elegant when you think in edges; Dijkstra-with-max is a direct grid traversal.

Interview follow-ups

Track parents during Dijkstra, or reconstruct through the union-find/MST structure.
Seed Dijkstra from all sources, or in Kruskal stop when any source–target pair connects.

Fun facts

  • LeetCode 1631 — the same problem as minimum effort, here through union-find eyes.
  • The bottleneck shortest path is a textbook application of Kruskal's algorithm.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
The two corners connect once weight-2 edges are added.
Example 2
Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
A route exists whose largest step is 1.
Constraints

- 1 <= R, C <= 100 - 1 <= heights[r][c] <= 10^6

Solve this problem →