Smallest Range I — LeetCode 908 Python Solution

EasyArrayMath
Problem
#908
Reading time
2 min

The problem

You are given an integer array nums and an integer k. In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, 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 smallestRangeI(self, nums: List[int], k: int) -> int:
        mx, mi = max(nums), min(nums)
        return max(0, mx - mi - k * 2)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 908. Smallest Range I is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 908. Smallest Range I?
LeetCode 908. Smallest Range I is rated Easy on LeetCode.
What is the time complexity of LeetCode 908. Smallest Range I?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 908. Smallest Range I?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 908. Smallest Range I cover?
LeetCode 908. Smallest Range I is tagged Array and Math 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