Back to challenges
Hard 0 solved 0% acceptance

Sliding Window Maximum

Report the maximum of every window of k numbers.

What you'll learn

  • Maintain a deque of window candidates
  • Remove values that leave the window
  • Get every window maximum in O(n)

Problem

Slide a window of size k across the list one step at a time and report the maximum inside each window. A deque keeps this O(n).

Implement window_maximums(numbers, k).

Input

numbers: The list of integers. k: The window size.

Output

Return the maximum of each window, left to right.

Constraints

1 ≤ k ≤ length ≤ 200,000

Examples

Example 1
Input:
k = 3
numbers = [1, 3, -1, -3, 5, 3, 6, 7]

Expected output:
expected = [3, 3, 5, 5, 6, 7]
Input:
long long k = 3;
std::vector<long long> numbers = {1, 3, -1, -3, 5, 3, 6, 7};

Expected output:
std::vector<long long> expected = {3, 3, 5, 5, 6, 7};
Input:
long k = 3;
long[] numbers = new long[] {1, 3, -1, -3, 5, 3, 6, 7};

Expected output:
long[] expected = new long[] {3, 3, 5, 5, 6, 7};

Explanation

Windows [1,3,-1], [3,-1,-3], [-1,-3,5], … have maxima 3, 3, 5, 5, 6, 7.

Example 2
Input:
k = 1
numbers = [4, 2]

Expected output:
expected = [4, 2]
Input:
long long k = 1;
std::vector<long long> numbers = {4, 2};

Expected output:
std::vector<long long> expected = {4, 2};
Input:
long k = 1;
long[] numbers = new long[] {4, 2};

Expected output:
long[] expected = new long[] {4, 2};

Explanation

Windows of one element are the elements themselves: [4, 2].

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

The maximum can disappear when it leaves the window, so you need a structure that updates by both value and index.

Hint 2

Keep candidate indices in decreasing order of their values, dropping anything outside the current window.

Hint 3

Watch the first full window and windows of size one; every answer must correspond to a fully formed window.

Expected complexity

O(n) time, O(k) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.