Continuous Subarray Sum
LeetCode 523 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Same prefix remainder twice, ≥ 2 apart ⇒ a good subarray.
நான் 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
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.
நான் எப்படித் தீர்த்தேன்
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 FalseContinuous 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.