ExamAdda Logo

Sliding Window Maximum

Easy

You are given an integer array nums and an integer k.

There is a sliding window of size k that moves from the beginning to the end of the array.

At each position, the window contains exactly k elements.

Return an array containing the maximum element from each sliding window.

Example 1

Input

n = 8
nums = [1, 3, -1, -3, 5, 3, 6, 7]
k = 3

Output

[3, 3, 5, 5, 6, 7]

Explanation

The sliding windows and their maximum values are:

[1, 3, -1] → 3
[3, -1, -3] → 3
[-1, -3, 5] → 5
[-3, 5, 3] → 5
[5, 3, 6] → 6
[3, 6, 7] → 7

Therefore, the answer is:

[3, 3, 5, 5, 6, 7]

Example 2

Input

n = 1
nums = [1]
k = 1

Output

[1]

Explanation

There is only one window containing the single element 1.

Constraints

1 <= n <= 10^5
1 <= k <= n
-10^4 <= nums[i] <= 10^4

Hints:

Hint 1

For every window, you need to efficiently find its maximum element.

Hint 2

Maintain a deque of indices.

Keep the indices in decreasing order of their corresponding values.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 27, 2026

Last updated

Aug 27, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output