#554
Brick Wall
MediumArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a HashMap to track the number of edges (or gaps) between bricks for each possible vertical line position. By finding the position with the most edges, we can minimize the number of crossed bricks.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a HashMap to count the number of edges at each position.
- 2Step 2: For each row, calculate the edge positions and update the HashMap.
- 3Step 3: The maximum value in the HashMap indicates the most edges crossed, so subtract this from the total number of rows to get the minimum crossed bricks.
solution.py13 lines
1# Full working Python code
2from collections import defaultdict
3
4def leastBricks(wall):
5 edge_count = defaultdict(int)
6 for row in wall:
7 position = 0
8 for brick in row[:-1]: # Exclude the last brick
9 position += brick
10 edge_count[position] += 1
11 return len(wall) - max(edge_count.values(), default=0)
12
13print(leastBricks([[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]))ℹ
Complexity note: The time complexity is O(n) because we only traverse each row once to calculate edge positions, leading to linear growth with respect to the number of rows.
- 1The edges between bricks are crucial for determining where to draw the line.
- 2Using a HashMap allows us to efficiently count the edges and minimize crossed bricks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.