Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 930 · Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

Binary Subarrays With Sum

LeetCode 930 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

exactly(k) = atMost(k) − atMost(k − 1).

మధ్యస్థంArrayHash TableSliding WindowPrefix Sum
LeetCode లో తెరవండి ↗

నేను 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. 1

    atMost(goal): expand right, shrink while the sum exceeds goal.

  2. 2

    Every right edge contributes r − l + 1 subarrays.

  3. 3

    Return atMost(goal) − atMost(goal − 1).

  4. 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.