Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
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]
Constraints:
1 <= nums.length <= 105-104 <= nums[i] <= 1041 <= k <= nums.lengthProblem summary: You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Sliding Window · Monotonic Queue
[1,3,-1,-3,5,3,6,7] 3
[1] 1
minimum-window-substring)min-stack)longest-substring-with-at-most-two-distinct-characters)paint-house-ii)jump-game-vi)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #239: Sliding Window Maximum
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
PriorityQueue<int[]> q
= new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
int n = nums.length;
for (int i = 0; i < k - 1; ++i) {
q.offer(new int[] {nums[i], i});
}
int[] ans = new int[n - k + 1];
for (int i = k - 1, j = 0; i < n; ++i) {
q.offer(new int[] {nums[i], i});
while (q.peek()[1] <= i - k) {
q.poll();
}
ans[j++] = q.peek()[0];
}
return ans;
}
}
// Accepted solution for LeetCode #239: Sliding Window Maximum
func maxSlidingWindow(nums []int, k int) (ans []int) {
q := hp{}
for i, v := range nums[:k-1] {
heap.Push(&q, pair{v, i})
}
for i := k - 1; i < len(nums); i++ {
heap.Push(&q, pair{nums[i], i})
for q[0].i <= i-k {
heap.Pop(&q)
}
ans = append(ans, q[0].v)
}
return
}
type pair struct{ v, i int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool {
a, b := h[i], h[j]
return a.v > b.v || (a.v == b.v && i < j)
}
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
# Accepted solution for LeetCode #239: Sliding Window Maximum
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
q = [(-v, i) for i, v in enumerate(nums[: k - 1])]
heapify(q)
ans = []
for i in range(k - 1, len(nums)):
heappush(q, (-nums[i], i))
while q[0][1] <= i - k:
heappop(q)
ans.append(-q[0][0])
return ans
// Accepted solution for LeetCode #239: Sliding Window Maximum
use std::collections::VecDeque;
impl Solution {
pub fn max_sliding_window(nums: Vec<i32>, k: i32) -> Vec<i32> {
let k = k as usize;
let mut ans = Vec::new();
let mut q: VecDeque<usize> = VecDeque::new();
for i in 0..nums.len() {
if let Some(&front) = q.front() {
if i >= front + k {
q.pop_front();
}
}
while let Some(&back) = q.back() {
if nums[back] <= nums[i] {
q.pop_back();
} else {
break;
}
}
q.push_back(i);
if i >= k - 1 {
ans.push(nums[*q.front().unwrap()]);
}
}
ans
}
}
// Accepted solution for LeetCode #239: Sliding Window Maximum
function maxSlidingWindow(nums: number[], k: number): number[] {
const ans: number[] = [];
const q = new Deque();
for (let i = 0; i < nums.length; ++i) {
if (!q.isEmpty() && i - q.front()! >= k) {
q.popFront();
}
while (!q.isEmpty() && nums[q.back()!] <= nums[i]) {
q.popBack();
}
q.pushBack(i);
if (i >= k - 1) {
ans.push(nums[q.front()!]);
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.