- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 47 lines of Python from the credited upstream file 3321.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from sortedcontainers import SortedList2 3 4class Solution:5 6 def findXSum(self, nums: list[int], k: int, x: int) -> list[int]:7 ans = []8 windowSum = 09 count = collections.Counter()10 top = SortedList() 11 bot = SortedList() 12 13 def update(num: int, freq: int) -> None:14 """Updates the count of num by freq and the window sum accordingly."""15 nonlocal windowSum16 if count[num] > 0: 17 if [count[num], num] in bot:18 bot.remove([count[num], num])19 else:20 top.remove([count[num], num])21 windowSum -= num * count[num]22 count[num] += freq23 if count[num] > 0:24 bot.add([count[num], num])25 26 for i, num in enumerate(nums):27 update(num, 1)28 if i >= k:29 update(nums[i - k], -1)30 31 while bot and len(top) < x:32 countB, b = bot.pop()33 top.add([countB, b])34 windowSum += b * countB35 36 while bot and bot[-1] > top[0]:37 countB, b = bot.pop()38 countT, t = top.pop(0)39 bot.add([countT, t])40 top.add([countB, b])41 windowSum += b * countB42 windowSum -= t * countT43 if i >= k - 1:44 ans.append(windowSum)45 46 return ans47