BackeasyArraysInfosys

Magnitude Range Extent Solution

Problem Statement

Given an array of integers representing signal magnitudes, calculate the absolute difference between the largest and smallest values found within the array.

Example 1
Input
[20, -10, 0, 10]
Output
30

Explanation: Step-by-step: Given the input [20, -10, 0, 10], we first find the maximum value, which is 20. Then, we find the minimum value, which is -10. The absolute difference between 20 and -10 is 30.

Example 2
Input
[7, 7, 7, 7]
Output
0

Explanation: Step-by-step: Given the input [7, 7, 7, 7], we first find the maximum value, which is 7. Then, we find the minimum value, which is also 7. The absolute difference between 7 and 7 is 0.

Constraints

  • 1 <= array.length <= 1000
  • -10^4 <= array[i] <= 10^4
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

Magnitude Range Extent — Problem Statement & Solution Guide

ArraysEasyBasic Traversal
TimeO(n)
|
SpaceO(1)

Problem Description

Given an array of integers representing signal magnitudes, calculate the absolute difference between the largest and smallest values found within the array.

Examples

Example 1

Input

[20, -10, 0, 10]

Output

30

Explanation: Step-by-step: Given the input [20, -10, 0, 10], we first find the maximum value, which is 20. Then, we find the minimum value, which is -10. The absolute difference between 20 and -10 is 30.

Example 2

Input

[7, 7, 7, 7]

Output

0

Explanation: Step-by-step: Given the input [7, 7, 7, 7], we first find the maximum value, which is 7. Then, we find the minimum value, which is also 7. The absolute difference between 7 and 7 is 0.

Constraints

  • 1 <= array.length <= 1000
  • -10^4 <= array[i] <= 10^4

Optimal Approach & Strategy

Perform a single pass through the array, maintaining track of the current minimum and maximum values encountered. This approach achieves the result in linear time, O(n) complexity, without requiring extra space.

Brute Force Approach

Sort the array in ascending order using a standard library sort method. Once sorted, subtract the first element (minimum) from the last element (maximum).

Verified 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.