BackmediumStackGoogleAmazon

Pipeline Beacon Resolver 8 Solution

Problem Statement

In a distributed sensor network, a sequence of integer readings is captured from a linear array of nodes. Each reading represents the signal strength at a specific node. The system requires identifying the maximum signal strength within any contiguous subarray of exactly length k. This metric is critical for determining the peak load on the network infrastructure over a sliding window of time.

Given an array readings of integers and an integer k, return the maximum value in every contiguous subarray of size k. The result should be an array where the i-th element corresponds to the maximum value in the subarray starting at index i and ending at index i + k - 1.

For example, if readings = [1, 3, -1, -3, 5, 3, 6, 7] and k = 3, the first window is [1, 3, -1] with max 3, the second is [3, -1, -3] with max 3, and so on. The output should reflect these maxima in order.

Example 1
Input
readings = [1, 3, -1, -3, 5, 3, 6, 7], k = 3
Output
[3, 3, 5, 5, 6, 7]

Explanation: Window 1: [1, 3, -1] -> max 3. Window 2: [3, -1, -3] -> max 3. Window 3: [-1, -3, 5] -> max 5. Window 4: [-3, 5, 3] -> max 5. Window 5: [5, 3, 6] -> max 6. Window 6: [3, 6, 7] -> max 7.

Example 2
Input
readings = [10, 20, 30, 40, 50], k = 2
Output
[20, 30, 40, 50]

Explanation: Window 1: [10, 20] -> max 20. Window 2: [20, 30] -> max 30. Window 3: [30, 40] -> max 40. Window 4: [40, 50] -> max 50.

Example 3
Input
readings = [5, 5, 5, 5], k = 4
Output
[5]

Explanation: Only one window of size 4 exists: [5, 5, 5, 5]. The maximum is 5.

Example 4
Input
readings = [-1, -2, -3, -4, -5], k = 3
Output
[-1, -2, -3]

Explanation: Window 1: [-1, -2, -3] -> max -1. Window 2: [-2, -3, -4] -> max -2. Window 3: [-3, -4, -5] -> max -3.

Constraints

  • 1 <= readings.length <= 10^5
  • -10^9 <= readings[i] <= 10^9
  • 1 <= k <= readings.length
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

Pipeline Beacon Resolver 8 — Problem Statement & Solution Guide

StackMediumDFS Traversal
TimeO(n)
|
SpaceO(k)

Problem Description

In a distributed sensor network, a sequence of integer readings is captured from a linear array of nodes. Each reading represents the signal strength at a specific node. The system requires identifying the maximum signal strength within any contiguous subarray of exactly length k. This metric is critical for determining the peak load on the network infrastructure over a sliding window of time.

Given an array readings of integers and an integer k, return the maximum value in every contiguous subarray of size k. The result should be an array where the i-th element corresponds to the maximum value in the subarray starting at index i and ending at index i + k - 1.

For example, if readings = [1, 3, -1, -3, 5, 3, 6, 7] and k = 3, the first window is [1, 3, -1] with max 3, the second is [3, -1, -3] with max 3, and so on. The output should reflect these maxima in order.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Pipeline Beacon Resolver 8"

medium

WHY DOES IT MATTER?

The sliding‑window maximum pattern appears in time‑series analysis, network traffic monitoring, and any scenario where you need real‑time aggregates over a moving horizon. Mastering it demonstrates an ability to convert a seemingly quadratic problem into linear time using clever data‑structure invariants.

OPTIMIZATION CHALLENGE

The key insight is maintaining a monotonic decreasing deque so that each element is processed exactly once. By discarding elements that can never become a future maximum, you eliminate redundant comparisons and achieve amortized O(1) per step.

REAL-WORLD CONNECTION

Think of a network router that tracks the peak bandwidth usage over the last 5 seconds. As each packet arrives, the router updates a sliding window of recent measurements; the deque acts like a rolling leaderboard that instantly tells the router the current peak without rescanning the entire history.

During an interview, implement the deque logic first for index handling, then add the clean‑up steps (pop from front if out of window, pop from back while new element is larger). Write a small helper to print the deque state while debugging; it often reveals off‑by‑one window errors.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(k)

Core Theory — Why This Approach?

The problem of finding the maximum element in every contiguous subarray of size k is a classic sliding‑window challenge. A naïve solution would recompute the maximum for each window by scanning k elements, leading to O(n·k) time, which quickly becomes prohibitive when n and k are large (e.g., n ≈ 10⁶). The optimal paradigm leverages a double‑ended queue (deque) to maintain candidates for the window maximum in monotonic decreasing order. As the window slides, elements that fall out of the range are popped from the front, and any new element that is smaller than the current tail is simply appended, while larger elements purge weaker candidates from the back. This guarantees that the front of the deque always holds the index of the current window’s maximum.

The deque approach achieves O(n) overall time because each array element is inserted and removed at most once. Space usage is O(k) in the worst case, but typically far less because the deque stores only potential maxima. This linear‑time, linear‑space solution is essential for real‑time analytics on streaming data where latency and memory footprints are tightly constrained.

Interview Questions on This Problem

Q1How would you modify the sliding‑window maximum algorithm to also return the index of each maximum element?

Store indices in the deque instead of values; when you output the maximum for a window, the front of the deque gives both the value (arr[deque[0]]) and its index. Ensure you discard indices that fall outside the current window (i < i‑k+1).

Q2Can you solve the same problem using a segment tree or a binary indexed tree? What are the trade‑offs?

Yes, you can build a segment tree in O(n) and answer each window query in O(log n), yielding O(n log n) total time. This approach uses more memory (≈4n) and is slower than the O(n) deque method, but it allows arbitrary range‑max queries, not just fixed‑size windows.

Q3If the input stream is infinite and you can only store O(k) elements, how would you compute the sliding maximum?

The deque algorithm naturally fits this constraint because it never stores more than k elements; as new values arrive, you push them while discarding out‑of‑range indices, maintaining O(k) memory and O(1) amortized update per element.

Examples

Example 1

Input

readings = [1, 3, -1, -3, 5, 3, 6, 7], k = 3

Output

[3, 3, 5, 5, 6, 7]

Explanation: Window 1: [1, 3, -1] -> max 3. Window 2: [3, -1, -3] -> max 3. Window 3: [-1, -3, 5] -> max 5. Window 4: [-3, 5, 3] -> max 5. Window 5: [5, 3, 6] -> max 6. Window 6: [3, 6, 7] -> max 7.

Example 2

Input

readings = [10, 20, 30, 40, 50], k = 2

Output

[20, 30, 40, 50]

Explanation: Window 1: [10, 20] -> max 20. Window 2: [20, 30] -> max 30. Window 3: [30, 40] -> max 40. Window 4: [40, 50] -> max 50.

Example 3

Input

readings = [5, 5, 5, 5], k = 4

Output

[5]

Explanation: Only one window of size 4 exists: [5, 5, 5, 5]. The maximum is 5.

Example 4

Input

readings = [-1, -2, -3, -4, -5], k = 3

Output

[-1, -2, -3]

Explanation: Window 1: [-1, -2, -3] -> max -1. Window 2: [-2, -3, -4] -> max -2. Window 3: [-3, -4, -5] -> max -3.

Constraints

  • 1 <= readings.length <= 10^5
  • -10^9 <= readings[i] <= 10^9
  • 1 <= k <= readings.length

Optimal Approach & Strategy

Maintain a decreasing deque of indices, updating it as the window slides so each element is added and removed at most once.

Brute Force Approach

For each window, scan its k elements to find the maximum, repeating this for all n‑k+1 windows.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
      let target = 0;
      let sequenceStart = 0;
      for (let i = 0; i < nums.length; i++) {
         if (nums[i] >= 1 && nums[i] <= 10) {
            sequenceStart = i;
            break;
         }
      }
      for (let i = sequenceStart; i < nums.length; i++) {
         if (nums[i] >= 1 && nums[i] <= 10) {
            target += nums[i];
         }
      }
      return target;
   }

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

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.