Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 523 · Prefix Sum

Continuous Subarray Sum

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

Same prefix remainder twice, ≥ 2 apart ⇒ a good subarray.

మధ్యస్థంArrayHash TableMathPrefix SumPigeonhole Principle
LeetCode లో తెరవండి ↗

నేను Continuous Subarray Sum (LeetCode 523) ను ఇలా పరిష్కరించాను — Prefix Sum ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Two prefix sums with the same remainder mod k differ by a multiple of k, so the stretch between them sums to a multiple of k. Remember the first index each remainder appeared at; if it shows up again at least two positions later, you've found a valid subarray.

Approach

  1. 1

    Running sum; a prefix that is itself a multiple of k (after index 0) is already a hit.

  2. 2

    Look up sum % k in the map of first occurrences.

  3. 3

    If seen and the gap is more than 1, return True.

  4. 4

    Otherwise store the first index for this remainder.

నేను ఎలా పరిష్కరించాను

Prefix remainders + mapPythonO(n) time · O(k) space
class Solution:
    def checkSubarraySum(self, nums, k):
        if len(nums) < 2:
            return False
        mpp = {}
        total = 0
        for i in range(len(nums)):
            total += nums[i]
            if i != 0 and total % k == 0:
                return True
            complement = total % k
            if complement in mpp:
                if i - mpp[complement] > 1:
                    return True
            else:
                mpp[total % k] = i
        return False
స్టెప్-త్రూ లోడ్ అవుతోంది…

Continuous Subarray Sum — తరచూ అడిగే ప్రశ్నలు

Continuous Subarray Sum వెనుక ఉన్న intuition ఏమిటి?

Two prefix sums with the same remainder mod k differ by a multiple of k, so the stretch between them sums to a multiple of k. Remember the first index each remainder appeared at; if it shows up again at least two positions later, you've found a valid subarray.

Continuous Subarray Sum (LeetCode 523) ను ఎలా పరిష్కరించాలి?

1. Running sum; a prefix that is itself a multiple of k (after index 0) is already a hit. 2. Look up sum % k in the map of first occurrences. 3. If seen and the gap is more than 1, return True. 4. Otherwise store the first index for this remainder.

Continuous Subarray Sum యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(min(n, k)). (Accepted approach: Prefix remainders + map.)

Continuous Subarray Sum లో సాధారణ పొరపాట్లు ఏమిటి?

Store only the first index of each remainder — overwriting shortens the gap. The subarray needs length ≥ 2.