Python 0908.py
class Solution:
def smallestRangeI(self, nums: List[int], k: int) -> int:
return max(0, (max(nums) - min(nums)) - 2*k)
Difficulty
and has an acceptance rate of about 74% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method smallestRangeI. The method receives a list of integers nums and an integer k. Its purpose is to compute the smallest possible difference between the maximum and minimum values of the list after each element may be adjusted by at most k units up or down. The result is guaranteed to be non-negative.
Key Steps
The algorithm follows a straightforward sequence of operations:
-
Determine the largest element in the input list.
max_val = max(nums) -
Determine the smallest element in the input list.
min_val = min(nums) -
Compute the raw range of the original list.
raw_range = max_val - min_val -
Reduce the raw range by the total amount that can be shaved off from both ends, which is
2 * k.adjusted_range = raw_range - 2 * k -
Clamp the result to zero to ensure the final answer cannot be negative.
result = max(0, adjusted_range) -
Return the clamped value.
return result
All of these steps are expressed compactly in a single return statement:
return max(0, (max(nums) - min(nums)) - 2 * k)
Edge Cases Handled
The logic inherently covers several important edge conditions:
When the original range is already less than or equal to 2 * k, the subtraction yields a non-positive number. The outer max(0, …) call then forces the output to be zero, reflecting that the list can be adjusted to make all elements equal.
If k is zero, the subtraction term disappears and the method returns the original range, which is the correct minimal range when no adjustments are permitted.
When all elements in nums are identical, max(nums) and min(nums) are equal, producing a raw range of zero. The subsequent arithmetic leaves the result at zero, matching the expectation that no variation exists.
If k is large enough to completely eliminate the original spread, the subtraction may produce a negative value. The final max operation again ensures the answer is zero, representing the scenario where the list can be collapsed to a single value.
Performance Optimizations
The implementation leverages Python’s built-in max and min functions, which are implemented in C and iterate over the list with minimal overhead. By using these highly optimized primitives, the code avoids explicit Python loops and benefits from low-level speed.
The single-line return eliminates the need for intermediate variables and additional conditional statements, reducing the number of bytecode operations executed. The use of max(0, …) provides a branch-free way to enforce the non-negative constraint, which can be more efficient than an explicit if statement.
Overall, the method runs in linear time relative to the size of nums and uses only a constant amount of extra memory, making it well-suited for large input collections.
ELI5 - Simplified Explanation
Imagine a big basket full of numbered blocks. Some blocks have very large numbers and some have very small numbers. The goal is to make the gap between the biggest block and the smallest block as tiny as possible.
To do this, there is a special magic tool called k. This tool lets you add or subtract an amount up to k from any block. To make the numbers as close together as possible, you take the biggest block and shrink it down by k, and you take the smallest block and grow it up by k.
By finding the difference between the new biggest and new smallest blocks, you figure out how far apart they still are. If the new biggest block is actually smaller than the new smallest one, that just means the gap has disappeared completely, so you call it zero.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 168: Excel Sheet Column Title
- problem 171: Excel Sheet Column Number
- problem 506: Relative Ranks
- problem 561: Array Partition
- problem 628: Maximum Product of Three Numbers
- problem 306: Additive Number
- problem 307: Range Sum Query - Mutable
- problem 378: Kth Smallest Element in a Sorted Matrix
- problem 692: Top K Frequent Words
- problem 720: Longest Word in Dictionary
- problem 910: Smallest Range II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality