Minimum Difference Between Highest and Lowest of K Scores
You are given a 0-indexed integer array nums, where numsi represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference. Sort the scores first, then slide a fixed length window of size k across the sorted array and compare each window's endpoints.
Constraints
- 1 ≤ k ≤ nums.length ≤ 1000
- 0 ≤ numsi ≤ 105
Example
nums = [9, 4, 1, 7], k = 22Explanation Sorted: [1, 4, 7, 9]. The windows are [1, 4] (diff 3), [4, 7] (diff 3), and [7, 9] (diff 2) — the minimum is 2.
Slide a fixed window of size 2 across the sorted array
Sorted: [1, 4, 7, 9]. Window [1, 4]: gap = 4 - 1 = 3 — best so far.
What happens in this step
sorted = [1, 4, 7, 9] window = [0, 1] (size 2) gap = sorted[1] - sorted[0] = 4 - 1 = 3 First window, so this gap of 3 starts out as the best so far.
Steps to visualize
- Sort the array first so the closest scores sit next to each other.
- Place a window of length k on the first k sorted values.
- Record the gap between the window's last and first value as the best so far.
- Slide one step right and compare the new gap to the best.
- Stop when the window reaches the end of the sorted array.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Sorted: [1, 4, 7, 9]. Window [1, 4]: gap = 4 - 1 = 3 — best so far.
What happens in this step
sorted = [1, 4, 7, 9] window = [0, 1] (size 2) gap = sorted[1] - sorted[0] = 4 - 1 = 3 First window, so this gap of 3 starts out as the best so far.
Solution
function minimumDifference(nums, k) {
if (k <= 0 || k > nums.length) {
throw new Error("k must be between 1 and nums.length");
}
const sorted = [...nums].sort((a, b) => a - b);
let minDiff = Infinity;
for (let left = 0; left + k - 1 < sorted.length; left++) {
const right = left + k - 1;
minDiff = Math.min(minDiff, sorted[right] - sorted[left]);
}
return minDiff;
}- Time
- O(n log n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [9, 4, 1, 7], k = 2 | 2 | example from the docstring |
nums = [9, 4, 1, 7], k = 4 | 8 | k === nums.length: only one window, the full range |
nums = [5, 3, 8, 1], k = 1 | 0 | k === 1: difference is always 0 |
nums = [1, 2, 3, 4, 5], k = 3 | 2 | already sorted input |
nums = [4, 4, 4, 4], k = 2 | 0 | all identical scores |
nums = [7], k = 1 | 0 | smallest valid input: single student |
nums = [90, 72, 51, 12, 10, 65, 30], k = 3 | 20 | larger, hand-verified case |
nums = [1, 2], k = 5 | throws | throws when k is larger than the array |