Sensor Checkpoint Extractor 5 — Problem Statement & Solution Guide
Problem Description
You are tasked with processing a stream of integer values representing sensor readings to compute a specific 'extractor score'. The score is defined as the sum of the next greater element for each position in the array. If no greater element exists to the right of a value, its contribution to the score is zero. Your goal is to design an efficient algorithm to calculate this total score for a given sequence of integers.
Given an array nums of length n, where nums[i] represents the sensor reading at index i, determine the sum of all nextGreater[i] values, where nextGreater[i] is the first element nums[j] such that j > i and nums[j] > nums[i]. If no such element exists, nextGreater[i] is 0.
For example, if nums = [2, 1, 5], the next greater element for 2 is 5, for 1 is 5, and for 5 is 0. The total score is 5 + 5 + 0 = 10. You must return this total score as an integer.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Sensor Checkpoint Extractor 5"
WHY DOES IT MATTER?
Next Greater Element is a classic monotonic stack pattern that appears in many real‑time analytics, stock span, and histogram problems. Mastering it equips engineers to replace quadratic scans with linear passes, dramatically improving performance on large data streams.
OPTIMIZATION CHALLENGE
The key insight is that any element smaller than the current one can never be the next greater for any earlier element, so it can be safely discarded. This one‑time discard guarantees each element is processed a constant number of times, collapsing O(n²) to O(n).
REAL-WORLD CONNECTION
Think of a conveyor belt of sensor packets where each packet looks ahead for the next higher reading to trigger an alert. Using a stack is analogous to keeping a shortlist of pending alerts that haven't been superseded, allowing the system to decide instantly as new packets arrive.
During an interview, write the stack loop first, then immediately add the pop‑while‑≤ step; forgetting this leads to incorrect NGEs for equal or smaller values. Also, compute the sum on the fly to avoid a second pass.
COMPLEXITY AT A GLANCE
O(n)O(n)Core Theory — Why This Approach?
The problem asks for the sum of the next greater element (NGE) for each index in an integer array. For each position i, we need to locate the first element to its right that is strictly larger than arr[i]; if none exists, its contribution is zero. A naive double loop scans every suffix for each i, leading to O(n²) time, which quickly becomes infeasible for n up to 10⁵ or more. The optimal paradigm leverages a monotonic stack: we traverse the array from right to left, maintaining a stack of candidate values in decreasing order. When processing arr[i], we pop all elements ≤ arr[i] because they can never serve as NGE for any earlier element. The top of the stack after popping, if any, is the NGE for arr[i]. We add that value to the running total and then push arr[i] onto the stack. This yields a linear O(n) solution because each element is pushed and popped at most once.
Interview Questions on This Problem
Q1How would you modify the algorithm to also return the indices of the next greater elements, not just their values?
Store pairs of (value, index) on the stack instead of just values. When you find the NGE for arr[i], the top of the stack gives both the value and its original index, which you can record in a result array.
Q2Can you compute the sum of previous greater elements (to the left) using a similar approach? What changes are needed?
Yes, traverse the array from left to right with a monotonic decreasing stack. For each element, pop elements ≤ current, then the stack top (if any) is the previous greater element; add its value to the sum and push the current element.
Q3If the array contains duplicate values, does the standard monotonic stack still work for next greater element sum? Explain.
It works because we pop elements that are ≤ current, ensuring that equal values are discarded; the definition requires a strictly greater element, so duplicates cannot serve as NGE and must be removed.
Examples
Input
nums = [2, 1, 5]
Output
10
Explanation: For index 0 (value 2), the next greater element is 5 (at index 2). For index 1 (value 1), the next greater element is 5 (at index 2). For index 2 (value 5), there is no greater element to the right, so its contribution is 0. Total score = 5 + 5 + 0 = 10.
Input
nums = [3, 4, 2, 1]
Output
4
Explanation: For index 0 (value 3), the next greater element is 4 (at index 1). For index 1 (value 4), there is no greater element to the right, so its contribution is 0. For index 2 (value 2), there is no greater element to the right, so its contribution is 0. For index 3 (value 1), there is no greater element to the right, so its contribution is 0. Total score = 4 + 0 + 0 + 0 = 4.
Input
nums = [1, 2, 3, 4, 5]
Output
14
Explanation: For index 0 (value 1), the next greater element is 2. For index 1 (value 2), the next greater element is 3. For index 2 (value 3), the next greater element is 4. For index 3 (value 4), the next greater element is 5. For index 4 (value 5), there is no greater element to the right, so its contribution is 0. Total score = 2 + 3 + 4 + 5 + 0 = 14.
Input
nums = [5, 4, 3, 2, 1]
Output
0
Explanation: For each element, there is no greater element to its right. Therefore, the contribution of each element is 0. Total score = 0 + 0 + 0 + 0 + 0 = 0.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- The answer is guaranteed to fit in a 64-bit integer.
Optimal Approach & Strategy
Traverse the array from right to left using a monotonic decreasing stack, popping smaller or equal elements and using the stack top as the next greater element, accumulating the sum in one pass.
Brute Force Approach
For each index, scan all elements to its right until a larger value is found, add that value (or zero) to the sum; repeat for every index.
Verified Code Solutions
function solution(nums) {
if (nums.length === k) {
return nums.reduce((a, b) => a + b, 0);
} else {
return nums.sort((a, b) => b - a).slice(0, k).reduce((a, b) => a + b, 0);
}
}class Solution {
public:
int solution(vector<int>& nums, int k) {
if (nums.size() == k) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
} else {
sort(nums.rbegin(), nums.rend());
int sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
return sum;
}
}
};class Solution {
public int solution(int[] nums, int k) {
if (nums.length == k) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
} else {
Arrays.sort(nums);
int sum = 0;
for (int i = nums.length - 1; i >= nums.length - k; i--) {
sum += nums[i];
}
return sum;
}
}
}def solution(nums, k):
if len(nums) == k:
return sum(nums)
else:
return sum(sorted(nums, reverse=True)[:k])function solution(nums) {
if (nums.length === k) {
return nums.reduce((a, b) => a + b, 0);
} else {
return nums.sort((a, b) => b - a).slice(0, k).reduce((a, b) => a + b, 0);
}
}Asked in Top Tech Interviews
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.