Skip to content

Commit e58fe43

Browse files
authored
Create brick-wall.py
1 parent cd89d42 commit e58fe43

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Python/brick-wall.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Time: O(n), n is the total number of the bricks
2+
# Space: O(m), m is the total number different widths
3+
4+
# There is a brick wall in front of you. The wall is rectangular and has several rows of bricks.
5+
# The bricks have the same height but different width. You want to draw a vertical line from
6+
# the top to the bottom and cross the least bricks.
7+
#
8+
# The brick wall is represented by a list of rows. Each row is a list of integers representing the
9+
# width of each brick in this row from left to right.
10+
#
11+
# If your line go through the edge of a brick, then the brick is not considered as crossed.
12+
# You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.
13+
#
14+
# You cannot draw a line just along one of the two vertical edges of the wall,
15+
# in which case the line will obviously cross no bricks.
16+
#
17+
# Example:
18+
# Input:
19+
# [[1,2,2,1],
20+
# [3,1,2],
21+
# [1,3,2],
22+
# [2,4],
23+
# [3,1,2],
24+
# [1,3,1,1]]
25+
# Output: 2
26+
#
27+
# Note:
28+
# The width sum of bricks in different rows are the same and won't exceed INT_MAX.
29+
# The number of bricks in each row is in range [1,10,000].
30+
# The height of wall is in range [1,10,000].
31+
# Total number of bricks of the wall won't exceed 20,000.
32+
33+
class Solution(object):
34+
def leastBricks(self, wall):
35+
"""
36+
:type wall: List[List[int]]
37+
:rtype: int
38+
"""
39+
widths = collections.defaultdict(int)
40+
result = len(wall)
41+
for row in wall:
42+
width = 0
43+
for i in xrange(len(row)-1):
44+
width += row[i]
45+
widths[width] += 1
46+
result = min(result, len(wall) - widths[width]);
47+
return result

0 commit comments

Comments
 (0)