Minimum Difference Between Highest and Lowest of K Scores (LeetCode 1984): Solution and Explanation

Easy
Array
Sliding window
Sorting

Pick k scores so that the highest minus the lowest is as small as possible. After sorting, the best pick is always k neighbouring scores, so one pass over windows of size k finds the answer.

Intuition

The spread of a pick depends only on its lowest and highest score. Whatever sits in between costs nothing.

Sort the scores and imagine them as dots on a number line. If a pick of k skips a dot that lies between its lowest and highest, swapping that dot in for one of the ends can only shrink the spread or keep it the same.

So the optimal pick is k consecutive dots in sorted order. There are only n - k + 1 such windows, and the spread of the window starting at i is nums[i + k - 1] - nums[i].

Approach: Sort + fixed-size sliding window

  1. Sort nums in ascending order.
  2. Start best at the full spread nums[n - 1] - nums[0], an upper bound for any pick.
  3. For every start i from 0 to n - k, set best = min(best, nums[i + k - 1] - nums[i]).
  4. Return best.

Step-by-step example

nums = [9,4,1,7], k = 2
  1. Sort: [1,4,7,9]. Start best = 9 - 1 = 8.
  2. Window [1,4]: spread 3, best = 3.
  3. Window [4,7]: spread 3, best stays 3.
  4. Window [7,9]: spread 2, best = 2.
  5. The answer is 2.

Code: Python, Java, C++

1class Solution:
2    def minimumDifference(self, nums: List[int], k: int) -> int:
3        nums.sort()
4        best = nums[-1] - nums[0]
5        for i in range(len(nums) - k + 1):
6            best = min(best, nums[i + k - 1] - nums[i])
7        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting costs O(n log n); the window pass is O(n).

Space

O(1)

Only a counter and the best value, apart from the in-place sort.

Other approaches

Brute force over combinations (time O(C(n, k) * k), space O(k))

Try every set of k scores and compute its spread. Correct, but the number of combinations explodes even for modest n.

Counting sort (time O(n + V), space O(V))

Since scores are at most 10^5, bucket them by value instead of comparison sorting, then run the same window. Linear in n plus the value range, rarely worth it at n = 1000.

Common mistakes

  • Sliding the window over the unsorted array. Neighbours by index are not neighbours by value.
  • Off-by-one in the loop bound: the last window starts at n - k, so the loop runs n - k + 1 times.
  • Forgetting the k = 1 case: every window has spread 0, so the answer is 0.
  • Starting best at 0 instead of a large value, which makes min return 0 for every input.

Frequently asked questions

Why is the best pick always k consecutive sorted scores?

Take any pick with lowest value a and highest value b. Every score between a and b in sorted order could replace a chosen score without moving a or b, so there is a pick of k neighbours with spread at most b - a.

What happens when k equals 1?

A single score is both the highest and the lowest, so every window has spread 0 and the answer is 0.

What is the time and space complexity?

O(n log n) time for sorting and O(1) extra space for the scan.