Smallest Range I — LeetCode 908 Python Solution
- Problem
- #908
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{nums} |
| Space | O(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.