Maximum of All Subarrays of Size K

You are provided with an array A containing N integers. Your task is to determine the maximum element in every contiguous subarray of size K as you move from left to right through the array.

Input:

The input begins with a single integer T, which indicates the number of test cases. For each test case, there will be two inputs: N and K, followed by an array A containing N integers.

Output:

For each test case, output a single line with N - K + 1 space-separated integers, representing the maximum elements in the K-sized subarrays.

Example:

Input:
A = [3, 2, 3], K = 2
Output:
[3, 3]
Input:
A = [3, 2, 3, 5, 1, 7], K = 3
Output:
[3, 5, 5, 7]

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^5
  • 1 <= K <= N
  • 1 <= A[i] <= 10^9

Note: You do not need to print anything, as it will be handled externally. Focus on implementing the solution function.

Additional Challenge:

Try to solve the problem in O(N) time complexity and O(K) space complexity.

AnswerBot
4mo

Find maximum element in every contiguous subarray of size K in an array.

  • Iterate through the array and maintain a deque to store the indices of elements in decreasing order.

  • Pop elements from the deque ...read more

Help your peers!
Select
Add answer anonymously...
Elgin Industries Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits