Problem 1984 · LeetCode 1984(opens in a new tab)
Minimum Difference Between Highest and Lowest of K Scores
EasyArrays
You are given nums, the test scores of a group of students, and a number k. Choose any k of the students. Their spread is the highest of the chosen scores minus the lowest.
Return the smallest spread you can get with a good choice of k students.
Example 1
Input: nums = [12, 3, 20, 8, 15], k = 3 Output: 7 Why: pick 8, 12 and 15: 15 − 8 = 7
2 more examples and the constraints
Example 2
Input: nums = [6, 40, 41, 11], k = 2 Output: 1 Why: 40 and 41 are only 1 apart
Example 3
Input: nums = [55], k = 1 Output: 0 Why: one score is both the highest and the lowest
Constraints
- 1 ≤ k ≤ length of nums ≤ 1,000
- 0 ≤ each score ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every lowest scoreO(n² log n)
- Sort + sliding windowO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 scores | Verdict |
|---|---|---|---|
| Try every lowest score | O(n² log n) | Correct, but sorts n times | |
| Sort + sliding window | O(n log n) | Best; one sort and one pass |
n = number of scores.
Edge cases to test
- k is 1. A single score has spread 0, so the answer is 0.
- k equals the number of scores. There is only one window: the maximum minus the minimum.
- Repeated scores. [7, 7, 2] with k = 2 gives 0, because the two 7s can be picked together.
- Only one score. [55] with k = 1 gives 0.
Common mistakes
- Sliding the window over the unsorted scores, which misses groups that are far apart in the input.
- Stopping the loop one window early or late: the last start is n − k.
- Sorting numbers as strings in TypeScript by calling
sort()with no compare function.
How to talk through it
- 1Clarify. Can k be 1 or equal to the length? Can scores repeat?
- 2Give the simple version. Fix each score as the lowest and take the next k − 1 above it; O(n² log n).
- 3Explain why neighbours win. In sorted order, a gap inside the group could be filled without widening the spread.
- 4Code sort and slide. One sort, then last minus first for every window of k.
- 5Test out loud. Run k = 1, k = n and a case with repeated scores.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?