I would like to know whether I could make my solution to this Leetcode challenge much faster.
There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same heights but different widths. You want to draw a vertical line from the top to the bottom and cross the least bricks.
The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.
If your line goes through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.
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.
The width sum of bricks in different rows are the same and won't exceed
The number of bricks in each row is in the range
[1, 10,000]. The height of the wall is in the range
[1, 10,000]. The total number of bricks in the wall won't exceed
Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] Output: 2
Here is my solution to this challenge -
import collections def least_bricks(wall): return len(wall) - max(collections.Counter(sum(row[:i + 1]) for row in wall for i in range(len(row[:-1]))).values(), default = 0)
Here is the time taken for the example output -
%timeit least_bricks([[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]]) >>> 13 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Here is my Leetcode result (85 test cases) -
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.