Minimum Difference Between Highest and Lowest of K Scores — LeetCode 1984 Python Solution

EasyArraySortingSliding Window
Problem
#1984
Reading time
2 min

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.

Example

Input
nums = [90], k = 1
Output
0
Explanation
There is one way to pick score(s) of one student:

Python solution

Python
class Solution:
    def minimumDifference(self, nums: List[int], k: int) -> int:
        nums.sort()
        return min(nums[i + k - 1] - nums[i] for i in range(len(nums) - k + 1))

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores?
LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores is rated Easy on LeetCode.
What is the time complexity of LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores cover?
LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores is tagged Array, Sorting and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview