Home › Company-wise questions › Microsoft › Sliding Window Maximum ← Microsoft bank
Microsoft · Question 35 · Queues
Sliding Window Maximum Queues Java code ⏱ O(n) 💾 O(k)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Evict indices that leave the window. 2 Evict smaller values beaten by the newcomer. 3 The 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 Flowchart Pseudocode
Time O(n)Space O(k)Loops 4Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat yes ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static int[] maxSlidingWindow(int[] nums, int k) if (nums == null || k <= 0) return new int[0] DEFINE n = nums.length DEFINE [] res = new int[n - k + 1] Deque<Integer> deque = new ArrayDeque<>() 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 res DEFINE static void main(String[] args) java.util.Scanner sc = new java.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← Q34 · Evaluate Reverse Polish Notation Q36 · Binary Tree Inorder Traversal → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →