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.