BackmediumStackGoogleAmazon

Sensor Checkpoint Detector 27 Solution

Problem Statement

You are tasked with implementing a signal processing routine for a distributed sensor network. The system receives a linear array of integer readings, readings, and a threshold parameter K. The goal is to compute the 'Detector Value' based on the following operational logic:

  1. If the total number of readings is strictly less than K, the system is considered under-sampled. In this case, return the arithmetic sum of all elements in the array.
  2. If the number of readings is greater than or equal to K, the system operates in 'Checkpoint Mode'. You must identify the maximum subarray sum of length exactly K. This represents the peak energy window detected by the checkpoint sensors. Return this maximum sum.

Your solution must efficiently handle large input sizes by leveraging a sliding window approach over the 1D array, which can be conceptualized as a 1D grid traversal.

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

Explanation: The length of readings is 5, which is >= K (2). We calculate the sum of every contiguous subarray of length 2: - [3, 1] -> 4 - [1, 4] -> 5 - [4, 1] -> 5 - [1, 5] -> 6 The maximum sum is 6. Wait, let me re-verify. 1+5=6. So the output should be 6. Let me correct the example to be consistent. Revised Example 1: Input: readings = [3, 1, 4, 1, 5], K = 2 Output: 6 Explanation: Length 5 >= 2. Sliding window sums: 3+1=4, 1+4=5, 4+1=5, 1+5=6. Max is 6.

Example 2
Input
readings = [10, 20, 30], K = 5
Output
60

Explanation: The length of readings is 3, which is < K (5). Therefore, we return the sum of all elements: 10 + 20 + 30 = 60.

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

Explanation: The length of readings is 4, which is >= K (2). We calculate the sum of every contiguous subarray of length 2: - [-1, -2] -> -3 - [-2, -3] -> -5 - [-3, -4] -> -7 The maximum sum is -3.

Example 4
Input
readings = [5], K = 1
Output
5

Explanation: The length of readings is 1, which is >= K (1). The only subarray of length 1 is [5]. The sum is 5.

Constraints

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

Sensor Checkpoint Detector 27 — Problem Statement & Solution Guide

StackMedium2D Grid DP
TimeO(N)
|
SpaceO(K)

Problem Description

You are tasked with implementing a signal processing routine for a distributed sensor network. The system receives a linear array of integer readings, readings, and a threshold parameter K. The goal is to compute the 'Detector Value' based on the following operational logic:

1. If the total number of readings is strictly less than K, the system is considered under-sampled. In this case, return the arithmetic sum of all elements in the array.

2. If the number of readings is greater than or equal to K, the system operates in 'Checkpoint Mode'. You must identify the maximum subarray sum of length exactly K. This represents the peak energy window detected by the checkpoint sensors. Return this maximum sum.

Your solution must efficiently handle large input sizes by leveraging a sliding window approach over the 1D array, which can be conceptualized as a 1D grid traversal.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Sensor Checkpoint Detector 27"

medium

WHY DOES IT MATTER?

Monotonic stacks turn a potentially quadratic scan into a linear pass, crucial for real‑time sensor streams.

OPTIMIZATION CHALLENGE

The key is to prune both value‑based violations and age‑based expirations in a single pass.

REAL-WORLD CONNECTION

It mirrors how hardware buffers discard stale samples while keeping only the most significant recent readings.

Initialize the stack with pairs {value, index} and always check the index difference before any pop to avoid hidden bugs.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

A monotonic stack maintains elements in a strictly decreasing (or increasing) order, allowing constant‑time access to the nearest greater (or smaller) element to the left or right. By pushing each reading and popping elements that violate the monotonic property while also discarding those that fall outside the K‑window, we can determine for every index whether a larger reading exists within the next K positions in linear time. Naïve approaches iterate over each element and scan the next K entries, leading to O(N·K) time which is prohibitive for N up to 10^5. The optimal paradigm leverages the stack’s LIFO nature to amortize each element’s push and pop to O(1), achieving an overall O(N) solution.

Interview Questions on This Problem

Q1How does a monotonic stack achieve O(N) time for sliding‑window maximum/minimum problems?

Each element is pushed once and popped at most once, so total operations are bounded by 2N. This amortization yields linear time.

Q2What edge case must you handle when elements are equal in a monotonic decreasing stack?

Decide whether to keep or discard equal values; typically you pop them to maintain strict monotonicity, ensuring correct window boundaries.

Q3Why must you remove elements whose index is more than K positions behind the current index?

Elements outside the K‑window can no longer influence future decisions, and keeping them would corrupt the detector logic.

Examples

Example 1

Input

readings = [3, 1, 4, 1, 5], K = 2

Output

5

Explanation: The length of readings is 5, which is >= K (2). We calculate the sum of every contiguous subarray of length 2: - [3, 1] -> 4 - [1, 4] -> 5 - [4, 1] -> 5 - [1, 5] -> 6 The maximum sum is 6. Wait, let me re-verify. 1+5=6. So the output should be 6. Let me correct the example to be consistent. Revised Example 1: Input: readings = [3, 1, 4, 1, 5], K = 2 Output: 6 Explanation: Length 5 >= 2. Sliding window sums: 3+1=4, 1+4=5, 4+1=5, 1+5=6. Max is 6.

Example 2

Input

readings = [10, 20, 30], K = 5

Output

60

Explanation: The length of readings is 3, which is < K (5). Therefore, we return the sum of all elements: 10 + 20 + 30 = 60.

Example 3

Input

readings = [-1, -2, -3, -4], K = 2

Output

-3

Explanation: The length of readings is 4, which is >= K (2). We calculate the sum of every contiguous subarray of length 2: - [-1, -2] -> -3 - [-2, -3] -> -5 - [-3, -4] -> -7 The maximum sum is -3.

Example 4

Input

readings = [5], K = 1

Output

5

Explanation: The length of readings is 1, which is >= K (1). The only subarray of length 1 is [5]. The sum is 5.

Constraints

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

Optimal Approach & Strategy

Maintain a decreasing monotonic stack of {value, index}, pop smaller values and those older than K, and count detections in a single linear pass.

Brute Force Approach

For each index, scan the next K elements to see if a larger reading exists, resulting in O(N·K) time.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums, K) {
   if (nums.length < K) {
       return nums.reduce((a, b) => a + b, 0);
   } else {
       return nums.slice(nums.length - K).reduce((a, b) => a + b, 0);
   }
}

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.