Bird
Raised Fist0
Interview Prepunion-findhardGoogleAmazon

Swim in Rising Water

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize grid and union-find

We start by initializing the union-find data structure for all 4 cells (0 to 3) and creating a list of all cells with their elevations.

💡 Setting up union-find and the cell list is essential to track connectivity and process cells in elevation order.
Line:n = len(grid) uf = UnionFind(n * n) cells = [(grid[i][j], i, j) for i in range(n) for j in range(n)]
💡 Union-find parent array is initialized to each node being its own parent, meaning no connections yet.
📊
Swim in Rising Water - Watch the Algorithm Execute, Step by Step
Watching each union and connectivity check reveals how the algorithm incrementally builds paths as water rises, making the abstract union-find operations concrete.
Step 1/10
·Active fill★Answer cell
Visiting: none
0
1
2
3
Visiting: none
0
2
1
3
Visiting: 0
0
2
1
3
Visiting: 2
Edge: 2 → 0
0
2
1
3
Visiting: 2
0
2
1
3
Visiting: 1
Edge: 1 → 0
0
2
1
3
Visiting: 1
0
2
1
3
Visiting: 3
Edge: 3 → 2
0
2
1
3
Visiting: 3
0
2
1
3
Visiting: none
0
2
1
3

Key Takeaways

✓ Union-Find efficiently tracks connectivity as cells become accessible in elevation order.

This insight is hard to see from code alone because union-find operations are abstract; watching unions happen stepwise clarifies how connectivity grows.

✓ Processing cells sorted by elevation simulates water rising and reveals the earliest time a path forms.

Seeing the order visually helps understand why sorting is critical and how it drives the algorithm's correctness.

✓ Connectivity checks after each union determine when the start and end become connected, signaling the answer.

The decision to stop when connected is subtle in code but clear when watching the connectivity state change in the visualization.

Practice

(1/5)
1. You are given an undirected, weighted graph and need to find a subset of edges that connects all vertices with the minimum possible total edge weight, without forming any cycles. Which algorithmic approach guarantees an optimal solution efficiently?
easy
A. Dynamic Programming on subsets of edges to find minimum cost spanning subgraph
B. Greedy algorithm sorting edges by weight and using union-find to avoid cycles
C. Depth-First Search to find all spanning trees and pick the minimum weight one
D. Breadth-First Search to find shortest paths and combine them into a spanning tree

Solution

  1. Step 1: Understand the problem requirements

    The problem asks for a minimum total edge weight subset connecting all vertices without cycles, which is the definition of a Minimum Spanning Tree (MST).
  2. Step 2: Identify the algorithm that guarantees optimal MST efficiently

    Kruskal's algorithm sorts edges by weight and uses union-find to avoid cycles, ensuring minimal total weight and connectivity efficiently.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Greedy + union-find is classic MST approach [OK]
Hint: MST needs cycle-free minimal edges; union-find + sorting fits [OK]
Common Mistakes:
  • Thinking DFS or BFS can find MST optimally
  • Assuming DP on subsets is efficient here
  • Believing greedy without cycle checks works
2. What is the time complexity of the optimal union-find solution for the Most Stones Removed with Same Row or Column problem, given n stones?
medium
A. O(n α(n)) where α is the inverse Ackermann function, due to union-find operations
B. O(n^2) due to checking all pairs of stones
C. O(n log n) because of sorting stones by coordinates
D. O(n) since each stone is processed once without extra overhead

Solution

  1. Step 1: Analyze union-find operations

    Each union/find operation runs in nearly O(1) amortized time, specifically O(α(n)) where α is inverse Ackermann.
  2. Step 2: Count total operations

    We perform at most 2n find operations and n union operations, total O(n α(n)).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Union-find with path compression and rank -> O(n α(n)) [OK]
Hint: Union-find with path compression -> near-linear time [OK]
Common Mistakes:
  • Assuming O(n^2) from brute force pairwise checks
  • Confusing sorting complexity with union-find
  • Ignoring inverse Ackermann function in complexity
3. What is the time complexity of the optimal DFS with adjacency list conversion approach for finding the number of provinces in an n x n connectivity matrix?
medium
A. O(n + e), where e is the number of edges
B. O(n log n), because of sorting neighbors during adjacency list creation
C. O(n^3), due to nested loops in DFS and adjacency list construction
D. O(n^2), because the adjacency matrix must be fully scanned

Solution

  1. Step 1: Identify loops in adjacency list construction

    Constructing adjacency list requires scanning the entire n x n matrix, which is O(n^2).
  2. Step 2: Analyze DFS traversal cost

    DFS visits each node and edge once. In worst case, edges can be O(n^2), so DFS is O(n + e) = O(n^2).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Overall time dominated by adjacency list construction and DFS traversal [OK]
Hint: Adjacency matrix scan dominates -> O(n^2) [OK]
Common Mistakes:
  • Confusing adjacency list DFS as O(n+e) ignoring matrix scan
  • Assuming sorting neighbors adds log factor
4. What is the time complexity of the optimal Union-Find algorithm with path compression and union by rank when finding the redundant connection in a graph with n edges?
medium
A. O(n²) because each union operation may traverse all nodes
B. O(n * α(n)) where α(n) is the inverse Ackermann function, nearly constant
C. O(n log n) due to sorting edges before union operations
D. O(n) because each edge is processed once without overhead

Solution

  1. Step 1: Identify number of union/find operations

    There are n edges, each triggers at most one union and two finds.
  2. Step 2: Analyze complexity of find with path compression and union by rank

    Each find/union operation runs in amortized O(α(n)) time, where α(n) is inverse Ackermann function, which grows extremely slowly.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Union-Find with optimizations runs in near-linear time O(n * α(n)) [OK]
Hint: Inverse Ackermann function α(n) is almost constant [OK]
Common Mistakes:
  • Assuming O(n²) due to nested loops
  • Confusing sorting complexity with union-find
  • Ignoring path compression benefits
5. Suppose the Accounts Merge problem is extended so that emails can be reused across multiple users (e.g., shared family emails). Which modification to the union-find approach correctly handles this scenario?
hard
A. Use a graph with edges between accounts and emails, then find connected components allowing multiple parents
B. Keep union-find as is; emails connected once belong to a single user
C. Modify union-find to allow multiple parents per node to represent shared emails
D. Assign emails to users greedily by first occurrence, ignoring overlaps

Solution

  1. Step 1: Understand the new constraint

    Emails can belong to multiple users, so union-find's single parent per node model breaks down.
  2. Step 2: Choose correct data structure

    A bipartite graph connecting accounts and emails with connected components allows shared emails without forcing merges.
  3. Step 3: Evaluate other options

    Union-find cannot represent multiple parents; greedy assignment loses correctness.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Graph approach models shared emails correctly [OK]
Hint: Union-find assumes disjoint sets; shared emails break this [OK]
Common Mistakes:
  • Trying to modify union-find for multiple parents
  • Ignoring shared emails and merging incorrectly
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