0
\$\begingroup\$

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.

Note -

  • The width sum of bricks in different rows are the same and won't exceed INT_MAX.

  • 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 20,000.

Example -

Input: [[1,2,2,1],
        [3,1,2],
        [1,3,2],
        [2,4],
        [3,1,2],
        [1,3,1,1]]

Output: 2

Explanation -

enter image description here

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) -

enter image description here

Taken from - https://docs.python.org/3/library/collections.html#collections.Counter -

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.

\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

There's a lot of repeated summing taking place in this part:

(sum(row[:i + 1]) for row in wall for i in range(len(row[:-1])))

So this is summing the first i+1 elements in the row, with an upper bound that steps through all values except the last. If the row was [1, 2, 3, 4, 5], these are the sums:

  • 1
  • 1+2 = 3
  • 1+2+3 = 6
  • 1+2+3+4 = 10

The sums differ, but only by the last term. It would therefore save effort to use a running sum instead, only adding that last term each time:

  • 1
  • 1+2 = 3
  • 3+3 = 6
  • 6+4 = 10

This can be done with itertools.accumulate:

(s for row in wall for s in itertools.accumulate(row[:-1]))

Another thing in your code that this approach solves is the i+1 summing. Instead of having this addition performed on every iteration, you could iterate through the correct values directly with for i in range(1, len(row)). But using accumulate, this is already taken care of.

\$\endgroup\$
3
\$\begingroup\$

Counter

Great use of Counter. One thing that can be improved, is to use most_common instead of max.

If edges is the Counter of all the edges in the wall, _, max_edges = edges.most_common(1) gives you the index with the most edges, and how many edges it has. Since this is the right side of the wall, you need the 2nd most common element: edges.most_common(2)[1]

aggregating the counter

Python is batteries included. Whenever you want to do advanced iteration, it can pay to look at the itertools module. For this, you can use accumulate (as @sedsarq notes in his answer) and chain.

edges = collections.Counter(
    chain.from_iterable(accumulate(row) for row in wall)
)

def least_bricks2(wall):
    edges = collections.Counter(
        chain.from_iterable(accumulate(row) for row in wall)
    )
    if len(edges) == 1: # only one brick wide
        return len(wall)
    _, max_edges = edges.most_common(2)[1]  #skipping the right edge of the wall
    return len(wall) - max_edges
\$\endgroup\$
2
  • 1
    \$\begingroup\$ To be pedantic, you need to check for the case where the counter only has one element. That can occur if there is only one width of brick, for instance the testcase [[2],[2],[2],[2],[2],[2]] \$\endgroup\$
    – spyr03
    Commented Jun 12, 2019 at 20:57
  • \$\begingroup\$ You are correct. Fixed that \$\endgroup\$ Commented Jun 13, 2019 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.