#554
Medium Algorithms Brick wall
Array Hash Table
56.0% acceptance
Jan 13, 2026
2665
186
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. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
Given the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn least_bricks(wall: Vec<Vec<i32>>) -> i32 {
use std::collections::HashMap;
let n = wall.len() as i32;
let mut edge_count: HashMap<i32, i32> = HashMap::new();
for row in &wall {
let mut pos = 0i32;
for &brick in &row[..row.len() - 1] {
pos += brick;
*edge_count.entry(pos).or_insert(0) += 1;
}
}
let max_edges = edge_count.values().copied().max().unwrap_or(0);
n - max_edges
}
}