#1984
Minimum Difference Between Highest and Lowest of K Scores
EasyArraySliding WindowSortingSortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the array first, we can ensure that the k scores we choose are adjacent in value. This allows us to minimize the difference between the highest and lowest scores efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Sort the nums array.
- 2Step 2: Initialize min_diff to a large value.
- 3Step 3: Iterate through the sorted array, checking the difference between the i-th score and the (i+k-1)-th score for all valid i.
- 4Step 4: Update min_diff with the smallest difference found.
solution.py9 lines
1# Full working Python code
2
3def minDifference(nums, k):
4 nums.sort()
5 min_diff = float('inf')
6 for i in range(len(nums) - k + 1):
7 current_diff = nums[i + k - 1] - nums[i]
8 min_diff = min(min_diff, current_diff)
9 return min_diffℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) since we are using a constant amount of extra space.
- 1Sorting the array allows us to efficiently find the minimum difference by only checking adjacent elements.
- 2The problem can be visualized as finding the smallest range in a sorted list.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.