Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 560 · Prefix Sum

Subarray Sum Equals K

LeetCode 560 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

count += seen[prefix − k], then record prefix.

ಮಧ್ಯಮArrayHash TablePrefix Sum
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Subarray Sum Equals K (LeetCode 560) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Prefix Sum ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

If the running sum up to here is x and some earlier prefix summed to x − k, then the stretch between them sums to exactly k. So keep a count of every prefix sum seen; at each step add how many times x − k has appeared.

Approach

  1. 1

    Keep a running prefix sum x.

  2. 2

    If x itself equals k, the subarray from the start counts.

  3. 3

    Add how many earlier prefixes equal x − k.

  4. 4

    Record x in the prefix-count map.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Prefix sum + hash mapPythonO(n) time · O(n) space
#prefix sum
#----------x--------|
#-------(x-k)|--k---|
#if cur sum == k increase count
#if we have seen cur_sum-k before that helps to get the sum k - increment count with the occurance of x-k 
# store the current sum and increment the occurance
class Solution:
    def subarraySum(self, nums: List[int], k: int) -> int:
        r=0
        prefix_sum = defaultdict(int)
        x = 0
        count=0
        while r<len(nums):
            x+=nums[r]
            if x==k:
                count+=1
            rem =x-k
            count+=prefix_sum.get(rem,0)
            prefix_sum[x]+=1
            r+=1
        return count

            
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Subarray Sum Equals K — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Subarray Sum Equals K ಹಿಂದಿನ intuition ಏನು?

If the running sum up to here is x and some earlier prefix summed to x − k, then the stretch between them sums to exactly k. So keep a count of every prefix sum seen; at each step add how many times x − k has appeared.

Subarray Sum Equals K (LeetCode 560) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Keep a running prefix sum x. 2. If x itself equals k, the subarray from the start counts. 3. Add how many earlier prefixes equal x − k. 4. Record x in the prefix-count map.

Subarray Sum Equals K ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(n). (Accepted approach: Prefix sum + hash map.)

Subarray Sum Equals K ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Sliding window doesn't work — values can be negative. Seeding the map with {0: 1} is the usual alternative to the x == k check.