Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Friday, December 4, 2026

Sliding Window Maximum – Monotonic Deque vs. Max-Heap in Java


Problem:  


Given an integer array nums and a sliding window of size k moving from the left of the array to the right one position at a time, return an array of the maximum value inside each window of size k.

    Window count: For an array of length n and window size k (with 1 up to k up to n), there are n - k + 1 windows.

    Example: For nums = [1, 3, -1, -3, 5, 3, 6, 7] and k = 3 

    the windows [1, 3, -1], [3, -1, -3], [-1, -3, 5], [-3, 5, 3], [5, 3, 6], and [3, 6, 7] produce [3, 3, 5, 5, 6, 7].
    

Approach 1: Monotonic Decreasing Deque – O(n) Time


    Store indices in an ArrayDeque such that their corresponding array values stay in decreasing order from front to back. The front of the deque always holds the index of the current window's maximum.

        Evict smaller/equal tail elements: When considering index i, pop indices from the back while a[dq.getLast()] <= a[i]. Those older, smaller elements can never become a future maximum once a[i] is present.

        Evict out-of-window front elements: As the window advances to i, any index less than or equal to i - k has fallen outside the current window and is removed from the front.

        Complexity: Each index is pushed and popped at most once, giving O(n) time and O(k) space.


        public int[] maxSlidingWindow(int[] a, int k) {
            int res[] = new int[a.length - k + 1];
            Deque<Integer> dq = new ArrayDeque<>();
            for (int i = 0; i < k; ++i) {
                while (!dq.isEmpty() && a[dq.getLast()] <= a[i]) dq.removeLast();
                dq.add(i);
            }
            res[0] = a[dq.peek()];
            for (int i = k; i < a.length; ++i) {
                if (!dq.isEmpty() && dq.getFirst() <= i - k) dq.removeFirst();
                while (!dq.isEmpty() && a[dq.getLast()] <= a[i]) dq.removeLast();
                dq.add(i);
                res[i - k + 1] = a[dq.peek()];
            }
            return res;
        }

    Approach 2: Lazy Deletion with Two Max-Heaps – O(n log n) Time


    Standard Java PriorityQueue supports O(log n) insertion and head removal, but arbitrary element removal takes O(n). Instead, track outgoing elements in a second max-heap (leftpq) and discard matching stale peaks lazily before reading the current maximum.

        Why .equals() matters: PriorityQueue<Integer> stores boxed Integer objects rather than primitives. Because Java caches Integer instances only over a limited range (by default -128 to 127), comparing two Integer objects with == can fail outside that cached range by checking reference identity instead of numeric value. Use .equals() when comparing Integer peaks.

        Complexity: Each element enters and leaves the heaps at most once, giving O(n log n) time and O(n) space.

        public int[] maxSlidingWindow(int[] a, int k) {
            int res[] = new int[a.length - k + 1];
            int itr = 1;
            PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
            for (int i = 0; i < k && i < a.length; ++i)
                pq.add(a[i]);
            res[0] = pq.peek();
            int left = 0;
            PriorityQueue<Integer> leftpq = new PriorityQueue<>(Collections.reverseOrder());
            leftpq.add(a[0]);
            for (int i = k; i < a.length; ++i) {
                while (!leftpq.isEmpty() && leftpq.peek().equals(pq.peek())) {
                    pq.poll();
                    leftpq.poll();
                }
                pq.add(a[i]);
                leftpq.add(a[i - k + 1]);
                res[itr++] = pq.peek();
            }
            return res;
    }

     

0 Comments:

Post a Comment

Stats