Swim in Rising Water
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Binary Search.
Swim in Rising Water
On an grid, elevation at
(i, j) is grid[i][j]. Return the least time such that you can swim from top-left to bottom-right.Examples
Input: grid = [[0,2],[1,3]]
Output: 3
Approach 1
Level I: Dijkstra (Min-Max Path)
Intuition
This is a variant of shortest path where the 'cost' of a path is elevations on path. Dijkstra's algorithm with a min-priority queue works perfectly.
⏱ $O(N^2 \\log N)$💾 $O(N^2)$
Detailed Dry Run
grid = [[0,2],[1,3]].
- Start (0,0) elev 0.
- Neighbors: (0,1) cost 2, (1,0) cost 1.
- Smallest max: (1,0) cost 1.
- Neighbor of (1,0) is (1,1) cost 3.
- Result: 3.
Approach 2
Level II: Optimal (Union Find / Kruskal's)
Intuition
Treat the grid as a graph where each edge has a weight equal to the maximum elevation of its two endpoints. Sort all possible edge weights (or cell elevations). Add cells one by one in increasing order of elevation and connect them with their visited neighbors. The first time the top-left and bottom-right are in the same component, the current elevation is the answer.
⏱ $O(N^2 \\log N^2)$💾 $O(N^2)$
Detailed Dry Run
grid = [[0,2],[1,3]].
- Cells sorted by elevation: (0,0):0, (1,0):1, (0,1):2, (1,1):3.
- Add (0,0). Add (1,0), connect to (0,0).
- Add (0,1), connect to (0,0).
- Add (1,1), connect to (1,0) and (0,1).
- (0,0) and (1,1) are connected. Result: 3.
Approach 3
Level III: Optimal (Binary Search + DFS/BFS)
Intuition
The answer lies in . For a fixed , we check if a path exists using only squares with elevation using BFS/DFS.
⏱ $O(N^2 \\cdot \\log(N^2))$💾 $O(N^2)$
Detailed Dry Run
grid = [[0,2],[1,3]]. BS on range [0, 3].
Try T=2: Path (0,0)->(1,0) works, but (1,0) neighbors are (1,1) elev 3 > 2. Fails.
Try T=3: Path (0,0)->(1,0)->(1,1) works! Possible.
Result: 3.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.