BackhardStackRazorpayZomato

Centroid Tree Metric Engine Solution

Problem Statement

You are given an array of N integers and a window size K. For every contiguous subarray of length K, determine the maximum element. The input consists of two lines: the first contains N and K, the second contains the N integers. The output is a single line with N-K+1 integers separated by spaces, each representing the maximum of the corresponding window. The problem can be solved in O(N) time using a monotonic queue that maintains candidates for the maximum in the current window.

Example 1
Input
5 3 1 3 -1 -3 5
Output
3 3 5

Explanation: Window 1: [1,3,-1] → max 3 Window 2: [3,-1,-3] → max 3 Window 3: [-1,-3,5] → max 5 Result: 3 3 5

Example 2
Input
8 4 2 1 5 3 6 4 7 2
Output
5 6 6 7 7

Explanation: Window 1: [2,1,5,3] → max 5 Window 2: [1,5,3,6] → max 6 Window 3: [5,3,6,4] → max 6 Window 4: [3,6,4,7] → max 7 Window 5: [6,4,7,2] → max 7 Result: 5 6 6 7 7

Example 3
Input
4 2 -5 -2 -3 -1
Output
-2 -2 -1

Explanation: Window 1: [-5,-2] → max -2 Window 2: [-2,-3] → max -2 Window 3: [-3,-1] → max -1 Result: -2 -2 -1

Example 4
Input
6 1 10 20 30 40 50 60
Output
10 20 30 40 50 60

Explanation: Each window contains a single element, so the maximum is the element itself. Result: 10 20 30 40 50 60

Constraints

  • 1 <= N <= 100000
  • 1 <= K <= N
  • -1000000000 <= arr[i] <= 1000000000
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Centroid Tree Metric Engine — Problem Statement & Solution Guide

StackHardMonotonic Queue Sliding Horizon
TimeO(N)
|
SpaceO(K)

Problem Description

You are given an array of N integers and a window size K. For every contiguous subarray of length K, determine the maximum element. The input consists of two lines: the first contains N and K, the second contains the N integers. The output is a single line with N-K+1 integers separated by spaces, each representing the maximum of the corresponding window. The problem can be solved in O(N) time using a monotonic queue that maintains candidates for the maximum in the current window.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Centroid Tree Metric Engine"

hard

WHY DOES IT MATTER?

The deque pattern transforms a quadratic problem into linear time, which is critical for large-scale data streams and real-time analytics. It eliminates redundant comparisons by discarding dominated elements, ensuring that only relevant candidates are kept for future windows.

OPTIMIZATION CHALLENGE

The core insight is that once an element is smaller than a newer element, it can never be a maximum for any future window that includes the newer element. By removing such elements from the deque, we keep the data structure size bounded and operations constant time.

REAL-WORLD CONNECTION

In high-frequency trading, traders need the maximum price over the last N ticks to trigger alerts. A deque-based sliding window can process millions of ticks per second with minimal latency, directly influencing trading decisions and risk management.

When implementing, always store indices rather than values in the deque. This allows you to check whether an element has slid out of the window by comparing its index to the current window start, avoiding costly value comparisons.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(K)

Core Theory — Why This Approach?

Sliding window maximum is a classic problem that asks for the maximum element in every contiguous subarray of length K in an array of N integers. The naive approach scans each window independently, leading to an O(NK) time complexity, which becomes infeasible when N and K are large (e.g., N=10^6). The optimal solution leverages a double-ended queue (deque) to maintain candidate indices in decreasing order of their values. As the window slides, the deque allows constant-time insertion of the new element, removal of elements that fall outside the window, and retrieval of the current maximum from the front of the deque. This yields an overall O(N) time complexity while using O(K) auxiliary space.

The key insight is that an element that is smaller than a later element can never be the maximum for any future window that includes the later element. Therefore, we can discard such elements from consideration, keeping the deque compact. Each array element is inserted and removed at most once, guaranteeing linear time. This pattern is a cornerstone of many online and streaming algorithms where maintaining a running statistic over a sliding window is required.

In distributed systems, similar techniques are used for real-time monitoring, where metrics are aggregated over recent time windows. The deque-based approach ensures low latency and minimal memory overhead, making it suitable for high-throughput environments such as log analytics or financial tick processing.

Interview Questions on This Problem

Q1How would you modify the sliding window maximum algorithm to handle a variable window size that changes during runtime?

You can maintain two deques: one for the current window and another for the next window. When the window size increases, you push new elements into the second deque and merge them when the size stabilizes. For decreasing size, you pop from the front of the first deque until the window size matches. This approach keeps O(1) amortized updates per element.

Q2A fintech platform needs to compute the maximum transaction amount over the last 5 minutes for each user in real time. What data structure would you recommend and why?

Use a time-indexed deque per user, storing pairs of (timestamp, amount). As new transactions arrive, push them to the back and pop from the front any entries older than 5 minutes. The front of the deque holds the maximum for the current window, ensuring O(1) query time and O(K) space per user.

Q3During a coding interview, the interviewer asks you to explain the time complexity of the sliding window maximum algorithm. How would you justify it?

Each element is inserted into the deque once and removed at most once. All operations on the deque (push, pop, front) are O(1). Therefore, across N elements, we perform O(N) operations, leading to O(N) time. The deque holds at most K elements, so the space complexity is O(K).

Examples

Example 1

Input

5 3
1 3 -1 -3 5

Output

3 3 5

Explanation: Window 1: [1,3,-1] → max 3 Window 2: [3,-1,-3] → max 3 Window 3: [-1,-3,5] → max 5 Result: 3 3 5

Example 2

Input

8 4
2 1 5 3 6 4 7 2

Output

5 6 6 7 7

Explanation: Window 1: [2,1,5,3] → max 5 Window 2: [1,5,3,6] → max 6 Window 3: [5,3,6,4] → max 6 Window 4: [3,6,4,7] → max 7 Window 5: [6,4,7,2] → max 7 Result: 5 6 6 7 7

Example 3

Input

4 2
-5 -2 -3 -1

Output

-2 -2 -1

Explanation: Window 1: [-5,-2] → max -2 Window 2: [-2,-3] → max -2 Window 3: [-3,-1] → max -1 Result: -2 -2 -1

Example 4

Input

6 1
10 20 30 40 50 60

Output

10 20 30 40 50 60

Explanation: Each window contains a single element, so the maximum is the element itself. Result: 10 20 30 40 50 60

Constraints

  • 1 <= N <= 100000
  • 1 <= K <= N
  • -1000000000 <= arr[i] <= 1000000000

Optimal Approach & Strategy

Maintain a deque of indices in decreasing order of values. As the window slides, pop indices outside the window from the front and remove smaller values from the back before inserting the new index. The front of the deque gives the current maximum in O(1).

Brute Force Approach

For each window, iterate over its K elements to find the maximum, resulting in O(NK) time. This is simple but too slow for large N and K.

Verified Code Solutions

JavaScript Solution
Time: O(N)
const fs=require('fs');const input=fs.readFileSync(0,'utf8').trim().split(/\s+/).map(Number);let idx=0;const N=input[idx++];const K=input[idx++];const a=input.slice(idx,idx+N);const dq=[];const res=[];for(let i=0;i<N;i++){while(dq.length&&dq[0]<=i-K)dq.shift();while(dq.length&&a[dq[dq.length-1]]<=a[i])dq.pop();dq.push(i);if(i>=K-1)res.push(a[dq[0]]);}console.log(res.join(' '));

Asked in Top Tech Interviews

RazorpayZomato

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.