Sliding Window Maximum

Asked byAmazonGoogleMicrosoftSalesforceUberFacebook

Problem

Given an array and a window size k, return an array of the maximum value in each sliding window of size k as it moves from the very left of the array to the very right.

Examples

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

Constraints

  • 1 <= k <= nums.length <= 10^5

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Sliding Window pattern

A window — a contiguous subarray or substring — expands and shrinks as it moves across the input, so you track a running condition instead of recomputing it from scratch for every possible window.

Look for this pattern when

  • The problem asks for the longest/shortest/best contiguous subarray or substring meeting a condition.
  • Brute force would recompute a sum or count for every possible window — a sign that work can be shared between overlapping ranges.

Read the full Sliding Window guide →

Video walkthroughs

Original problem on LeetCode ↗

More Sliding Window problems