Posts

Showing posts with the label prefix sum

554. Brick Wall

Image
https://leetcode.com/problems/brick-wall/ There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same height but different width. 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 go 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.   Example: Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] Output: 2 Explanation:   Note: The width sum of bricks in different rows ar...

930. Binary Subarrays With Sum

https://leetcode.com/problems/binary-subarrays-with-sum/ In an array  A  of  0 s and  1 s, how many  non-empty  subarrays have sum  S ? Example 1: Input: A = [1,0,1,0,1] , S = 2 Output: 4 Explanation: The 4 subarrays are bolded below: [ 1,0,1 ,0,1] [ 1,0,1,0 ,1] [1, 0,1,0,1 ] [1,0, 1,0,1 ] Note: A.length <= 30000 0 <= S <= A.length A[i]  is either  0  or  1 . ---- Intuition Prefix sum approach If difference of prefix sum at any two indices == target => sum of elements between those two indices == target => increment ans by 1 If the same prefix sum appears again.. (can happen in binary array or array with negative numbers), then ans += number of previous prefix sums with that sum Track the prefix sum, and # of times it appears in a hash map Seed the map with key = 0, value = 1 (*) Traverse left to right if (sum >= s)    ans += map.get(sum - s) map.put(sum, map.get(sum) + 1) (*) When prefi...