Binary Subarrays With Sum
LeetCode 930 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
exactly(k) = atMost(k) − atMost(k − 1).
আমি Binary Subarrays With Sum (LeetCode 930) এভাবে সমাধান করেছি — Counting Subarrays (Exactly K = AtMost K − AtMost K−1) প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।
নিচের বিবরণ ইংরেজিতে।
Intuition
Counting windows with sum exactly goal is awkward, but counting windows with sum ≤ goal is easy with a sliding window (each right edge adds r − l + 1 windows). Exactly goal = atMost(goal) − atMost(goal − 1).
Approach
- 1
atMost(goal): expand right, shrink while the sum exceeds goal.
- 2
Every right edge contributes r − l + 1 subarrays.
- 3
Return atMost(goal) − atMost(goal − 1).
- 4
An earlier version used prefix sums with a hash map.
আমি কীভাবে সমাধান করেছি
atMost(k) − atMost(k−1)PythonO(n) time · O(1) space
class Solution:
def getCountSubArray(self, nums, goal):
if goal < 0:
return 0
cnt = 0
total = 0
l = 0
for r in range(len(nums)):
total += nums[r]
while total > goal:
total = total - nums[l]
l += 1
if total <= goal:
cnt += r - l + 1
return cnt
def numSubarraysWithSum(self, nums, goal):
return self.getCountSubArray(nums, goal) - self.getCountSubArray(nums, goal - 1)Binary Subarrays With Sum — সাধারণ প্রশ্ন
Binary Subarrays With Sum-এর পেছনে intuition কী?
Counting windows with sum exactly goal is awkward, but counting windows with sum ≤ goal is easy with a sliding window (each right edge adds r − l + 1 windows). Exactly goal = atMost(goal) − atMost(goal − 1).
Binary Subarrays With Sum (LeetCode 930) কীভাবে সমাধান করবেন?
1. atMost(goal): expand right, shrink while the sum exceeds goal. 2. Every right edge contributes r − l + 1 subarrays. 3. Return atMost(goal) − atMost(goal − 1). 4. An earlier version used prefix sums with a hash map.
Binary Subarrays With Sum-এর time আর space complexity কত?
Time: O(n)। Space: O(1)। (Accepted approach: atMost(k) − atMost(k−1)।)
Binary Subarrays With Sum-এ সাধারণ ভুলগুলো কী?
atMost(−1) must return 0.