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
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
Focus on handling smallest and boundary inputs correctly before tackling complex cases.
Beware of common algorithmic traps like greedy approaches and incorrect path assumptions.
Ensure your solution is optimized for large inputs using efficient data structures.
t1_01basic
Input{"grid":[[0,2],[1,3]]}
Expected3
⏱ Performance - must finish in 2000ms
At time 3, water level is 3, allowing movement from (0,0) to (1,1) through (1,0).
💡 Consider the water level as a time parameter that must be at least the elevation of cells you traverse.
💡 Use union-find or BFS to check connectivity at each water level increment.
💡 The answer is the minimum water level at which start and end cells become connected.
Why it failed: Returned value less than 3 means path connectivity logic is incorrect; fix union-find merges or BFS checks to ensure all reachable cells at current water level are connected.
✓ Correctly identifies earliest time when path is possible.
t1_02basic
Input{"grid":[[0,1,2],[5,4,3],[6,7,8]]}
Expected5
⏱ Performance - must finish in 2000ms
Minimum time is 5 because path must cross elevation 5 at (1,0) to reach bottom-right.
💡 Track cells in order of elevation and union adjacent cells as water rises.
💡 Check when top-left and bottom-right cells become connected.
💡 The earliest time is the maximum elevation on the path connecting start and end.
Why it failed: Output less than 5 means algorithm missed higher elevation cells blocking path; ensure union-find merges include all adjacent cells with elevation <= current time.
✓ Correctly computes minimum time considering elevation barriers.
t2_01edge
Input{"grid":[[0]]}
Expected0
⏱ Performance - must finish in 2000ms
Single cell grid; start is end; minimum time is elevation at (0,0).
💡 Check behavior when grid size is 1x1.
💡 The answer should be the elevation of the only cell.
💡 Return grid[0][0] immediately for n=1.
Why it failed: Fails single element case by not returning grid[0][0]; add base case for n=1 to return grid[0][0].
✓ Handles single cell grid correctly.
t2_02edge
Input{"grid":[[0,1],[2,3]]}
Expected3
⏱ Performance - must finish in 2000ms
Path requires waiting until water level 3 to reach bottom-right cell.
💡 Verify that algorithm handles exact boundary where water level equals max elevation on path.
💡 Check union-find merges include cells with elevation equal to current water level.
💡 Ensure <= comparison when checking if cell is accessible at current time.
Why it failed: Fails exact boundary by using < instead of <= in elevation checks; fix condition to allow cells with elevation equal to water level.
All cells have identical elevation 0; path is immediately available.
💡 Test grids where all elevations are the same.
💡 Union-find should merge all cells at time 0.
💡 Answer is elevation of start cell since all are accessible immediately.
Why it failed: Fails identical elevation case by not merging all cells at time 0; fix union-find initialization to merge all adjacent cells with elevation <= current time.
✓ Handles identical elevation grids correctly.
t3_01corner
Input{"grid":[[0,100,1],[2,3,4],[5,6,7]]}
Expected7
⏱ Performance - must finish in 2000ms
Greedy approach picking lowest elevation neighbors first fails; must consider union-find connectivity over time.
💡 Beware of greedy approach that picks lowest elevation neighbor without considering connectivity.
💡 Use union-find or binary search over time to check connectivity.
💡 Answer is max elevation on any path connecting start and end, not just local minima.
Why it failed: Greedy trap: returns 6 or less by ignoring high elevation cell blocking direct path; fix by using union-find to check connectivity at each water level.
✓ Correctly avoids greedy trap by checking connectivity globally.
t3_02corner
Input{"grid":[[0,1,2],[3,4,5],[6,7,8]]}
Expected8
⏱ Performance - must finish in 2000ms
Confusing 0/1 knapsack analogy: must not reuse cells multiple times; path must be continuous and respects water level.
💡 Do not confuse with unbounded knapsack; each cell can be visited once per path.
💡 Connectivity depends on water level and adjacency, not repeated usage.
💡 Use union-find or BFS to check if start and end are connected at given water level.
Why it failed: Mistakes 0/1 vs unbounded by allowing multiple visits or ignoring adjacency; fix by enforcing adjacency and single visit per path in connectivity checks.
✓ Correctly models path constraints and water level conditions.
t3_03corner
Input{"grid":[[0,2,3],[1,100,4],[5,6,7]]}
Expected7
⏱ Performance - must finish in 2000ms
High elevation cell blocks direct path; algorithm must find detour around it.
💡 Check if algorithm handles isolated high elevation cells blocking direct path.
💡 Union-find merges must consider all accessible neighbors at current water level.
💡 Answer is minimum water level allowing detour around high elevation obstacle.
Why it failed: Fails detour case by assuming direct path always available; fix by merging all accessible neighbors and checking connectivity properly.
✓ Correctly finds detour path around high elevation obstacles.
t4_01performance
Input{"_description":"n=50 at constraint boundary - executor generates this"}
Expectednull
⏱ Performance - must finish in 2000ms
n=50 grid with unique elevations; O(n^2 log n) union-find approach must complete within 2 seconds.
💡 Use union-find with sorting cells by elevation for efficient connectivity checks.
💡 Avoid brute force DFS for each time increment; use binary search or union-find.
💡 Optimize union-find with path compression and union by rank.
Why it failed: TLE due to brute force DFS or inefficient union-find; fix by implementing union-find with sorting and path compression.
✓ Algorithm runs within time limit using efficient union-find approach.
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
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.
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.
Final Answer:
Option C -> Option C
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
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.
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.
Final Answer:
Option A -> Option A
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
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.
Step 2: Check inequalities
Check 'b!=c': since 'b' and 'c' share the same root, this inequality contradicts the equality sets, so return False.
Final Answer:
Option D -> Option D
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
Step 1: Analyze union-find operations
Each union/find operation runs in amortized O(α(n)) time with path compression and union by rank.
Step 2: Multiply by number of connections
We perform m union operations, so total time is O(m * α(n)), which is almost linear.
Final Answer:
Option D -> Option D
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
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.
Step 2: Count total operations
Processing n equations involves at most 2n union/find calls, so total time is O(n α(n)).
Final Answer:
Option B -> Option B
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 unknownstrongwhile earning +1 Grip toward your certificate.