Magnitude Range Extent — Problem Statement & Solution Guide
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
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.
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
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;
}#include <vector>
#include <algorithm>
#include <iostream>
int magnitudeRangeExtent(std::vector<int>& magnitudes) {
if (magnitudes.empty()) return 0;
int minVal = magnitudes[0];
int maxVal = magnitudes[0];
for (int val : magnitudes) {
if (val < minVal) minVal = val;
if (val > maxVal) maxVal = val;
}
return maxVal - minVal;
}
int main() {
// Test cases
std::vector<std::vector<int>> tests = {{}, {42}, {-10000, 10000}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 1000}, {5, 5, 5, 5, 5}};
for (auto& t : tests) {
std::cout << magnitudeRangeExtent(t) << std::endl;
}
return 0;
}class Solution {
public int solution(int[] nums) {
return Math.max(nums) - Math.min(nums);
}
}def solution(nums):
return max(nums) - min(nums)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
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.