← PayPal bank

PayPal · Question 52 · Queues

Sliding Window Maximum

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

Problem

Find the maximum value in each sliding window of size k in an array.

Approach

Use a deque to store indexes of useful elements in the window.

Time O(n)Space O(k)

How it works

  1. 1Evict out-of-window indices from the front.
  2. 2Evict smaller values beaten by the newcomer.
  3. 3The head always holds the window maximum.

Sample input / output

Input:
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
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 3Branches 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 [] result = newint[n - k + 1]Deque<Integer> deque = newLinkedList<>()for (int i = 0; i <nums.length; i++)while(!deque.isEmpty() &&deque.peekFirst() < …deque.pollFirst()while(!deque.isEmpty() &&nums[deque.peekLast()…deque.pollLast()deque.offerLast(i)if (i >= k - 1)result[i - k + 1] =nums[deque.peekFirst()]RETURN resultDEFINE static voidmain(String[] args)System.out.println(Arrays.toString(maxSlidingWindow(newint[]{1, 3, -1, -3, 5, 3,6, 7}, 3)))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/19

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