Lecture 1 (Medium Problems)¶
Binary subarray with sum¶
You are given a binary array nums (containing only 0s and 1s) and an integer goal. Return the number of non-empty subarrays of nums that sum to goal. A subarray is a contiguous part of the array.
Input: nums =[1,0,1,0,1], goal = 2
Output: 4
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
Input: nums = [0,0,0,0,0], goal = 0
Output: 15
Approach 1 (Brute Force)¶
- three nested loops like subarray sum
In [8]:
def binary_subarray(nums,target):
count =0
n = len(nums)
for i in range(n):
for j in range(i,n):
sum =0
for k in range(i,j+1):
sum += nums[k]
if sum == target:
count +=1
return count
print(binary_subarray([1,0,1,0,1],2))
print(binary_subarray([0,0,0,0,0],0))
4 15
Complexity¶
- N = len(nums)
O(N^3)
O(1)
Approach 2¶
- remove outer most loop
- sum check will remain inside second loop
In [11]:
def binary_subarray(nums,target):
count =0
n = len(nums)
for i in range(n):
sum =0
for j in range(i,n):
sum += nums[j]
if sum == target:
count +=1
return count
print(binary_subarray([1,0,1,0,1],2))
print(binary_subarray([0,0,0,0,0],0))
4 15
Complexity¶
- N = len(nums)
O(N^2)
O(1)
Approach 3 (prefix sum with hashmap)¶
- Kadane's algorithm finds the maximum sum subarray
- This problem requires counting ALL subarrays with a specific sum
- You need to track all possible prefix sums and their frequencies
In [14]:
def binary_subarray(nums,target):
count =0
prefix_sum =0
sum_count ={0:1}
for num in nums:
prefix_sum += num
if (prefix_sum - target) in sum_count:
count += sum_count[prefix_sum - target]
sum_count[prefix_sum] = sum_count.get(prefix_sum,0) +1
return count
print(binary_subarray([1,0,1,0,1],2))
print(binary_subarray([0,0,0,0,0],0))
4 15
Complexity¶
- N = len(nums)
O(N)
O(N)
Approach 4 (Sliding window)¶
- result = sub_array_sum_atmost(goal) - sub_array_sum_atmost(goal -1)
- where sub_array_sum_atmost(goal) : all possible subarray count whose sum <= target
- in order to find the sub array sum , we can make use of sliding window
- both left and right will start from 0
- shrink the window till the subarray sum > target
- window lenfth = right - left +1 => required count
In [17]:
def binary_subarray(nums,target):
n = len(nums)
def sum_atmost(goal):
if goal < 0:
return 0
left =0
count =0
sum =0
for right in range(n):
sum += nums[right]
## shrink the window if sum exceeds
while sum > goal and left <= right:
sum -= nums[left]
left +=1
count += (right - left +1)
return count
return sum_atmost(target) - sum_atmost(target-1)
print(binary_subarray([1,0,1,0,1],2))
print(binary_subarray([0,0,0,0,0],0))
4 15
Complexity¶
- N = len(nums)
O(N)
O(1)