All problems
HardSliding Window

Sliding Window Maximum

googleamazonmetamicrosoftbloomberguberapple

You are given an array of integers nums and an integer k representing the size of a sliding window. The window moves from the very left of the array to the very right, one position at a time. Return an array of the maximum value in each window position.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7      3
 1 [3  -1  -3] 5  3  6  7      3
 1  3 [-1  -3  5] 3  6  7      5
 1  3  -1 [-3  5  3] 6  7      5
 1  3  -1  -3 [5  3  6] 7      6
 1  3  -1  -3  5 [3  6  7]     7

Example 2:

Input: nums = [1], k = 1
Output: [1]
Explanation: The only window contains the single element 1.

Example 3:

Input: nums = [9,11], k = 2
Output: [11]
Explanation: The single window [9,11] has maximum 11.

Examples

Example 1

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

Output: [3,3,5,5,6,7]

Explanation: As the window slides from left to right, the maximum in each window of size 3 is [3,3,5,5,6,7].

Example 2

Input: nums = [1], k = 1

Output: [1]

Explanation: The only window contains the single element 1.

Example 3

Input: nums = [9,11], k = 2

Output: [11]

Explanation: The single window [9,11] has maximum 11.

Constraints

  • -1 <= nums.length <= 10^5
  • --10^4 <= nums[i] <= 10^4
  • -1 <= k <= nums.length

Optimal Complexity

Time

O(n)

Space

O(k)

Practice this problem with an AI interviewer

TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.

Start a free interview