Problem 908

Abstract / Summary

Given an array and an integer k, find the smallest possible range after adding or subtracting k from each element.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0908.py

class Solution:
    def smallestRangeI(self, nums: List[int], k: int) -> int:
        return max(0, (max(nums) - min(nums)) - 2*k)
3 lines | 134 bytes | submitted September 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 74% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. Determine the largest element in the input list.

    max_val = max(nums)
  2. Determine the smallest element in the input list.

    min_val = min(nums)
  3. Compute the raw range of the original list.

    raw_range = max_val - min_val
  4. 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
  5. Clamp the result to zero to ensure the final answer cannot be negative.

    result = max(0, adjusted_range)
  6. 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.11 | σ = 2.08

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
35 links | 21 authors | 10 languages

Videos

2 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 easy 6 medium
12 solutions   September 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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