githubEdit

12. K Sized Subarray Maximum

βœ… GFG solution to the K Sized Subarray Maximum problem: find maximum value for each contiguous subarray of size k using deque-based sliding window technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given an array arr[] of positive integers and an integer k. Your task is to find the maximum value for each contiguous subarray of size k. Return an array of maximum values corresponding to each contiguous subarray.

A subarray is a contiguous sequence of elements within an array. The goal is to efficiently compute the maximum element in every window of size k as it slides through the array.

πŸ“˜ Examples

Example 1

Input: arr[] = [1, 2, 3, 1, 4, 5, 2, 3, 6], k = 3
Output: [3, 3, 4, 5, 5, 5, 6]
Explanation: 
1st contiguous subarray [1, 2, 3], max = 3
2nd contiguous subarray [2, 3, 1], max = 3
3rd contiguous subarray [3, 1, 4], max = 4
4th contiguous subarray [1, 4, 5], max = 5
5th contiguous subarray [4, 5, 2], max = 5
6th contiguous subarray [5, 2, 3], max = 5
7th contiguous subarray [2, 3, 6], max = 6

Example 2

πŸ”’ Constraints

  • $1 \le \text{arr.size()} \le 10^6$

  • $1 \le k \le \text{arr.size()}$

  • $0 \le \text{arr}[i] \le 10^9$

βœ… My Approach

The optimal approach uses a Deque-based Sliding Window technique to maintain indices of potentially maximum elements in the current window:

Monotonic Deque Sliding Window

  1. Initialize Variables:

    • Use a deque to store indices of array elements.

    • The deque maintains elements in decreasing order of their values.

    • Result vector to store maximum of each window.

  2. Process Each Element:

    • Remove indices from the front if they are outside the current window (index <= i - k).

    • Remove indices from the back if their corresponding values are smaller than or equal to the current element.

    • Add the current index to the deque.

  3. Extract Maximum:

    • Once we've processed at least k elements (i >= k - 1), the front of the deque contains the index of the maximum element in the current window.

    • Add this maximum value to the result.

  4. Maintain Monotonic Property:

    • The deque always maintains indices in decreasing order of their values.

    • This ensures the front always has the maximum element's index.

  5. Continue Until End:

    • Repeat for all elements to get all window maximums.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), as each element is added to and removed from the deque at most once. Although we have nested loops, each element is processed a constant number of times across all iterations.

  • Expected Auxiliary Space Complexity: O(k), as the deque stores at most k indices corresponding to the current window size. The result array requires O(n-k+1) space but that's part of the output, not auxiliary space.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Multiset-Based Approach

πŸ’‘ Algorithm Steps:

  1. Use a multiset to maintain the current window in sorted order.

  2. Insert first k elements into the multiset for the initial window.

  3. The maximum element is always the last element in the multiset.

  4. Slide the window by removing the leftmost element and adding the new element.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log k) - Log k operations for each element

  • Auxiliary Space: πŸ’Ύ O(k) - Space for the multiset

βœ… Why This Approach?

  • Simple to implement and understand

  • Automatically maintains sorted order

  • Good for dynamic range queries

πŸ“Š 3️⃣ Brute Force Approach

πŸ’‘ Algorithm Steps:

  1. Iterate through all possible windows of size k.

  2. For each window, find the maximum element by scanning all k elements.

  3. Store the maximum in the result array.

  4. Continue until all windows are processed.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n * k) - k operations for each of n-k+1 windows

  • Auxiliary Space: πŸ’Ύ O(1) - Only constant extra space

βœ… Why This Approach?

  • Simple and straightforward implementation

  • No additional data structures needed

  • Easy to debug and verify correctness

Note: This approach results in Time Limit Exceeded (TLE) for large inputs (fails ~1110/1111 test cases due to time constraints).

πŸ“Š 4️⃣ Dynamic Programming with Blocks

πŸ’‘ Algorithm Steps:

  1. Divide the array into blocks of size k.

  2. Precompute maximum from left for each block and from right.

  3. For each window, the maximum is the max of right[left] and left[right].

  4. This eliminates redundant comparisons across windows.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Three linear passes through the array

  • Auxiliary Space: πŸ’Ύ O(n) - Two additional arrays for preprocessing

βœ… Why This Approach?

  • Linear time complexity without complex data structures

  • Good for static arrays with multiple queries

  • Elegant use of preprocessing

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Deque (Sliding Window)

🟒 O(n)

🟒 O(k)

πŸš€ Optimal time complexity

πŸ”§ Requires deque understanding

πŸ” Multiset-Based

🟑 O(n log k)

🟑 O(k)

πŸ“– Clean implementation

🐌 Slower than deque

πŸ“Š Brute Force

πŸ”΄ O(n * k)

🟒 O(1)

🎯 Simple logic

⏰ Poor time complexity

πŸ”„ DP with Blocks

🟒 O(n)

🟑 O(n)

⭐ Linear time

πŸ’Ύ Extra space needed

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Deque (Sliding Window)

β˜…β˜…β˜…β˜…β˜…

πŸ“– Readability priority

πŸ₯ˆ Multiset-Based

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Small k, minimal space

πŸ₯‰ Brute Force

β˜…β˜…β˜…β˜†β˜†

🎯 Multiple queries on static array

πŸ… DP with Blocks

β˜…β˜…β˜…β˜…β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated