LeetCode Problem Workspace

Bricks Falling When Hit

Bricks Falling When Hit challenges your ability to simulate brick falls after sequential erasures using Union Find.

category

3

Topics

code_blocks

4

Code langs

hub

3

Related

Practice Focus

Hard · Array plus Union Find

bolt

Answer-first summary

Bricks Falling When Hit challenges your ability to simulate brick falls after sequential erasures using Union Find.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Array plus Union Find

Try AiBox Copilotarrow_forward

In the Bricks Falling When Hit problem, you need to simulate the effect of erasing bricks sequentially in a grid. Use a combination of Union Find and Array techniques to track how bricks fall after each hit. The key challenge is handling the stability of bricks efficiently after each modification.

Problem Statement

You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if it is directly connected to the top row or has at least one neighboring brick that is stable. You will also be given an array hits, which contains the sequence of positions where bricks will be erased. After each erasure, some bricks may no longer be stable and will fall.

Your goal is to return an array where each element represents the number of bricks that fall after the ith erasure is applied. This requires simulating the erasure process and determining how the stability of other bricks is affected by each hit. The key to solving this problem efficiently is utilizing Union Find to manage connectivity between bricks.

Examples

Example 1

Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]

Output: [2]

Starting with the grid: [[1,0,0,0], [1,1,1,0]] We erase the underlined brick at (1,0), resulting in the grid: [[1,0,0,0], [0,1,1,0]] The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is: [[1,0,0,0], [0,0,0,0]] Hence the result is [2].

Example 2

Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]

Output: [0,0]

Starting with the grid: [[1,0,0,0], [1,1,0,0]] We erase the underlined brick at (1,1), resulting in the grid: [[1,0,0,0], [1,0,0,0]] All remaining bricks are still stable, so no bricks fall. The grid remains the same: [[1,0,0,0], [1,0,0,0]] Next, we erase the underlined brick at (1,0), resulting in the grid: [[1,0,0,0], [0,0,0,0]] Once again, all remaining bricks are still stable, so no bricks fall. Hence the result is [0,0].

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • grid[i][j] is 0 or 1.
  • 1 <= hits.length <= 4 * 104
  • hits[i].length == 2
  • 0 <= xi <= m - 1
  • 0 <= yi <= n - 1
  • All (xi, yi) are unique.

Solution Approach

Union Find Setup

The problem requires us to track the stability of bricks after each hit. A Union Find (disjoint-set) structure helps efficiently determine which bricks are connected to the top row and, consequently, which bricks are stable. By initially marking all positions in the grid, we can then progressively simulate each erasure and determine which bricks fall.

Reversing Hits for Initial Stability

To handle the erasures efficiently, we reverse the sequence of hits and simulate the effect of all hits applied before determining the result. This allows us to restore the grid to its original state, then check how the removal of bricks at each step affects the stability of other bricks connected to the top row.

Tracking Falling Bricks

For each hit, after restoring the grid, we use Union Find to check which bricks are still connected to the top row and which ones will fall. Once a brick is identified as falling, it is immediately erased, and this process continues until no further changes occur.

Complexity Analysis

Metric Value
Time O(N \cdot \alpha(N))
Space O(N)

The time complexity is O(N * α(N)), where N is the total number of cells in the grid and α(N) is the inverse Ackermann function, which grows very slowly. The space complexity is O(N), where N is the number of grid cells and the size of the Union Find structure.

What Interviewers Usually Probe

  • Tests the candidate's ability to handle grid manipulation using efficient data structures like Union Find.
  • Assesses the candidate's understanding of graph connectivity and the impact of sequential modifications on data structures.
  • Evaluates the candidate's approach to problem-solving under constraints like time complexity and handling large inputs.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to reverse the hits and restoring the grid before processing each hit.
  • Mismanaging the Union Find structure, leading to incorrect connectivity checks.
  • Overcomplicating the problem by using brute force instead of efficient Union Find operations.

Follow-up variants

  • What if the grid was dynamic and cells could be added after each erasure?
  • How would you approach this if you were required to support a 3D grid?
  • Can this be optimized further for very large grids, say for a billion cells?

FAQ

How do I solve Bricks Falling When Hit using Union Find?

You need to simulate the erasure of bricks while tracking the stability of others using Union Find. Start by reversing the hits and restoring the grid before applying each hit.

What is the time complexity of the Bricks Falling When Hit problem?

The time complexity is O(N * α(N)), where N is the number of cells in the grid and α(N) is the inverse Ackermann function.

How can I handle multiple hits in the Bricks Falling When Hit problem?

You can process the hits in reverse order, restoring the grid at each step, and then using Union Find to determine the number of falling bricks after each hit.

What happens if a brick is no longer stable after a hit?

If a brick is no longer stable after a hit, it falls and is erased from the grid immediately, affecting the stability of other connected bricks.

How does GhostInterview assist with solving Bricks Falling When Hit?

GhostInterview offers real-time feedback and helps you optimize your Union Find approach, providing detailed explanations to avoid common pitfalls and improve your solution.

terminal

Solution

Solution 1

#### Python3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution:
    def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:
        def find(x):
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        def union(a, b):
            pa, pb = find(a), find(b)
            if pa != pb:
                size[pb] += size[pa]
                p[pa] = pb

        m, n = len(grid), len(grid[0])
        p = list(range(m * n + 1))
        size = [1] * len(p)
        g = deepcopy(grid)
        for i, j in hits:
            g[i][j] = 0
        for j in range(n):
            if g[0][j] == 1:
                union(j, m * n)
        for i in range(1, m):
            for j in range(n):
                if g[i][j] == 0:
                    continue
                if g[i - 1][j] == 1:
                    union(i * n + j, (i - 1) * n + j)
                if j > 0 and g[i][j - 1] == 1:
                    union(i * n + j, i * n + j - 1)
        ans = []
        for i, j in hits[::-1]:
            if grid[i][j] == 0:
                ans.append(0)
                continue
            g[i][j] = 1
            prev = size[find(m * n)]
            if i == 0:
                union(j, m * n)
            for a, b in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and g[x][y] == 1:
                    union(i * n + j, x * n + y)
            curr = size[find(m * n)]
            ans.append(max(0, curr - prev - 1))
        return ans[::-1]
Bricks Falling When Hit Solution: Array plus Union Find | LeetCode #803 Hard