BackmediumLinked ListAdobeInfosys

Monotonic Range Extent Solution

Problem Statement

Given an array or sequence of length N representing numerical values or system metrics, compute the monotonic range extent according to the target algorithm rules.

Example 1
Input
[1, 2, 3, 4, 5]
Output
20

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we first find the maximum sum subarray, which is the sum of all elements in the array. Then, we find the minimum sum subarray, which is 0. The monotonic range extent is the difference between the maximum sum subarray and the minimum sum subarray, which is 20.

Example 2
Input
[-1, -2, -3, -4, -5]
Output
0

Explanation: Step-by-step: with input [-1, -2, -3, -4, -5], we first find the maximum sum subarray, which is the sum of all elements in the array. Then, we find the minimum sum subarray, which is the sum of all negative numbers in the array. The monotonic range extent is the difference between the maximum sum subarray and the minimum sum subarray, which is 0.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)
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

Monotonic Range Extent — Problem Statement & Solution Guide

Linked ListMediumFloyd Cycle Detection
TimeO(N)
|
SpaceO(1)

Problem Description

Given an array or sequence of length N representing numerical values or system metrics, compute the monotonic range extent according to the target algorithm rules.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Monotonic Range Extent"

medium

WHY DOES IT MATTER?

Detecting longest monotonic stretches is a fundamental pattern for time‑series analysis, trend detection, and performance monitoring, where you often need to know how long a metric has been consistently rising or falling.

OPTIMIZATION CHALLENGE

The key insight is that monotonicity is a property that can be validated incrementally; you never need to re‑examine earlier elements once a break is found, allowing a single linear pass with constant auxiliary state.

REAL-WORLD CONNECTION

In distributed systems, a monotonic range can model a period during which latency steadily improves (or degrades) before a configuration change resets the trend, helping engineers pinpoint root causes of performance regressions.

During an interview, code the solution as a single loop that updates two counters and a global max – this keeps the implementation short, avoids off‑by‑one errors, and demonstrates mastery of sliding‑window thinking.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The monotonic range extent problem asks for the length (or indices) of the longest contiguous sub‑sequence that is either entirely non‑decreasing or entirely non‑increasing. A naïve solution would examine every possible sub‑array, checking monotonicity in O(N) time per sub‑array, which leads to O(N^3) overall for an array of size N – completely infeasible for N in the order of 10^5 or larger. The optimal paradigm leverages the fact that monotonicity is a local property: once a break in monotonic order is encountered, the current run must end and a new run can start. By scanning the input once while maintaining two counters – one for the current increasing run and one for the current decreasing run – we can update the global maximum in constant time per element, achieving linear time.

This approach is a classic example of a sliding‑window / two‑pointer technique applied to a one‑dimensional stream. The window expands while the monotonic condition holds and contracts instantly when it fails, without ever revisiting elements. Because we only store a few integer counters and possibly the start index of the best range, the space usage stays O(1). The same logic extends naturally to linked lists, where we traverse node‑by‑node instead of index‑by‑index, preserving the O(N) time and O(1) auxiliary space guarantees.

Interview Questions on This Problem

Q1How would you modify the algorithm to return the start and end indices (or node references) of the longest monotonic sub‑array instead of just its length?

Maintain variables for the start index of the current run and update global start/end whenever the current run length exceeds the best seen so far. When a monotonic break occurs, reset the current start to the previous element (the point of break) and continue.

Q2Can the algorithm be adapted to handle "strictly" monotonic sequences (no equal elements) and what changes are required?

Replace the non‑decreasing (<=) and non‑increasing (>=) checks with strict < and > comparisons. The rest of the logic stays identical; only the condition that triggers a run reset changes.

Q3Explain how you would solve the problem if the input were a singly linked list and you could only use O(1) extra space.

Traverse the list node by node, keeping the same two counters and a pointer to the start node of the current run. When the monotonic condition fails, move the start pointer to the previous node (the one that caused the break) and reset the appropriate counter. No additional containers are needed, preserving O(1) space.

Examples

Example 1

Input

[1, 2, 3, 4, 5]

Output

20

Explanation: Step-by-step: with input [1, 2, 3, 4, 5], we first find the maximum sum subarray, which is the sum of all elements in the array. Then, we find the minimum sum subarray, which is 0. The monotonic range extent is the difference between the maximum sum subarray and the minimum sum subarray, which is 20.

Example 2

Input

[-1, -2, -3, -4, -5]

Output

0

Explanation: Step-by-step: with input [-1, -2, -3, -4, -5], we first find the maximum sum subarray, which is the sum of all elements in the array. Then, we find the minimum sum subarray, which is the sum of all negative numbers in the array. The monotonic range extent is the difference between the maximum sum subarray and the minimum sum subarray, which is 0.

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)

Optimal Approach & Strategy

Traverse the sequence once, maintaining counters for the current increasing and decreasing runs and a global maximum. Reset counters only when the monotonic condition breaks, achieving O(N) time and O(1) space.

Brute Force Approach

Check every possible sub‑array, verify if it is monotonic, and keep the longest length. This requires O(N^3) time because there are O(N^2) sub‑arrays and each check can be O(N).

Verified Code Solutions

JavaScript Solution
Time: O(N)
function monotonicRangeExtent(nums) {
      let maxSum = 0;
      let minSum = 0;
      for (let num of nums) {
         maxSum = Math.max(maxSum + num, num);
         minSum = Math.min(minSum + num, num);
      }
      return maxSum - minSum;
   }

Asked in Top Tech Interviews

AdobeInfosys

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.