Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an n × n grid where grid[r][c] is the height of that cell. The heights are all different and are exactly the numbers 0 to n² − 1. It starts raining, and at time t the water is at height t everywhere. You can swim from a cell to one of its 4 neighbours if both cells have height ≤ t, and swimming takes no time. Starting at (0, 0), return the smallest t at which you can reach (n − 1, n − 1). n is at most 50.
Example: [[0,2],[1,3]] → 3. You can't stand on the bottom-right cell until the water reaches 3, and by then everything is connected.
Start with brute force
For a fixed t, the question "can I get across?" is just a BFS over cells with height ≤ t. So try t = 0, 1, 2, … and BFS each time. That's up to n² BFS runs of n² cells each: O(n⁴), about 6 million steps for n = 50. That's fine here, but it's the slow idea.
The answer is monotone: if you can cross at t, you can cross at any later time. So you can binary search on t instead. That's O(n² log n²), and it's a perfectly good interview answer (it's why the problem is tagged Binary Search). Another option is a Dijkstra-style min-heap that always expands the lowest reachable cell, which is O(n² log n).
Building the intuition
Look at what changes as time goes from t − 1 to t. Every cell's flooded status stays the same, except one cell: the one whose height is exactly t. The heights are a permutation, so there's exactly one.
Binary search and the brute force both throw away everything they learned and BFS from scratch. Instead, picture the flooded cells as islands of water that grow:
- At time
t, the cell with heighttfloods. - It joins any flooded neighbour's region. Two separate regions might merge right here.
- The moment
(0, 0)and(n − 1, n − 1)are in the same region, you can swim across, so thattis the answer.
"Regions that only ever merge, and I keep asking whether two cells are in the same one" is exactly what Union-Find is built for. Each cell (r, c) becomes node r · n + c.
Because the heights are 0..n² − 1, you don't even need to sort the cells. Build cellAt[h], the cell whose height is h, in one pass.
The optimal approach
- Build
cellAt: for every cell,cellAt[grid[r][c]] = r · n + c. - Make a DSU with
n²nodes. - For
t = 0, 1, …, n² − 1:- let
(r, c)be the cell atcellAt[t]; - for each of its 4 neighbours inside the grid with height
≤ t(already flooded), union the two cells; - if
find(0) == find(n² − 1), returnt.
- let
The subtle detail is the condition grid[nr][nc] <= t. A neighbour with a smaller height flooded at an earlier time, so it's already in some region. One with a bigger height isn't under water yet, so don't connect to it, even though it's adjacent.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class DSU:
def __init__(self, n: int):
self.parent = list(range(n)) # every node starts as its own root
self.size = [1] * n
def find(self, x: int) -> int:
root = x
while self.parent[root] != root:
root = self.parent[root]
# path compression: point every node we walked past straight at the root
while x != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same group
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra # union by size: hang the smaller tree under the bigger
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return True
class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid)
# heights are a permutation of 0..n*n-1, so we can find "the cell of height t" directly
cell_at = [0] * (n * n)
for r in range(n):
for c in range(n):
cell_at[grid[r][c]] = r * n + c
dsu = DSU(n * n) # cell (r, c) is node r * n + c
for t in range(n * n):
# at time t exactly one new cell goes underwater: join it to flooded neighbours
r, c = divmod(cell_at[t], n)
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] <= t:
dsu.union(r * n + c, nr * n + nc)
if dsu.find(0) == dsu.find(n * n - 1):
return t # the first moment start and end share a flooded region
return n * n - 1 # unreachable: by the last time every cell is floodedclass DSU {
public:
vector<int> parent, sz;
DSU(int n) : parent(n), sz(n, 1) {
iota(parent.begin(), parent.end(), 0); // every node starts as its own root
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
// "union" is a C++ keyword, so this one is called unite
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (sz[ra] < sz[rb]) swap(ra, rb); // union by size: smaller tree under the bigger
parent[rb] = ra;
sz[ra] += sz[rb];
return true;
}
};
class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size();
// heights are a permutation of 0..n*n-1, so we can find "the cell of height t" directly
vector<int> cellAt(n * n);
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) cellAt[grid[r][c]] = r * n + c;
DSU dsu(n * n); // cell (r, c) is node r * n + c
int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
for (int t = 0; t < n * n; t++) {
// at time t exactly one new cell goes underwater: join it to flooded neighbours
int r = cellAt[t] / n, c = cellAt[t] % n;
for (int d = 0; d < 4; d++) {
int nr = r + dr[d], nc = c + dc[d];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] <= t) {
dsu.unite(r * n + c, nr * n + nc);
}
}
if (dsu.find(0) == dsu.find(n * n - 1)) return t; // first moment they meet
}
return n * n - 1; // unreachable: by the last time every cell is flooded
}
};class DSU {
int[] parent, size;
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every node starts as its own root
size[i] = 1;
}
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (size[ra] < size[rb]) { // union by size: smaller tree under the bigger
int t = ra; ra = rb; rb = t;
}
parent[rb] = ra;
size[ra] += size[rb];
return true;
}
}
class Solution {
public int swimInWater(int[][] grid) {
int n = grid.length;
// heights are a permutation of 0..n*n-1, so we can find "the cell of height t" directly
int[] cellAt = new int[n * n];
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++) cellAt[grid[r][c]] = r * n + c;
DSU dsu = new DSU(n * n); // cell (r, c) is node r * n + c
int[] dr = { 1, -1, 0, 0 }, dc = { 0, 0, 1, -1 };
for (int t = 0; t < n * n; t++) {
// at time t exactly one new cell goes underwater: join it to flooded neighbours
int r = cellAt[t] / n, c = cellAt[t] % n;
for (int d = 0; d < 4; d++) {
int nr = r + dr[d], nc = c + dc[d];
if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] <= t) {
dsu.union(r * n + c, nr * n + nc);
}
}
if (dsu.find(0) == dsu.find(n * n - 1)) return t; // first moment they meet
}
return n * n - 1; // unreachable: by the last time every cell is flooded
}
}class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i); // every node starts as its own root
this.size = new Array(n).fill(1);
}
find(x) {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
// path compression: point every node we walked past straight at the root
while (x !== root) {
const nxt = this.parent[x];
this.parent[x] = root;
x = nxt;
}
return root;
}
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same group
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra]; // union by size
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
return true;
}
}
/**
* @param {number[][]} grid
* @return {number}
*/
var swimInWater = function (grid) {
const n = grid.length;
// heights are a permutation of 0..n*n-1, so we can find "the cell of height t" directly
const cellAt = new Array(n * n);
for (let r = 0; r < n; r++)
for (let c = 0; c < n; c++) cellAt[grid[r][c]] = r * n + c;
const dsu = new DSU(n * n); // cell (r, c) is node r * n + c
const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
for (let t = 0; t < n * n; t++) {
// at time t exactly one new cell goes underwater: join it to flooded neighbours
const r = Math.floor(cellAt[t] / n), c = cellAt[t] % n;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] <= t) {
dsu.union(r * n + c, nr * n + nc);
}
}
if (dsu.find(0) === dsu.find(n * n - 1)) return t; // first moment they meet
}
return n * n - 1; // unreachable: by the last time every cell is flooded
};Dry run
grid = [[0,2],[1,3]], so the cell numbers are (0,0) = 0, (0,1) = 1, (1,0) = 2, (1,1) = 3.
| t | Floods | Flooded neighbours | Unions | Start and end joined? |
|---|---|---|---|---|
| 0 | (0,0) | none (heights 1 and 2) | none | no |
| 1 | (1,0) | (0,0) | 2 ∪ 0 | no |
| 2 | (0,1) | (0,0) | 1 ∪ 0 | no |
| 3 | (1,1) | (0,1), (1,0) | 3 ∪ 1, 3 ∪ 2 | yes → return 3 |
Complexity
- Time: O(n² · α(n²)). Each of the n² cells floods once, with up to 4 unions and 2 finds, each effectively O(1). Building
cellAtis O(n²). - Space: O(n²) for
cellAtand the DSU arrays.
Edge cases and traps
n = 1. Att = 0the start is the end, sofind(0) == find(0)and the answer is0.- Forgetting the start cell's own height. You can't leave
(0, 0)untilt ≥ grid[0][0]. The union method handles it automatically, because cell 0 only joins anything once it floods. - Connecting to neighbours that aren't flooded. Check
grid[nr][nc] <= t, not just whether the neighbour is in bounds. - Treating it as a sum of heights. The cost of a path is its highest cell, not the total. That's why plain shortest-path sums don't apply.
Say it in the interview
"At time t I can use every cell with height at most t, and the answer is the earliest t that connects the corners. Instead of re-running a BFS for each t, I raise the water one step at a time. The heights are a permutation of 0 to n² − 1, so exactly one cell floods at each t, and I can find it with a lookup array. I union it with its already-flooded neighbours and stop the first time the two corners share a root. O(n² · α) time, O(n²) space. Binary search plus BFS, or a min-heap Dijkstra on the max height, would also work in O(n² log n)."
Follow-ups interviewers ask
- "What if heights could repeat or be huge?" Sort the cells by height, which makes it O(n² log n), and flood in that order. Or use the min-heap version: always expand the lowest reachable cell, and track the highest height you've popped.
- "Explain the heap version." It's Dijkstra where a path's cost is its maximum height instead of a sum. Pop the cell with the smallest cost, and push neighbours with cost
max(current, height). - "Where else does this 'merge as you sweep' idea show up?" In Kruskal's MST (add edges cheapest first) and in counting islands as land is added one cell at a time (Number of Islands II).
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free