Leetcode – Smallest Range I Solution in Python

Spread the love

The Smallest Range I problem is an interesting exercise on Leetcode that delves into array manipulation and mathematical reasoning. This comprehensive article aims to break down the problem’s statement, outline possible strategies, and offer Python solutions. We’ll also assess the time and space complexities of each proposed solution.

Table of Contents:

  1. Understanding the Problem Statement
  2. Analyzing the Problem
  3. Simple Mathematical Approach
  4. Python Implementation
  5. Complexity Analysis
  6. Conclusion

1. Understanding the Problem Statement


Given an array A of integers, for each integer A[i] we may choose any x from -K to K, and add x to A[i].

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B.


Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [4,6,3] or B=[3,3,3] or many other possibilities.

2. Analyzing the Problem

The objective is to minimize the difference between the maximum and minimum values of the array B. To do this, we should try to increase the smallest values and decrease the largest values of array A by K.

Given the flexibility to add any value from -K to K, including zero, the most significant changes we can make to the range of values in A are:

  • Add K to the smallest value
  • Subtract K from the largest value

This approach can potentially reduce the overall range of values in the array.

3. Simple Mathematical Approach

To find the smallest possible range:

  1. Identify the current range of A by subtracting its minimum value from its maximum value.
  2. Try to reduce this range by adding and subtracting K as discussed.
  3. If the adjusted range is less than zero, it means we have managed to overlap the values such that they can become equal. In this case, return 0.
  4. Otherwise, return the adjusted range.

4. Python Implementation

Using the approach described above, the problem can be elegantly solved in a few lines of Python code:

def smallestRangeI(A, K):
    return max(0, max(A) - min(A) - 2*K)

5. Complexity Analysis

Time Complexity:

  • O(n) for max(A)
  • O(n) for min(A) Thus, the total time complexity is O(n), where n is the length of the array A.

Space Complexity: O(1)
We only used a constant amount of space to store intermediate values, regardless of the input size.

6. Conclusion

The Smallest Range I problem on Leetcode is an excellent exercise to appreciate the combination of mathematical reasoning with coding. Rather than diving into intricate algorithms, sometimes a problem can be efficiently solved by logically reasoning through the given conditions and constraints. Such problems emphasize the importance of thoroughly understanding the problem statement and considering the mathematical properties of the data, before jumping into coding.

Leave a Reply