Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
alternative approach using deuque, but not monotonic decreasing deque

n.place

Sep 1, 2025

This approach always guarantees that the front of the queue for a given window is the greatest in a given window, but by removing smaller elements from the front rather than the rear


class Solution {
    printMax(arr, k) {
        let result = [];
        let deque = new Deque()
        let left = 0
        let right = k - 1

        // setup
        for (let i = 0; i < right; i++) {
            while (!deque.isEmpty() && arr[deque.getFront()] < arr[i]) {
                deque.removeFront()
            }
            deque.addRear(i)
        }

        // main loop
        while (right < arr.length) {
            while (!deque.isEmpty() && (arr[deque.getFront()] < arr[right] || deque.getFront() < left)) {
                deque.removeFront()
            }
            deque.addRear(right)
            result.push(arr[deque.getFront()])
            left++;
            right++;
        }
        return result;
    }
}

0

0

Comments
Comments

On this page