Similar Problems

Similar Problems not available

Brick Wall - Leetcode Solution

Companies:

LeetCode:  Brick Wall Leetcode Solution

Difficulty: Medium

Topics: hash-table array  

The Brick Wall problem on LeetCode is a medium-level difficulty problem that can be solved using hashmaps and cumulative sum logic. The problem statement is as follows:

You have a wall that has a height of "height" and a width of infinity. You have an array "wall" of size n, where wall[i] is the width of the ith wall in your wall. The distance between any two adjacent bricks must be exactly the same. You need to find out the least number of bricks that you need to use to build the wall such that the width of the wall is the same between any two adjacent bricks. If it is not possible to achieve this, then return the number of bricks that you need to break to achieve this condition.

The steps to solve this problem are as follows:

Step 1: Create a hashmap that will store the number of times a particular distance is found in the wall. The key of the hashmap will be the distance and the value will be the frequency.

Step 2: Traverse the wall array and calculate the cumulative sum of the width of the wall. Store the cumulative sum in a variable called "count".

Step 3: For each brick in the wall, calculate the distance between the rightmost edge of the brick and the leftmost edge of the wall using the formula "distance = height - count", where "height" is the height of the wall.

Step 4: Check whether this distance is already present in the hashmap. If it is present, then increase the frequency of that distance by 1. If it is not present, then add it to the hashmap with a frequency of 1.

Step 5: Find the maximum frequency in the hashmap. This frequency will be the number of bricks that will be touching the same point on the wall.

Step 6: Subtract the number of bricks touching the same point on the wall from the total number of bricks in the wall to get the number of bricks that need to be removed to make the wall such that the width of the wall is the same between any two adjacent bricks.

Step 7: Return the number of bricks that need to be removed.

Here is the Python code for the solution:

class Solution:
    def leastBricks(self, wall: List[List[int]]) -> int:
        frequency = {}
        max_freq = 0
        
        for row in wall:
            count = 0
            for brick in row[:-1]:
                count += brick
                dist = len(row) - count
                if dist in frequency:
                    frequency[dist] += 1
                else:
                    frequency[dist] = 1
                max_freq = max(max_freq, frequency[dist])
                
        return len(wall) - max_freq

The time complexity of this solution is O(n*m), where n is the number of rows in the wall and m is the length of the longest row. The space complexity is O(n).

Brick Wall Solution Code

1