The "Smallest Range II" interview question is a "MEDIUM" difficulty version of the previous problem. Again, you can add or subtract k from each element. But here, the choice is binary: for each nums[i], you must either do nums[i] + k or nums[i] - k. You want to find the minimum possible range (max - min). This "Smallest Range II coding problem" is much harder because the relative order of elements can change.
Meta and Amazon ask this to test sorting and greedy strategies. It requires you to realize that if you sort the array, there will be a "split point" where all elements to the left are increased by k and all elements to the right are decreased by k. Finding the best split point is the crux of the problem.
This follows the "Sorting and Greedy interview pattern".
nums.nums[n-1] - nums[0].i from 0 to n-2:
nums[0] + k and nums[i+1] - k.nums[i] + k and nums[n-1] - k.max(max_candidates) - min(min_candidates).Array: [1, 3, 6], k = 3. Sorted: [1, 3, 6].
6 - 1 = 5.[4]. Right side (-3): [0, 3].[4, 0, 3]. Range: 4 - 0 = 4.[4, 6]. Right side (-3): [3].[4, 6, 3]. Range: 6 - 3 = 3.
Smallest range is 3.The most common mistake is not sorting the array first. Another error is not considering that the original minimum (first element) and original maximum (last element) are always the core of the new min and max after the operations. Many candidates also find the split-point logic counter-intuitive and struggle to identify the four critical values at each step.
Sorting often reveals hidden properties in range and difference problems. Once sorted, you only need to check the boundaries between elements. This "Smallest Range II interview question" is a classic example of using sorting to reduce a complex combinatorial problem into a linear scan.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Append K Integers With Minimal Sum | Medium | Solve | |
| Largest Perimeter Triangle | Easy | Solve | |
| Maximum Number of Coins You Can Get | Medium | Solve | |
| Maximum Median Sum of Subsequences of Size 3 | Medium | Solve | |
| Make K-Subarray Sums Equal | Medium | Solve |