easyArraysPattern: Basic Traversal
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.
Examples
Example 1:
Input:[12, 5, 8, 20, 3]
Output:17
Explanation: The maximum value is 20 and the minimum value is 3. The absolute difference is 20 - 3 = 17.
Example 2:
Input:[7, 7, 7, 7]
Output:0
Explanation: The maximum value is 7 and the minimum value is 7. The absolute difference is 7 - 7 = 0.
Example 3:
Input:[-10, 0, 10]
Output:20
Explanation: The maximum value is 10 and the minimum value is -10. The absolute difference is 10 - (-10) = 20.
Constraints
- 1 <= array.length <= 1000
- -10^4 <= array[i] <= 10^4
Time: O(n) Space: O(1)
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.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import json
def magnitude_range_extent(magnitudes):
if not magnitudes:
return 0
return max(magnitudes) - min(magnitudes)
# Verification with test cases
def run_tests():
test_cases = [
("[]", 0),
("[42]", 0),
("[-10000, 10000]", 20000),
("[1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]", 999),
("[5, 5, 5, 5, 5]", 0)
]
for inp, expected in test_cases:
data = json.loads(inp)
result = magnitude_range_extent(data)
assert result == expected
if __name__ == '__main__':
run_tests()