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.

Be the first one to answer
Add answer anonymously...
SPRINKLR Production Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter