You are given a rectangular brick wall that is n
bricks high and of varying width. Each brick has the same height, but different widths. The wall is represented as a list of lists, where each inner list represents one row of the wall, and each element in the inner list represents the width of a brick.
You want to find the vertical line that cuts through the fewest number of bricks. This vertical line can only run between the bricks.
Write a function that returns the minimum number of crossed bricks.
Example:
Input:
[[1,2,2,1],
[3,1,2],
[1,3,2],
[2,4],
[3,1,2],
[1,3,1,1]]
Output: 2
Explanation:
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
unordered_map<int, int> edgeCount;
for (const auto& row : wall) {
int width = 0;
// We do not consider the rightmost edge of the wall
for (int i = 0; i < row.size() - 1; ++i) {
width += row[i];
edgeCount[width]++;
}
}
int maxEdges = 0;
for (const auto& edge : edgeCount) {
maxEdges = max(maxEdges, edge.second);
}
return wall.size() - maxEdges;
}
};
Time Complexity: O(n * m), where n is the number of rows and m is the maximum number of bricks in a row. This complexity arises because we are iterating over each brick, updating our hash map.
Space Complexity: O(n), where n is the number of unique edges in the wall. In the worst case, every brick forms a unique edge, but typically it will be significantly less than the total number of bricks.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?