hardGraphsBinary SearchBinary Search

Swim in Rising Water

hardTime: O(n^2 log n)Space: O(n^2)

Signals to notice

minimum time to reach bottom-rightgrid with elevationbinary search on time + BFS

Brute force first

Try all paths and find the minimum maximum elevation — exponential path enumeration. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Binary search on the answer (time t): for each candidate t, check if you can reach (n-1,n-1) using only cells with elevation ≤ t (BFS/DFS). The minimum t where a path exists is the answer. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

If you can swim at time t (all cells ≤ t are passable), you can also swim at time t+1. This monotonicity makes binary search valid. The feasibility check is a simple grid BFS. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Using Dijkstra when binary search + BFS is simpler. Both work, but binary search on the answer with a BFS check is easier to implement and reason about. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Binary Search Pattern