Peak Values in Fixed-Length Subarrays
Stacks & QueuesAuto-graded · 18 test casesLast updated
Tests understanding of monotonic deques to efficiently track the largest element across consecutive fixed-size subarrays in linear time.
Peak Values in Fixed-Length Subarrays
You are given an array of integers arr and a positive integer window_size. Imagine a fixed-length window that starts at the beginning of the array and slides one position to the right at each step until it reaches the end. Your task is to determine the largest value inside the window at each position.
Write a function that returns a list containing the maximum value for each window position as it slides through the array.
Parameters
arr: A list of integers (may contain negative values)window_size: A positive integer representing the number of consecutive elements in each window
Return Value
Return a list of integers where each element is the maximum value in the corresponding window position.
Constraints
1 <= len(arr) <= 10^5-10^4 <= arr[i] <= 10^41 <= window_size <= len(arr)
Notes
- The first window covers indices
[0, window_size-1], the second covers[1, window_size], and so on - The number of windows is
len(arr) - window_size + 1 - When
window_sizeequals the array length, return a single-element list containing the overall maximum
Examples
Example 1
Input: find_window_peaks([1, 3, -1, -3, 5, 3, 6, 7], 3)
Output: [3, 3, 5, 5, 6, 7]
Example 2
Input: find_window_peaks([1], 1)
Output: [1]
Hints
Hint 1
A brute-force solution that rescans each window will be too slow for large inputs. Can you avoid rechecking elements that are no longer relevant?
Hint 2
Think about which elements can never be the maximum in any future window. If an earlier element is smaller than or equal to a later one, the earlier element is dominated.
Hint 3
Use a deque to maintain indices of potential maximum values in decreasing order of their values. The front of the deque always holds the index of the current maximum.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
The naive approach of checking every element in each window leads to O(n·k) time complexity, where n is the array length and k is the window size. With constraints allowing n and k up to 10^5, this becomes impractically slow.
The key insight is that many elements become irrelevant as the window slides. If element at index j comes before index i and has a value less than or equal to arr[i], then j can never be the maximum in any future window that contains both positions. Since i appears later, it will remain in the window longer, making j permanently dominated.
We maintain a monotonic deque storing array indices with the following properties:
- Indices appear in increasing order (left to right)
- Their corresponding values are strictly decreasing from front to back
- The front element is always the index of the current window's maximum
Algorithm Steps
For each position i in the array:
- Remove expired indices: Pop from the front any index that falls outside the current window
[i - window_size + 1, i] - Remove dominated indices: Pop from the back while the value at the back index is less than or equal to the current value
- Add current index: Append
ito the deque - Record result: Once we have a complete window (when
i >= window_size - 1), the front of the deque holds the maximum
We store indices rather than values because we need position information to determine when an element exits the window.
Correctness
The algorithm maintains an invariant: after processing index i, the deque contains exactly those indices within the current window whose values could potentially be the maximum for this or future windows. An element qualifies only if no later element in the window has a greater or equal value.
- Removing expired indices keeps only in-window candidates
- Removing dominated indices discards elements that cannot be maxima
- The strictly decreasing value property ensures the front holds the largest value
- Each true maximum is never dominated by later elements, so it always remains at the front
Complexity Analysis
Time Complexity: O(n)
Each array index is pushed to the deque exactly once and popped at most once (either from the front or back). Although a single iteration might pop multiple elements, the total number of pop operations across all iterations is bounded by 2n. This amortized analysis confirms linear time.
Space Complexity: O(k)
The deque holds at most window_size indices at any time, since it only stores in-window candidates. The output list requires O(n - k + 1) space.
Implementation
from collections import deque
from typing import List
def find_window_peaks(arr: List[int], window_size: int) -> List[int]:
candidates = deque()
result = []
for i, value in enumerate(arr):
# Remove indices outside current window
while candidates and candidates[0] <= i - window_size:
candidates.popleft()
# Remove dominated indices
while candidates and arr[candidates[-1]] <= value:
candidates.pop()
# Current index is now a candidate
candidates.append(i)
# Record maximum once we have a full window
if i >= window_size - 1:
result.append(arr[candidates[0]])
return result