Smallest Range II - Problem

Imagine you have an array of numbers and you're given a magical power to transform each element! For every number in the array, you must choose to either add k or subtract k from it - no exceptions, no staying the same.

Your goal is to minimize the range (difference between maximum and minimum values) of the transformed array. This is like trying to bring all the numbers as close together as possible after applying your transformations.

Example: If you have [1, 3, 6] and k = 3, you could transform it to [4, 0, 9] (adding 3, subtracting 3, adding 3) giving a range of 9, or [4, 6, 3] (adding 3, adding 3, subtracting 3) giving a range of 3. The second choice is better!

Input: An integer array nums and an integer k
Output: The minimum possible range after transforming all elements

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1], k = 0
โ€บ Output: 0
๐Ÿ’ก Note: Single element array always has range 0, regardless of operations
example_2.py โ€” Simple Transformation
$ Input: nums = [0, 10], k = 2
โ€บ Output: 6
๐Ÿ’ก Note: We can transform to [2, 8] (both +2) giving range 6, which is better than [2, 12] or [-2, 8]
example_3.py โ€” Multiple Elements
$ Input: nums = [1, 3, 6], k = 3
โ€บ Output: 3
๐Ÿ’ก Note: Transform to [4, 6, 3] by doing +3, +3, -3. This gives range 6-3=3, which is optimal

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • 0 โ‰ค nums[i] โ‰ค 104
  • 0 โ‰ค k โ‰ค 104

Visualization

Tap to expand
๐Ÿ“ธ The Height Adjustment ChallengeOriginal Heights: [1, 3, 6] with k=3136Range = 6 - 1 = 5After Optimal Adjustments:1+3=43+3=66-3=3Range = 6 - 3 = 3 โœ“๐Ÿ”‘ Key InsightAfter sorting, the optimal solution has a"split point" where:โ€ข Left side: all get same operation (+k or -k)โ€ข Right side: all get opposite operationWe try all n-1 possible split pointsand choose the one with minimum range๐ŸŽฏ Optimal AlgorithmTime: O(n log n) | Space: O(1)Sort โ†’ Try all splits โ†’ Return minimum range
Understanding the Visualization
1
Initial Setup
We have people of different heights who must either stand on platform (+k) or crouch (-k)
2
Sort by Height
Arrange people from shortest to tallest
3
Try Split Points
Test each boundary where people to the left stand up, people to the right crouch down
4
Find Minimum Range
Choose the split that minimizes height difference between tallest and shortest
Key Takeaway
๐ŸŽฏ Key Insight: Sorting enables us to efficiently find the optimal split point where elements are divided into two groups with opposite operations, minimizing the overall range.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
19.7K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen