Python 0910.py
class Solution:
def smallestRangeII(self, nums: List[int], k: int) -> int:
if len(nums) == 1:
return 0
# partition sorted values:
# left side: add k
# right side: subtract k
# in extreme cases, a side can be empty
nums.sort()
low = nums[0]
high = nums[-1]
result = high - low
for split in range(1, len(nums)):
up = max(nums[split - 1] + k, high - k)
down = min(nums[split ] - k, low + k)
result = min(result, up - down)
return result
Difficulty
and has an acceptance rate of about 38% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Math
- Sorting
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 routine computes the smallest possible difference between the maximum and minimum values of an integer array after each element has been either increased or decreased by a fixed amount k. The algorithm relies on sorting the array once and then examining every possible partition point that separates elements treated with +k from those treated with -k. By evaluating the extreme values that can arise from each partition, the method derives the minimal achievable range.
Key Steps
Single-element shortcut
When the input contains only one number, any transformation leaves the range at zero. The code returns immediately in this situation.
if len(nums) == 1:
return 0
Sorting and establishing baseline extremes
The array is sorted in ascending order, which orders the numbers for a clean left-to-right scan. The smallest (low) and largest (high) values of the original list are captured, and their difference forms the initial candidate result.
nums.sort()
low = nums[0]
high = nums[-1]
result = high - low
Scanning possible split positions
The algorithm iterates over each index that could serve as the boundary between the “add k” side (elements left of the split) and the “subtract k” side (elements right of the split). For each split, it computes the highest possible value (up) and the lowest possible value (down) after the transformation.
for split in range(1, len(nums)):
up = max(nums[split - 1] + k, high - k)
down = min(nums[split ] - k, low + k)
result = min(result, up - down)
Updating the minimal range
Within the loop, the current range (up - down) is compared against the best result found so far, and the smaller of the two replaces the stored answer. This ensures that after the final iteration, result holds the minimal achievable range.
result = min(result, up - down)
Edge Cases Addressed
The implementation explicitly handles the scenario where the input list consists of a single element, returning zero without further processing. During the partition loop, the first possible split (split = 1) treats the left side as containing only the smallest element, while the right side contains the remainder; conversely, the last split (split = len(nums) - 1) leaves the right side with only the largest element. In both extremes, one side may be empty after the transformation, and the max/min calculations gracefully accommodate these cases by comparing against the unchanged extreme values (high - k and low + k). This design guarantees correct behavior even when all elements are identical or when k is zero.
Performance Optimizations
The algorithm performs an in-place sort, avoiding the allocation of an auxiliary sorted copy and thereby reducing memory overhead. After sorting, a single linear pass evaluates every partition point, eliminating the need for nested loops or repeated scans of the array. The use of built-in max and min functions provides constant-time selection of candidate extremes, and the result is updated incrementally without storing intermediate ranges. Overall, the approach achieves the desired outcome with minimal additional data structures and a tight computational loop.
ELI5 - Simplified Explanation
Imagine having a long line of numbered building blocks lined up from the smallest number to the biggest number. Some blocks are tiny and some are very tall. The goal is to make the gap between the smallest block and the biggest block as small as possible.
To do this, every block gets a special turn. A block can either grow taller by adding a specific amount or get shorter by taking that same amount away. Think of it like deciding whether to wear platform shoes to look taller or take them off to look shorter.
The code starts by putting all the blocks in order from tiny to tall. Then, it pretends to draw a line somewhere in the middle of that row. Everything to the left of the line gets to grow taller, and everything to the right of the line must get shorter.
Since it does not know the best place to draw the line, it tries every single spot possible. For each spot, it checks the height of the new tallest block and the height of the new shortest block. It calculates the distance between those two and keeps track of the smallest distance found during all of those tries. It keeps doing this until it has looked at every possible way to split the blocks.
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++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| wisdompeak | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
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 908: Smallest Range I
- 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
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