Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions data_structures/arrays/sliding_window_maximum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from collections import deque
from typing import List

Check failure on line 2 in data_structures/arrays/sliding_window_maximum.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

data_structures/arrays/sliding_window_maximum.py:2:1: UP035 `typing.List` is deprecated, use `list` instead


def sliding_window_maximum(nums: List[int], k: int) -> List[int]:

Check failure on line 5 in data_structures/arrays/sliding_window_maximum.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/arrays/sliding_window_maximum.py:5:56: UP006 Use `list` instead of `List` for type annotation

Check failure on line 5 in data_structures/arrays/sliding_window_maximum.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/arrays/sliding_window_maximum.py:5:34: UP006 Use `list` instead of `List` for type annotation

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: k

"""
Return a list of the maximum values in each sliding window of size k.

This algorithm runs in O(n) time using a deque to keep track of useful elements.

Parameters
----------
nums : List[int]
The input list of integers.
k : int
The window size.

Returns
-------
List[int]
A list containing the maximum of each sliding window.

Examples
--------
>>> sliding_window_maximum([1,3,-1,-3,5,3,6,7], 3)
[3, 3, 5, 5, 6, 7]
>>> sliding_window_maximum([9, 11], 2)
[11]
>>> sliding_window_maximum([4, -2], 1)
[4, -2]
>>> sliding_window_maximum([], 3)
[]
>>> sliding_window_maximum([1,2,3], 0)
[]
"""
if not nums or k <= 0:
return []

dq: deque[int] = deque()
result: List[int] = []

Check failure on line 40 in data_structures/arrays/sliding_window_maximum.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/arrays/sliding_window_maximum.py:40:13: UP006 Use `list` instead of `List` for type annotation

for i, num in enumerate(nums):
# Remove indices that are out of the current window
while dq and dq[0] <= i - k:
dq.popleft()

# Remove smaller values as they are not useful
while dq and nums[dq[-1]] < num:
dq.pop()

dq.append(i)

# Add the current max to the result once the window is of size k
if i >= k - 1:
result.append(nums[dq[0]])

return result
Loading