KatInterview

Peak Values in Fixed-Length Subarrays

Stacks & QueuesAuto-graded · 18 test cases
HardAuto-gradedStacks & Queuesdequesliding-windowmonotonic-queue

Last 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^4
  • 1 <= 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_size equals 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.