← Microsoft bank

Microsoft · Question 35 · Queues

Sliding Window Maximum

QueuesJavacode⏱ O(n)💾 O(k)
Product-based

Problem

Given an array and window size k, return the max in each sliding window.

Approach

Deque of indices in decreasing value order; head is each window's max.

Time O(n)Space O(k)

How it works

  1. 1Evict indices that leave the window.
  2. 2Evict smaller values beaten by the newcomer.
  3. 3The head always holds the window maximum.

Sample input / output

Input:
8 3
1 3 -1 -3 5 3 6 7
Output:
[3, 3, 5, 5, 6, 7]

Constraints

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

Solution — read it, then walk it

Time O(n)Space O(k)Loops 4Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeatyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static int[]maxSlidingWindow(int[]nums, int k)if (nums == null || k<= 0) return newint[0]DEFINE n = nums.lengthDEFINE [] res = new int[n -k + 1]Deque<Integer> deque = newArrayDeque<>()for (int i = 0; i < n;i++)while(!deque.isEmpty() &&deque.peek() < i - k …deque.poll()while(!deque.isEmpty() &&nums[deque.peekLast()…deque.pollLast()deque.offer(i)if (i >= k - 1)res[i - k + 1] =nums[deque.peek()]RETURN resDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)DEFINE n = sc.nextInt();int k = sc.nextInt()DEFINE [] nums = new int[n]for (int i = 0; i <nums.length; i++)nums[i] = sc.nextInt()System.out.println(Arrays.toString(maxSlidingWindow(nums,k)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits