Bird
Raised Fist0
Interview Prepunion-findhardGoogleAmazon

Swim in Rising Water

Choose your preparation mode4 modes available
📋
Problem

Imagine you are trapped in a flooded grid where water levels rise over time, and you need to find the earliest time you can swim from the top-left to the bottom-right cell.

You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j). Initially, the water level is at 0 and rises by 1 unit per time step. You can swim from a cell to any adjacent cell (up, down, left, right) if and only if the water level is at least the elevation of both cells. Return the minimum time required to reach the bottom-right cell (n-1, n-1) starting from the top-left cell (0, 0).

1 ≤ n ≤ 500 ≤ grid[i][j] < n*nAll grid[i][j] are unique
Edge cases: n = 1 → output is grid[0][0]Grid with strictly increasing elevations along the path → output equals max elevation on pathGrid where start or end cell has very high elevation → output equals that elevation
</>
IDE
def swimInWater(grid: List[List[int]]) -> int:public int swimInWater(int[][] grid)int swimInWater(vector<vector<int>>& grid)function swimInWater(grid)
def swimInWater(grid):
    # Write your solution here
    pass
class Solution {
    public int swimInWater(int[][] grid) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int swimInWater(vector<vector<int>>& grid) {
    // Write your solution here
    return 0;
}
function swimInWater(grid) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Less than actual minimum timeGreedy approach picking lowest elevation neighbors without checking full connectivity.✅ Use union-find or binary search with connectivity checks instead of greedy local decisions.
Wrong: Output equals elevation of start cell even when path blockedNot checking if path to end cell is actually reachable at that water level.✅ Check connectivity between start and end cells at each water level increment.
Wrong: Fails single cell grid or returns incorrect valueNo base case for n=1 grid.✅ Add base case to return grid[0][0] when n=1.
Wrong: Fails exact boundary elevation checksUsing < instead of <= when comparing cell elevation to water level.✅ Use <= comparison to include cells with elevation equal to current water level.
Wrong: TLE on large inputsBrute force DFS for each time increment instead of union-find or binary search.✅ Implement union-find with sorting and path compression for O(n^2 log n) solution.
✓
Test Cases
t1_01basic
Input{"grid":[[0,2],[1,3]]}
Expected3

At time 3, water level is 3, allowing movement from (0,0) to (1,1) through (1,0).

t1_02basic
Input{"grid":[[0,1,2],[5,4,3],[6,7,8]]}
Expected5

Minimum time is 5 because path must cross elevation 5 at (1,0) to reach bottom-right.

t2_01edge
Input{"grid":[[0]]}
Expected0

Single cell grid; start is end; minimum time is elevation at (0,0).

t2_02edge
Input{"grid":[[0,1],[2,3]]}
Expected3

Path requires waiting until water level 3 to reach bottom-right cell.

t2_03edge
Input{"grid":[[0,0],[0,0]]}
Expected0

All cells have identical elevation 0; path is immediately available.

t3_01corner
Input{"grid":[[0,100,1],[2,3,4],[5,6,7]]}
Expected7

Greedy approach picking lowest elevation neighbors first fails; must consider union-find connectivity over time.

t3_02corner
Input{"grid":[[0,1,2],[3,4,5],[6,7,8]]}
Expected8

Confusing 0/1 knapsack analogy: must not reuse cells multiple times; path must be continuous and respects water level.

t3_03corner
Input{"grid":[[0,2,3],[1,100,4],[5,6,7]]}
Expected7

High elevation cell blocks direct path; algorithm must find detour around it.

t4_01performance
Input{"_description":"n=50 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

n=50 grid with unique elevations; O(n^2 log n) union-find approach must complete within 2 seconds.

Practice

(1/5)
1. You are given n computers and a list of connections where each connection connects two computers. You want to connect all computers with the minimum number of operations, where each operation can rewire an existing connection. Which algorithmic approach guarantees the optimal solution to determine the minimum operations needed or if it's impossible?
easy
A. Dynamic Programming to find the minimum spanning tree cost
B. Greedy approach that connects the most connected computers first
C. Union-Find (Disjoint Set Union) to count connected components and check redundant connections
D. Depth-First Search to find the longest path and rewire connections accordingly

Solution

  1. Step 1: Understand problem requirements

    The problem requires connecting all computers with minimum operations by rewiring existing connections. This involves grouping nodes into connected components and counting redundant edges.
  2. Step 2: Identify suitable algorithm

    Union-Find efficiently tracks connected components and redundant edges, enabling quick checks if the network can be connected and how many operations are needed.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Union-Find is the standard approach for connectivity and component counting [OK]
Hint: Union-Find tracks components and redundant edges efficiently [OK]
Common Mistakes:
  • Thinking greedy or DFS alone can guarantee minimal rewiring
  • Confusing MST with this problem
  • Assuming DP applies directly
2. You are given a list of edges representing an undirected graph with n nodes. The graph started as a tree with n nodes and one additional edge was added, creating a cycle. Which algorithmic approach guarantees finding the edge that creates the cycle efficiently?
easy
A. Union-Find (Disjoint Set Union) with path compression and union by rank to detect cycles during edge insertion
B. Dynamic programming to store reachable nodes and detect cycles
C. Depth-first search (DFS) cycle detection on each edge, checking connectivity repeatedly
D. Greedy algorithm that removes edges with the highest node degree first

Solution

  1. Step 1: Understand problem constraints

    The graph is initially a tree with n nodes, so it has exactly n-1 edges. Adding one edge creates exactly one cycle.
  2. Step 2: Identify suitable algorithm

    Union-Find efficiently tracks connected components and detects if adding an edge connects two nodes already in the same component, indicating a cycle.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Union-Find detects cycles in near-linear time [OK]
Hint: Union-Find detects cycles during edge insertion [OK]
Common Mistakes:
  • Thinking DFS on each edge is efficient enough
  • Believing DP can track cycles here
  • Assuming greedy edge removal finds cycles
3. Given the following code snippet implementing union-find for satisfiability of equality equations, what is the return value of equationsPossible when called with ["a==b", "b!=c", "c==a"]?
easy
A. Depends on input order
B. True
C. Raises an error
D. False

Solution

  1. Step 1: Process equalities

    Union 'a' and 'b', then union 'c' and 'a' (via 'c==a'), so 'a', 'b', 'c' are in the same set.
  2. Step 2: Check inequalities

    Check 'b!=c': since 'b' and 'c' share the same root, this inequality contradicts the equality sets, so return False.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Contradiction detected correctly [OK]
Hint: Check inequalities after all unions [OK]
Common Mistakes:
  • Checking inequalities before unions
  • Not path compressing causing wrong roots
4. What is the time complexity of the optimized Union-Find solution with path compression and union by rank for the Number of Operations to Make Network Connected problem, given n nodes and connections.length = m?
medium
A. O(n * m) due to nested loops over nodes and connections
B. O(m log n) due to union by rank tree height
C. O(m + n^2) because union operations can degrade to quadratic
D. O(m * α(n)) where α(n) is the inverse Ackermann function, nearly constant

Solution

  1. Step 1: Analyze union-find operations

    Each union/find operation runs in amortized O(α(n)) time with path compression and union by rank.
  2. Step 2: Multiply by number of connections

    We perform m union operations, so total time is O(m * α(n)), which is almost linear.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Union-Find with optimizations is near-linear, not quadratic or log-linear [OK]
Hint: Inverse Ackermann function α(n) is almost constant [OK]
Common Mistakes:
  • Assuming union-find is O(m log n)
  • Confusing n and m in complexity
  • Thinking union-find degrades to O(n*m)
5. What is the time complexity of the optimal union-find approach with early contradiction detection for satisfiability of equality equations, assuming n equations and a fixed alphabet of 26 variables?
medium
A. O(n^2) due to repeated find operations without optimization
B. O(n α(n)) where α(n) is the inverse Ackermann function, nearly constant
C. O(n log n) because of union by rank and path compression overhead
D. O(n) since each equation is processed once with constant-time unions

Solution

  1. Step 1: Identify union-find operations

    Each union or find operation runs in amortized O(α(n)) time due to path compression and union by rank.
  2. Step 2: Count total operations

    Processing n equations involves at most 2n union/find calls, so total time is O(n α(n)).
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Union-find nearly linear time complexity [OK]
Hint: Inverse Ackermann function is nearly constant [OK]
Common Mistakes:
  • Confusing α(n) with log n
  • Assuming O(n) without considering find complexity
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard