Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Difference Between Highest and Lowest of K Scores solution and explanation

EasyArraySliding WindowSorting6 min read66.2% acceptanceUpdated 9 Apr 2026
Minimum Difference Between Highest and Lowest of K Scores - Leetcode Weekly Contest - 1984 PythonNeetCode · 4:33 · 22K viewsWatch on YouTube
9 more videos on this problem
  1. Minimum Difference Between Highest and Lowest of K Scores - Leetcode Weekly Contest - 1984 PythonNeetCode · 4:33 · 22K views
  2. Minimum Difference Between Highest and Lowest of K Scores | Easy | Leetcode 1984 | codestorywithMIKcodestorywithMIK · 11:37 · 4K views
  3. Minimum Difference Between Highest and Lowest of K Scores | LeetCode 1984 | EnglishCodeClips with Abhishek Ranjan · 7:00 · 2K views
  4. 1984. Minimum Difference Between Highest and Lowest of K Scores (Leetcode Easy)Programming Live with Larry · 3:16 · 994 views
  5. LeetCode 1984 | Minimum Difference Between Highest and Lowest of K Scores | Array | Debug | JavaSleepy Cracker · 5:58 · 645 views
  6. 03. Minimum Difference Between Highest and Lowest of K Scores || LeetCode - 1984Code Craft - ARS · 8:04 · 551 views
  7. 1984. Minimum Difference Between Highest and Lowest of K Scores | Leetcode Daily - PythonLeetcode Daily · 8:14 · 404 views
  8. Minimum Difference Between Highest and Lowest of K Scores | LeetCode 1984 🔥 Sliding Window Study Placement · 7:59 · 397 views
  9. Minimum Difference Between Highest and Lowest of K Scores | LeetCode 1984 | Java | Developer CoderDeveloper Coder · 7:44 · 387 views
  10. Leetcode 1984. Minimum Difference between highest and lowest of k scores #leetcode #faang #interviewSuper Lazy Coder · 14:27 · 260 views

The problem

You are given a 0-indexed integer array nums, where nums[i] 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.

Example 1:

Input: nums = [90], k = 1
Output: 0
Explanation: There is one way to pick score(s) of one student:
- [90]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.

Example 2:

Input: nums = [9,4,1,7], k = 2
Output: 2
Explanation: There are six ways to pick score(s) of two students:
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.

Constraints:

  • 1 <= k <= nums.length <= 1000
  • 0 <= nums[i] <= 105

Approach overview

Problem Overview: You receive an array of student scores and an integer k. Choose any k scores such that the difference between the highest and lowest score in that group is as small as possible. Return that minimum difference.

The key observation: once the scores are ordered, the best group of k scores must appear as a contiguous segment in the sorted list. Any non‑contiguous choice would only increase the difference between the minimum and maximum values.

Approach 1: Sorting and Sliding Window (Time: O(n log n), Space: O(1) or O(n) depending on sort)

Start by sorting the scores using a standard sorting algorithm. After sorting, every valid group of k elements appears as a contiguous window. Slide a window of size k from left to right and compute nums[i + k - 1] - nums[i] for each position. Track the minimum difference across all windows.

This works because sorting ensures the smallest value in the window is at the left boundary and the largest at the right boundary. The algorithm performs a single pass after sorting, making the window scan O(n). The technique resembles a classic sliding window over a sorted array. This is the standard and most efficient approach used in interviews.

Approach 2: Dynamic Programming Style Buckets (Time: O(n + R), Space: O(R))

If score values fall within a limited range, you can avoid sorting by using buckets. Create a frequency array where the index represents a score and the value represents how many students have that score. Then simulate collecting k scores while scanning the bucket range from smallest to largest.

Maintain a running window across the bucket values while counting how many elements are currently included. Expand the right boundary until at least k scores are covered, then shrink from the left to maintain the smallest possible range. The difference between bucket indices represents the score spread.

This approach behaves similarly to sliding window but operates on value ranges instead of sorted elements. It becomes efficient when the score range R is small compared to n, though it requires additional memory for the bucket array.

Recommended for interviews: Sorting with a sliding window is the expected solution. It is simple, provably optimal for this problem, and easy to implement under time pressure. Discussing the bucket-based idea shows deeper algorithmic thinking, but interviewers typically look for the sorted window approach first.

Approach 1: Approach 1: Sorting and Sliding Window

Sort the array and use a sliding window of size k to find the minimum difference. This approach works because sorting arranges the numbers in non-decreasing order, so the subarray of size k with the minimum difference between the maximum and minimum scores will be contiguous.

The basic steps are:

  1. Sort the array.
  2. Initialize a variable to store the minimum difference and set it to a large number.
  3. Slide a window of size k across the sorted array, and for each window, calculate the difference between the highest and lowest numbers found in this window.
  4. Keep track of the minimum difference encountered across all windows.
  5. Return the minimum difference.
def min_difference(nums, k):
    nums.sort()
    return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1))

nums = [9, 4, 1, 7]
k = 2
print(min_difference(nums, k))
import java.util.Arrays;

public class Solution {
    public int minDifference(int[] nums, int k) {
        Arrays.sort(nums);
        int minDiff = Integer.MAX_VALUE;
        for (int i = 0; i <= nums.length - k; i++) {
            minDiff = Math.min(minDiff, nums[i + k - 1] - nums[i]);
        }
        return minDiff;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums = {9, 4, 1, 7};
        int k = 2;
        System.out.println(sol.minDifference(nums, k));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

int minDifference(std::vector<int>& nums, int k) {
    if (k == 1) return 0;
    std::sort(nums.begin(), nums.end());
    int minDiff = INT_MAX;
    for (int i = 0; i <= nums.size() - k; i++) {
        minDiff = std::min(minDiff, nums[i + k - 1] - nums[i]);
    }
    return minDiff;
}

int main() {
    std::vector<int> nums = {9, 4, 1, 7};
    int k = 2;
    std::cout << minDifference(nums, k) << std::endl;
    return 0;
}
function minDifference(nums, k) {
    nums.sort((a, b) => a - b);
    let minDiff = Infinity;
    for (let i = 0; i <= nums.length - k; i++) {
        minDiff = Math.min(minDiff, nums[i + k - 1] - nums[i]);
    }
    return minDiff;
}

const nums = [9, 4, 1, 7];
const k = 2;
console.log(minDifference(nums, k));
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return *(int*)a - *(int*)b;
}

int minDifference(int* nums, int numsSize, int k) {
    qsort(nums, numsSize, sizeof(int), compare);
    int minDiff = 1000000;
    for (int i = 0; i <= numsSize - k; i++) {
        int diff = nums[i + k - 1] - nums[i];
        if (diff < minDiff) {
            minDiff = diff;
        }
    }
    return minDiff;
}

int main() {
    int nums[] = {9, 4, 1, 7};
    int k = 2;
    int size = sizeof(nums) / sizeof(nums[0]);
    printf("%d\n", minDifference(nums, size, k));
    return 0;
}
using System;

public class Solution {
    public int MinDifference(int[] nums, int k) {
        Array.Sort(nums);
        int minDiff = int.MaxValue;
        for (int i = 0; i <= nums.Length - k; i++) {
            minDiff = Math.Min(minDiff, nums[i + k - 1] - nums[i]);
        }
        return minDiff;
    }

    public static void Main(string[] args) {
        Solution sol = new Solution();
        int[] nums = {9, 4, 1, 7};
        int k = 2;
        Console.WriteLine(sol.MinDifference(nums, k));
    }
}

We use Python's built-in `sort()` method to sort the list, then list comprehension is employed to calculate the minimum difference by iterating over all possible k-length segments of the array.

Complexity

Time Complexity: O(n log n) due to the sort operation.

Space Complexity: O(1) additional space.

Try this approach in the editor

Approach 2: Approach 2: Dynamic Programming Style Buckets

An alternative approach involves using a frequency array (bucket), preview typical dynamic programming styles, especially useful if the range of scores is small. The idea is to count frequencies of each score, then determine the smallest window in terms of integer value rather than index that includes k students.

The basic steps are:

  1. Create a frequency array large enough to cover the entire range of scores.
  2. Count occurrences of each score.
  3. Track how many scores are being summed and adjust window size while keeping an exact count of k students.
  4. Calculate differences on the go and update the minimum difference as needed.
def min_difference_dp(nums, k):
    max_value = max(nums)
    min_value = min(nums)
    freq = [0] * (max_value + 1)
    for num in nums:
        freq[num] += 1
    start, sum_k, min_diff = min_value, 0, float('inf')
    for end in range(min_value, max_value + 1):
        if freq[end] > 0:
            sum_k += freq[end]
            while sum_k >= k:
                min_diff = min(min_diff, end - start)
                sum_k -= freq[start]
                start += 1
    return min_diff

nums = [9, 4, 1, 7]
k = 2
print(min_difference_dp(nums, k))

This approach constructs a frequency array to dynamically track the use of indices over the range of integer values found in `nums`. Using two pointers, we adjust to always ensure at least k students are captured, updating the minimum difference when this condition is maintained.

Complexity

Time Complexity: O(n + m) where m is the range covered by `max - min`.

Space Complexity: O(m).

Try this approach in the editor

Approach 3: Sorting + Sliding Window

We can sort the students' scores in ascending order, then use a sliding window of size k to calculate the difference between the maximum and minimum values in the window, and finally take the minimum of the differences of all windows.

Why do we take the scores of k consecutive students? Because if they are not consecutive, the difference between the maximum and minimum values may remain the same or increase, but it will definitely not decrease. Therefore, we only need to consider the scores of k consecutive students after sorting.

The time complexity is O(n times log n), and the space complexity is O(log n). Here, n is the number of students.

function minimumDifference(nums: number[], k: number): number {
    nums.sort((a, b) => a - b);
    const n = nums.length;
    let ans = nums[n - 1] - nums[0];
    for (let i = 0; i + k - 1 < n; i++) {
        ans = Math.min(nums[i + k - 1] - nums[i], ans);
    }
    return ans;
}
func minimumDifference(nums []int, k int) int {
	sort.Ints(nums)
	ans := 100000
	for i := 0; i < len(nums)-k+1; i++ {
		ans = min(ans, nums[i+k-1]-nums[i])
	}
	return ans
}
impl Solution {
    pub fn minimum_difference(mut nums: Vec<i32>, k: i32) -> i32 {
        nums.sort();
        let k = k as usize;
        let mut res = i32::MAX;
        for i in 0..=nums.len() - k {
            res = res.min(nums[i + k - 1] - nums[i]);
        }
        res
    }
}
class Solution {
    /**
     * @param Integer[] $nums
     * @param Integer $k
     * @return Integer
     */
    function minimumDifference($nums, $k) {
        sort($nums);
        $ans = 10 ** 5;
        for ($i = 0; $i < count($nums) - $k + 1; $i++) {
            $ans = min($ans, $nums[$i + $k - 1] - $nums[$i]);
        }
        return $ans;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Sorting and Sliding Window

Time Complexity: O(n log n) due to the sort operation.

Space Complexity: O(1) additional space.

Approach 2: Dynamic Programming Style Buckets

Time Complexity: O(n + m) where m is the range covered by `max - min`.

Space Complexity: O(m).

Sorting + Sliding Window–

Complexity analysis

ApproachTimeSpaceWhen to Use
Sorting + Sliding WindowO(n log n)O(1) to O(n)General case; simplest and most common interview solution
Bucket / Frequency WindowO(n + R)O(R)When score values lie within a small bounded range

Frequently asked questions

Is Minimum Difference Between Highest and Lowest of K Scores easy or hard?

The problem is classified as Easy on LeetCode. The core idea is recognizing that sorting converts the problem into checking consecutive windows of size k. Once that insight is clear, the implementation is straightforward.

Minimum Difference Between Highest and Lowest of K Scores Python/Java solution

In Python or Java, sort the array using the built-in sort function and iterate from index 0 to n - k. For each index i, compute nums[i + k - 1] - nums[i] and keep the minimum result. This implementation runs in O(n log n) time and requires only a few lines of code.

How to solve Minimum Difference Between Highest and Lowest of K Scores in O(n)?

True O(n) without constraints is difficult because the values must effectively be ordered. However, if score values lie within a limited range, you can use a bucket or counting approach. Build a frequency array and slide a window across score values while maintaining at least k elements, giving O(n + R) time where R is the score range.

What is the best approach for Minimum Difference Between Highest and Lowest of K Scores?

Sorting the scores and scanning with a sliding window is the best approach. After sorting, every group of k students appears as a contiguous segment, so you only need to check the difference between nums[i + k - 1] and nums[i]. The time complexity is O(n log n) due to sorting and O(n) for the window scan.

Is Minimum Difference Between Highest and Lowest of K Scores asked at Google/Amazon/Meta?

Problems based on sorting and sliding window patterns frequently appear in interviews at companies like Amazon, Google, and Meta. This specific problem tests recognition of sorted windows and range minimization, a common pattern in array optimization questions.

What data structure is used in Minimum Difference Between Highest and Lowest of K Scores?

The primary data structure is an array. The optimal solution sorts the array and applies a sliding window across k consecutive elements. An alternative approach uses a frequency bucket array to track score counts when the value range is small.

What is the time complexity of Minimum Difference Between Highest and Lowest of K Scores?

The optimal solution runs in O(n log n) time because the array must be sorted first. After sorting, a sliding window of size k moves across the array in O(n) time. Space complexity is O(1) if sorting in place, or O(n) depending on the language's sorting implementation.

Comments

Now write it yourselfClose this page and solve Minimum Difference Between Highest and Lowest of K Scores in the editor, without looking.
Practise Minimum Difference Between Highest and Lowest of K Scores