Imagine a brick wall made of several rows of bricks. Each row has the same total width, but the bricks in each row have different widths. You want to draw a vertical line from top to bottom that crosses the fewest number of bricks. The line cannot be drawn at the very edges of the wall.
This is a popular question at companies like Bloomberg, Amazon, and Meta. It tests your ability to think "laterally." Instead of counting how many bricks you cross, you should count how many edges (gaps between bricks) you align with. This shift in perspective turns a geometric problem into a Hash Table frequency problem.
This problem uses the Hash Table / Frequency Map pattern. For each row, you calculate the cumulative sum of the brick widths (which represents the positions of the edges). You store the frequency of each edge position in a map. The position with the highest frequency is where you should draw your line, as it passes through the most gaps and thus the fewest bricks.
Wall: Row 1: [1, 2, 2, 1] -> Edges at: 1, 3, 5 Row 2: [3, 1, 2] -> Edges at: 3, 4 Row 3: [1, 3, 2] -> Edges at: 1, 4
Frequency Map: Edge 1: 2 times Edge 3: 2 times Edge 4: 2 times Edge 5: 1 time
Maximum edge frequency is 2. The wall height is 3. Minimum bricks crossed = Total Rows - Max Edges = 3 - 2 = 1.
The most common error is including the last edge (the end of the wall) in the map. The problem specifically says you cannot draw the line at the edges. Another mistake is using nested loops that result in time (where is the width of the wall), which is too slow if the bricks are thin and the wall is wide. The hash table approach is , where is the total number of bricks.
When a problem asks to "minimize intersections," look for "maximum alignments." Counting gaps or edges is often much easier than counting overlaps. This "complementary" thinking is a key skill for optimizing spatial algorithms.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| 4Sum II | Medium | Solve | |
| Find All Duplicates in an Array | Medium | Solve | |
| Find the Number of Good Pairs II | Medium | Solve | |
| Convert an Array Into a 2D Array With Conditions | Medium | Solve | |
| Card Flipping Game | Medium | Solve |