Array Amplitude — 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 integers representing a dataset. Your task is to compute the amplitude of this sequence. The amplitude is defined as the absolute difference between the largest and smallest values present in the sequence. This metric quantifies the total spread or range of the data points.

If the sequence contains only a single element, the amplitude is defined as 0, as there is no variation to measure.

Your function should accept an integer array nums and return an integer representing the calculated amplitude.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Array Amplitude"

easy

WHY DOES IT MATTER?

Finding min and max in one pass is a fundamental reduction pattern used in many analytics and monitoring systems where real‑time metrics like range, variance, or thresholds are needed without incurring sorting overhead.

OPTIMIZATION CHALLENGE

The insight is recognizing that max and min are associative; you can update them incrementally, eliminating the need for sorting or auxiliary data structures.

REAL-WORLD CONNECTION

In distributed monitoring, each node reports its latency; a central aggregator computes the global latency spread by tracking the smallest and largest latency observed, analogous to the amplitude calculation.

During an interview, write the initialization clearly (handle empty or single‑element arrays first), then loop with concise if‑conditions; this demonstrates both correctness and awareness of edge cases.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The amplitude of a numeric sequence is simply the range of its values, defined as |max − min|. Computing this metric requires identifying the extremal elements of the array. A naïve solution might sort the array first and then subtract the first element from the last, but sorting incurs O(N log N) time, which is unnecessary because the problem only asks for two specific values. The optimal paradigm leverages a single linear scan, maintaining running minima and maxima, which yields the answer in O(N) time and O(1) auxiliary space. This approach exemplifies the "single pass" pattern, where each element is processed exactly once, making it ideal for large datasets where memory and time budgets are tight.

On large inputs, the naive sorting approach not only wastes CPU cycles but also may cause memory overhead due to auxiliary arrays used by certain sorting algorithms. Moreover, sorting destroys the original order, which might be needed later in a pipeline. By contrast, the linear scan respects the input order and can be combined with other streaming computations (e.g., computing sum, average) without additional passes. The key insight is that the maximum and minimum are associative and commutative operations, allowing them to be aggregated incrementally.

The optimal algorithm therefore follows a deterministic pattern: initialize min and max with the first element (or appropriate sentinel values), iterate through the remaining elements, updating min if a smaller value is seen and max if a larger value is seen. After the traversal, the amplitude is max − min, with a special‑case guard for single‑element arrays returning 0. This yields the best possible asymptotic complexity for the problem.

Interview Questions on This Problem

Q1How would you compute the amplitude of an array in a single pass and why is this preferable to sorting?

Initialize min and max with the first element, then iterate through the array updating them as needed; this runs in O(N) time and O(1) space, whereas sorting costs O(N log N) time and extra space, which is unnecessary for just finding extremes.

Q2If the array can contain negative numbers and duplicates, does the algorithm change?

No. The same linear scan works because min and max are independent of sign and duplicates; the algorithm still correctly captures the smallest and largest values.

Q3How would you modify the solution to handle a stream of numbers where the total count isn’t known upfront?

Maintain running min and max variables as each number arrives; after the stream ends, compute amplitude as max − min. This works because min/max are reducible operations that don’t require the full dataset to be stored.

Examples

Example 1

Input

nums = [4, 1, 7, 2, 9]

Output

8

Explanation: Identify the minimum value in the array, which is 1. Identify the maximum value in the array, which is 9. Calculate the absolute difference: |9 - 1| = 8. Thus, the amplitude is 8.

Example 2

Input

nums = [5]

Output

0

Explanation: The array contains only one element, 5. According to the problem definition, the amplitude of a single-element array is 0.

Example 3

Input

nums = [-3, -1, -7, -2]

Output

6

Explanation: Identify the minimum value, which is -7. Identify the maximum value, which is -1. Calculate the absolute difference: |-1 - (-7)| = |-1 + 7| = |6| = 6. The amplitude is 6.

Example 4

Input

nums = [10, 10, 10, 10]

Output

0

Explanation: The minimum value is 10 and the maximum value is 10. The absolute difference is |10 - 10| = 0. Since all elements are identical, the amplitude is 0.

Constraints

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

Optimal Approach & Strategy

Perform a single linear scan, updating running min and max; this yields O(N) time and O(1) extra space. Handle the single‑element edge case by returning 0.

Brute Force Approach

Sort the array and subtract the first element from the last; this costs O(N log N) time. Alternatively, use nested loops to compare every pair, which is O(N²).

Code Solutions

JavaScript Solution
Time: O(N)
const fs = require('fs');
const data = fs.readFileSync(0, 'utf8').trim().split(/\s+/).filter(s => s.length > 0).map(Number);
if (data.length === 0) process.exit(0);
let minVal = data[0];
let maxVal = data[0];
for (const num of data) {
    if (num < minVal) minVal = num;
    if (num > maxVal) maxVal = num;
}
console.log(maxVal - minVal);

Asked in Top Tech Interviews

AmazonZomato

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.