Sliding Window Minimum and Maximum

viaLeetCode

Problem: Given an array and a window size m, find the minimum and maximum element in every contiguous window of size m as it slides across the array.

Constraints: Array length up to 10^5, window size 1 <= m <= array length.

Example: arr = [1,3,-1,-3,5,3,6,7], m=3 -> max per window: [3,3,5,5,6,7]; min per window: [-1,-3,-3,-3,3,3].

Approach: Use a monotonic deque per direction (one for max, one for min): push new indices while popping from the back any indices whose values are dominated by the new element, and pop from the front any indices that have fallen out of the current window. Each element is pushed/popped at most once, giving O(n) time and O(m) space.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account