File: smallest-range-i/solution.py

Date: 2026-06-06

Time: 19:09

smallest-range-i/solution.py

Purpose

This file solves LeetCode 908 — Smallest Range I. Given an integer array nums and an integer k, you can add any value in [-k, k] to each element (independently). The goal is to minimize the score, defined as max(nums) - min(nums) after adjustments.

Key Components

Solution.smallestRangeI(nums, k) — The only method. It computes the answer in a single expression:


return max(0, max(nums) - min(nums) - 2 * k)

The contract: given a non-empty list of integers and a non-negative integer k, return the minimum possible difference between the largest and smallest elements after each element is independently adjusted by at most k.

Patterns

Closed-form math instead of simulation. The solution skips any actual adjustment of array elements. The key insight: you can shrink the gap between max(nums) and min(nums) by at most 2*k — push the minimum up by k and pull the maximum down by k. If 2*k exceeds the original gap, the gap collapses to zero (you can make all elements equal), hence the max(0, ...) clamp.

This is characteristic of "greedy insight" problems where the optimal strategy has a direct formula.

Dependencies

Imports: typing.List — used only for the type annotation. No algorithmic dependencies.

Imported by: The test_solution.py in the same directory. The massive "Imported By" list in the prompt is an artifact of the repo's test infrastructure importing a shared test harness, not this specific solution.

Flow

1. Compute max(nums) and min(nums) — two linear scans (or one fused pass internally).

2. Subtract 2 * k from the spread.

3. Clamp to zero if negative.

Total: O(n) time, O(1) space.

Invariants

Error Handling

None. The function trusts its inputs match LeetCode constraints. An empty nums would raise ValueError from max()/min() on an empty sequence — this is the correct Python behavior and no guard is needed given the problem contract.

Topics to Explore

Beliefs