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.