Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #778: Swim in Rising Water

In this guide, we solve Leetcode #778 Swim in Rising Water in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). It starts raining, and water gradually rises over time.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Union Find, Array, Binary Search, Matrix, Heap (Priority Queue)

Intuition

The problem structure suggests a monotonic decision, which makes binary search a natural fit.

By halving the search space each step, we reach the answer efficiently.

Approach

Search either directly on a sorted array or on the answer space using a check function.

Each check is fast, and the logarithmic search keeps the overall runtime low.

Steps:

  • Define the search bounds.
  • Check the mid point condition.
  • Narrow the bounds until convergence.

Example

Input: grid = [[0,2],[1,3]] Output: 3 Explanation: At time 0, you are in grid location (0, 0). You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0. You cannot reach point (1, 1) until time 3. When the depth of water is 3, we can swim anywhere inside the grid.

Python Solution

class Solution: def swimInWater(self, grid: List[List[int]]) -> int: def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] n = len(grid) m = n * n p = list(range(m)) hi = [0] * m for i, row in enumerate(grid): for j, h in enumerate(row): hi[h] = i * n + j dirs = (-1, 0, 1, 0, -1) for t in range(m): x, y = divmod(hi[t], n) for dx, dy in pairwise(dirs): nx, ny = x + dx, y + dy if 0 <= nx < n and 0 <= ny < n and grid[nx][ny] <= t: p[find(x * n + y)] = find(nx * n + ny) if find(0) == find(m - 1): return t return 0

Complexity

The time complexity is O(n2×log⁡n)O(n^2 \times \log n)O(n2×logn) and the space complexity is O(n2)O(n^2)O(n2), where nnn is the side length of the matrix. The space complexity is O(n2)O(n^2)O(n2), where nnn is the side length of the matrix.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy