Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Bricks Falling When Hit

Updated
5 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "803" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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 of the grid, or At least one other brick in its four adjacent cells is stable. You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks). Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied. Note that an erasure may refer to a location with no brick, and if it does, no bricks drop. Example 1: Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]] Output: [2] Explanation: 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] Explanation: 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.

Explanation

Here's the approach, analysis, and Python code:

  • Reverse Thinking: Instead of removing bricks and checking for instability after each hit, we reverse the process. We first "hit" all the target locations in the grid, marking them (e.g., with a value of 2). Then, we start by making the grid stable as it would be after all the hits. We then iterate through the hits array in reverse order, "restoring" the bricks at each hit location one by one, and calculating how many bricks become stable as a result of this restoration.
  • Union-Find for Connectivity: We use the Union-Find data structure to efficiently track connected components of stable bricks. Specifically, we consider bricks connected to the top row as part of the "stable" component. When restoring a brick, we check its neighbors, and if they are also bricks (value 1) already considered stable, we merge their components using Union-Find. The change in the size of the stable component is the number of bricks that fell as a result of the removal.

  • Runtime Complexity: O(m n + k α(m n)), where 'm' and 'n' are the dimensions of the grid, 'k' is the number of hits, and α is the inverse Ackermann function (which grows very slowly and can be considered practically constant). Storage Complexity: O(m n)

Code

    class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x != root_y:
            if self.size[root_x] < self.size[root_y]:
                root_x, root_y = root_y, root_x
            self.parent[root_y] = root_x
            self.size[root_x] += self.size[root_y]

class Solution:
    def hitBricks(self, grid, hits):
        m, n = len(grid), len(grid[0])
        uf = UnionFind(m * n + 1)  # +1 to represent the "top" connection

        # Mark hits as "removed" (2)
        for r, c in hits:
            if grid[r][c] == 1:
                grid[r][c] = 2

        # Initial stability check (after all hits are applied)
        for r in range(m):
            for c in range(n):
                if grid[r][c] == 1:
                    index = r * n + c
                    if r == 0:
                        uf.union(index, m * n)  # Connect to the "top"
                    # Connect to adjacent bricks
                    for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
                            neighbor_index = nr * n + nc
                            uf.union(index, neighbor_index)

        result = []
        for r, c in reversed(hits):
            if grid[r][c] == 2:  # It was a brick
                grid[r][c] = 1  # Restore the brick
                prev_size = uf.size[uf.find(m * n)]
                index = r * n + c
                if r == 0:
                    uf.union(index, m * n)
                # Connect to adjacent bricks
                for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                    nr, nc = r + dr, c + dc
                    if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
                        neighbor_index = nr * n + nc
                        uf.union(index, neighbor_index)

                new_size = uf.size[uf.find(m * n)]
                fallen = new_size - prev_size - 1  # -1 to exclude the restored brick itself
                result.append(max(0, fallen))  # Ensure non-negative
            else:
                result.append(0)  # It was an empty cell, so no bricks fell

        return result[::-1]  # Reverse the result to match the original hit order

More from this blog

C

Chatmagic blog

2894 posts