Question Bank
JavaScript Largest Difference Without Sort: Two Approaches Quiz
Difficulty: Medium
Two seeded approaches to compute the largest pairwise difference in an array without sorting (single-pass min/max and the brute-force nested loop), plus two companions on prefix tracking and a negative-numbers twist.
JavaScript Largest Difference Without Sort: Two Approaches Quiz
Two seeded approaches to compute the largest pairwise difference in an array without sorting (single-pass min/max and the brute-force nested loop), plus two companions on prefix tracking and a negative-numbers twist.
184 views
1
Implement largestDiff(arr) using a SINGLE-PASS min/max tracker. Walk the array once, keep running min and max, then return max - min. Sorting is not allowed.
Examples
Example 1:
Input: [2, 8, 24, 7, 4, 13, 4, 6, 30, 8]
Output: 28
Explanation: max is 30 and min is 2, so the largest pairwise difference is 30 - 2 = 28.Example 2:
Input: [5]
Output: 0
Explanation: With a single element, min equals max, so the difference is 0.Implement the SAME largestDiff(arr) using a nested loop that inspects every (i, j) pair and tracks the maximum Math.abs(arr[i] - arr[j]). Sorting is still not allowed.
Examples
Example 1:
Input: [2, 8, 24, 7, 4, 13, 4, 6, 30, 8]
Output: 28
Explanation: The pair (30, 2) yields the largest absolute difference.A teammate proposes Math.max(...arr) - Math.min(...arr) as a one-liner. Identify TWO real problems with this version compared to the single-pass tracker, and rewrite it to keep the brevity but fix the worst issue.
Examples
Example 1:
Input: an array of 200,000 numbers
Output: RangeError on most engines from spread arg limit
Explanation: Spread into Math.max passes every element as a separate argument and hits the engine call-stack limit around 100k-200k args.Negative-numbers twist: implement largestDiff(arr) for an array that mixes negatives and positives, and explain why the single-pass min/max algorithm still works without any change.
Examples
Example 1:
Input: [-7, 3, -2, 11, -8, 4]
Output: 19
Explanation: max is 11, min is -8, and 11 - (-8) = 19.Example 2:
Input: [-5, -1, -9, -3]
Output: 8
Explanation: All negative; max is -1, min is -9, and -1 - (-9) = 8.