# C++ 6 lines (hash map)

• For each potential cut position - which is at the edge of any brick, I am counting the number of brick edges for all rows. Note that we need to use hash map to only track potential (not all) cuts. If bricks are very wide, you'll get MLE if you store all cut positions.

``````int leastBricks(vector<vector<int>>& wall) {
unordered_map<int, int> edges;
auto min_bricks = wall.size();
for (auto row : wall)
for (auto i = 0, width = 0; i < row.size() - 1; ++i) // skip last brick
min_bricks = min(min_bricks, wall.size() - (++edges[width += row[i]]));
return min_bricks;
}
``````

• excellent solution！

• pretty good,and mine is trivial.

``````class Solution {
public:
int leastBricks(vector<vector<int>>& wall) {
//firstly,there is a function using hashtable
for(auto &i:wall){
for(int j=1;j<i.size();j++){
i[j]+=i[j-1];
}
}
unordered_map<int,int>mymap;
for(auto &i:wall){
for(int j=0;j<i.size()-1;j++){
mymap[i[j]]++;
}
}
int max=0;
for(auto i=mymap.begin();i!=mymap.end();i++){
if((*i).second>max){
max=(*i).second;
}
}
return wall.size()-max;
}
};
``````

• Longer but logically more modularized

``````int leastBricks(vector<vector<int>>& wall) {
unordered_map<int, int> edges;
auto minBricks = wall.size();

for(auto row: wall){
for(int i = 0, width = 0; i <row.size()-1; i++){
width += row[i];
edges[width] += 1;
}
}

for(auto edge: edges) minBricks = min(minBricks, wall.size() - edge.second);
return minBricks;
}``````

• wonderful! I have learnt a lot from it.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.