Magnitude Range Extent — Problem Statement & Solution Guide

ArraysEasyBasic Traversal
TimeO(n)
|
SpaceO(1)

Quick Answer & Algorithm Key Takeaway

Iterating arrays and tracking min/max

TopicArrays
PatternBasic Traversal
TimeO(n)
SpaceO(1)

Problem Description

You are provided with a sequence of integer values representing discrete signal amplitudes recorded over a specific time window. Your task is to determine the total dynamic range of these signals. The dynamic range is defined as the absolute difference between the maximum amplitude and the minimum amplitude present in the sequence.

Given an array magnitudes of length n, compute the value max(magnitudes) - min(magnitudes). This metric indicates the full extent of variation within the dataset, which is critical for assessing signal fidelity and potential clipping risks in audio or sensor processing pipelines.

Return the computed range as an integer. If the array contains only a single element, the range is zero, as there is no variation between the maximum and minimum values.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Magnitude Range Extent"

easy

WHY DOES IT MATTER?

Finding extremal values in a single traversal is a fundamental pattern that appears in statistics, finance (high‑low price), and system monitoring (peak load). Mastery of this pattern demonstrates an ability to derive optimal solutions by recognizing that ordering is unnecessary for certain aggregates.

OPTIMIZATION CHALLENGE

The key insight is that the max and min can be maintained concurrently without extra passes or auxiliary data structures. By comparing each element to both current extremes, you halve the number of required traversals compared to a two‑pass approach (first for max, second for min).

REAL-WORLD CONNECTION

In distributed telemetry pipelines, a central aggregator often needs the global maximum and minimum latency across thousands of nodes. Rather than sorting each node's logs, each node streams its local min/max, and the aggregator updates a running global min/max in O(1) per report, mirroring the single‑pass algorithm.

During an interview, write the loop that updates both extremes in one line per comparison; it shows you can think compactly and avoid redundant passes. Also, explicitly initialize min to a very large value and max to a very small value to prevent logical errors on negative numbers.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem reduces to finding two extremal values – the maximum and minimum – in a list of integers. In algorithmic terms, this is a classic reduction to a single linear scan where each element updates the current max and min if it exceeds or falls below them respectively. Naïve solutions that sort the array first or use nested loops incur O(n log n) or O(n²) time, which becomes prohibitive for large n (e.g., n > 10⁶) due to both CPU cycles and memory overhead.

The optimal paradigm leverages the fact that the max‑min pair can be discovered independently of element ordering. By maintaining two variables while iterating once over the array, we achieve the lower bound of Θ(n) time – you must inspect each element at least once to guarantee correctness. This approach also uses O(1) auxiliary space, making it ideal for memory‑constrained environments such as embedded signal‑processing units.

Interview Questions on This Problem

Q1How would you compute the dynamic range of a signal array in a single pass, and why is sorting not the preferred method?

Initialize two variables, minVal = +∞ and maxVal = -∞. Iterate through the array, updating minVal = min(minVal, current) and maxVal = max(maxVal, current). After the loop, the dynamic range is maxVal - minVal. Sorting is O(n log n) and unnecessary because the extremal values can be found without ordering, yielding O(n) time and O(1) space.

Q2What edge cases must you handle when computing max‑min difference for an integer array?

Handle arrays of length 1 (range = 0), arrays containing all identical values (range = 0), and potential integer overflow when subtracting large negative from large positive values – use a larger type (e.g., long long) if the language’s int range may be exceeded.

Q3Can you extend the single‑pass technique to compute both the range and the indices of the max and min elements? How would you modify the algorithm?

Yes. Alongside minVal and maxVal, keep minIdx and maxIdx. When updating minVal, also set minIdx = current index; similarly for maxVal. This still runs in O(n) time and O(1) extra space, providing both the magnitude and positional information.

Examples

Example 1

Input

magnitudes = [12, 45, 7, 90, 33]

Output

83

Explanation: Step 1: Identify the minimum value in the array. Scanning [12, 45, 7, 90, 33], the smallest value is 7. Step 2: Identify the maximum value in the array. Scanning [12, 45, 7, 90, 33], the largest value is 90. Step 3: Calculate the difference: 90 - 7 = 83. Step 4: Return 83.

Example 2

Input

magnitudes = [-5, -10, -2, -8]

Output

8

Explanation: Step 1: Identify the minimum value. The values are all negative. The smallest (most negative) value is -10. Step 2: Identify the maximum value. The largest (least negative) value is -2. Step 3: Calculate the difference: -2 - (-10) = -2 + 10 = 8. Step 4: Return 8.

Example 3

Input

magnitudes = [42]

Output

0

Explanation: Step 1: The array contains a single element, 42. Step 2: The minimum value is 42. Step 3: The maximum value is 42. Step 4: Calculate the difference: 42 - 42 = 0. Step 5: Return 0.

Example 4

Input

magnitudes = [100, 100, 100, 100]

Output

0

Explanation: Step 1: All elements in the array are identical (100). Step 2: The minimum value is 100. Step 3: The maximum value is 100. Step 4: Calculate the difference: 100 - 100 = 0. Step 5: Return 0.

Constraints

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

Optimal Approach & Strategy

Traverse the array once, maintaining current minimum and maximum values, then compute their difference after the loop.

Brute Force Approach

Sort the array and take the difference between the last and first elements, or use two nested loops to compare every pair and track the max difference.

Code Solutions

JavaScript Solution
Time: O(n)
function magnitudeRangeExtent(magnitudes) {
  if (magnitudes.length <= 1) return 0;
  let min = magnitudes[0];
  let max = magnitudes[0];
  for (let i = 1; i < magnitudes.length; i++) {
    if (magnitudes[i] < min) min = magnitudes[i];
    if (magnitudes[i] > max) max = magnitudes[i];
  }
  return max - min;
}

Asked in Top Tech Interviews

Infosys

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.