BackeasyArraysCognizantTCS

Magnitude Spread Calculation Solution

Problem Statement

Given an array of integers, determine the magnitude spread, defined as the difference between the largest and smallest values present within the collection.

Example 1
Input
[1, 5]
Output
4

Explanation: Step-by-step: Given the array [1, 5], we first find the largest value, which is 5. Then we find the smallest value, which is 1. The difference between the largest and smallest values is 5 - 1 = 4.

Example 2
Input
[10, 50]
Output
40

Explanation: Step-by-step: Given the array [10, 50], we first find the largest value, which is 50. Then we find the smallest value, which is 10. The difference between the largest and smallest values is 50 - 10 = 40.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^6 <= nums[i] <= 10^6
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 Spread Calculation — Problem Statement & Solution Guide

ArraysEasyBasic Traversal
TimeO(n)
|
SpaceO(1)

Problem Description

Given an array of integers, determine the magnitude spread, defined as the difference between the largest and smallest values present within the collection.

Examples

Example 1

Input

[1, 5]

Output

4

Explanation: Step-by-step: Given the array [1, 5], we first find the largest value, which is 5. Then we find the smallest value, which is 1. The difference between the largest and smallest values is 5 - 1 = 4.

Example 2

Input

[10, 50]

Output

40

Explanation: Step-by-step: Given the array [10, 50], we first find the largest value, which is 50. Then we find the smallest value, which is 10. The difference between the largest and smallest values is 50 - 10 = 40.

Constraints

  • 2 <= nums.length <= 10^4
  • -10^6 <= nums[i] <= 10^6

Optimal Approach & Strategy

A more optimized approach would be to use built-in functions to find the maximum and minimum values in one pass, then calculate the spread. This approach would be more efficient and reduce the risk of errors.

Brute Force Approach

The brute force approach would involve iterating through the array to find the maximum and minimum values, then calculating the spread. This approach would be simple to implement but may not be efficient for large arrays.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function magnitudeSpreadCalculation(nums) { return Math.abs(Math.max(...nums) - Math.min(...nums)); }

Asked in Top Tech Interviews

CognizantTCS

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.