Skip to content

Commit 3daa124

Browse files
Merge pull request #15 from codewithme-py/feat/sliding-window-maximum-0239
problem solution & test 0239
2 parents 6c9637a + 8e518c8 commit 3daa124

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from collections import deque
2+
3+
4+
class Solution:
5+
def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
6+
"""
7+
Finds the maximum values in each sliding window of size k.
8+
9+
The algorithm uses a monotonic deque (double-ended queue) to achieve
10+
a time complexity of O(n), where n is the length of the nums array.
11+
12+
The monotonic deque stores indices of elements in the nums array in
13+
descending order of their values. Thus, the element with index dq[0]
14+
is always the index of the maximum element in the current window.
15+
16+
Args:
17+
nums (list[int]): Input array of integers.
18+
k (int): Size of the sliding window.
19+
20+
Returns:
21+
list[int]: List of maximum values for each window.
22+
23+
Example:
24+
>>> nums = [1, 3, -1, -3, 5, 3, 6, 7]
25+
>>> k = 3
26+
>>> Solution().maxSlidingWindow(nums, k)
27+
[3, 3, 5, 5, 6, 7]
28+
29+
Time Complexity:
30+
O(n), where n is the length of nums. Each index is added and removed
31+
from the deque at most once.
32+
33+
Space Complexity:
34+
O(k), as the deque stores at most k indices.
35+
"""
36+
result, dq = [], deque()
37+
for i in range(len(nums)):
38+
if dq and dq[0] == i - k:
39+
dq.popleft()
40+
while dq and nums[dq[-1]] < nums[i]:
41+
dq.pop()
42+
dq.append(i)
43+
if i >= k - 1:
44+
result.append(nums[dq[0]])
45+
return result
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from solutions.sliding_window_maximum_0239 import Solution
4+
5+
6+
@pytest.mark.parametrize('nums, k, expected', [
7+
([1,3,-1,-3,5,3,6,7], 3, [3,3,5,5,6,7]),
8+
([1], 1, [1]),
9+
([1, -1], 1, [1, -1]),
10+
([9, 11], 2, [11]),
11+
([4, -2], 2, [4]),
12+
])
13+
14+
def test_solution(nums: list[int], k: int, expected: list[int]) -> None:
15+
sol = Solution()
16+
assert sol.maxSlidingWindow(nums, k) == expected

0 commit comments

Comments
 (0)