Brick Wall — LeetCode 554 Python Solution
- Problem
- #554
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths.
Example
- Input
- wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]
- Output
- 2
Python solution
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
cnt = Counter()
for row in wall:
s = 0
for x in row[:-1]:
s += x
cnt[s] += 1
return len(wall) - max(cnt.values(), default=0)Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 554. Brick Wall is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 554. Brick Wall?
- LeetCode 554. Brick Wall is rated Medium on LeetCode.
- What is the time complexity of LeetCode 554. Brick Wall?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 554. Brick Wall?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 554. Brick Wall cover?
- LeetCode 554. Brick Wall is tagged Array and Hash Table on LeetCode.