Smallest Range II — LeetCode 910 Python Solution

MediumGreedyArrayMathSorting
Problem
#910
Pattern
Greedy
Reading time
2 min

The problem

You are given an integer array nums and an integer k. For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.

Example

Input
nums = [1], k = 0
Output
0
Explanation
The score is max(nums) - min(nums) = 1 - 1 = 0.

Python solution

Python
class Solution:
    def smallestRangeII(self, nums: List[int], k: int) -> int:
        nums.sort()
        ans = nums[-1] - nums[0]
        for i in range(1, len(nums)):
            mi = min(nums[0] + k, nums[i] - k)
            mx = max(nums[i - 1] + k, nums[-1] - k)
            ans = min(ans, mx - mi)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n), where n is the length of the array auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 910. Smallest Range II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 910. Smallest Range II?
LeetCode 910. Smallest Range II is rated Medium on LeetCode.
What is the time complexity of LeetCode 910. Smallest Range II?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 910. Smallest Range II?
The Python solution on this page uses O(\log n), where n is the length of the array auxiliary space.
What topics does LeetCode 910. Smallest Range II cover?
LeetCode 910. Smallest Range II is tagged Greedy, Array, Math and Sorting 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