↓Skip to main content
  1. LeetCode/

LeetCode 908: Smallest Range I

·1 min· ·
LeetCode Easy Array Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-25

  • Submissions: Wrong Answer ×5 → Accepted

Approach
#

Only the maximum and minimum matter (Math Template 4): the maximum can drop by k and the minimum rise by k, shrinking the gap by up to 2k; every other value lies between and can follow. The gap cannot go below 0.

My Attempts
#

The first four computed max + min instead of max - min; after fixing that, a gap larger than 2k forgot to subtract 2k: [9, 0], k = 3 should be 3; it returned 9.

Solution
#

class Solution:
    def smallestRangeI(self, nums: List[int], k: int) -> int:
        return max(0, max(nums) - min(nums) - 2 * k)

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Take the maximum minus the minimum, then subtract 2k.

Interview Explanation
#

Only the extremes matter: the maximum drops by k and the minimum rises by k, so the gap shrinks by up to 2k but not below 0. Time O(n).

Related

LeetCode 914: X of a Kind in a Deck of Cards
·2 mins
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 note: every card count must be divisible by one X >= 2, i.e. the GCD of all counts is at least 2
LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left
LeetCode 883: Projection Area of 3D Shapes
·1 min
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 note: the top view counts nonzero cells, and the front and side views sum each row’s and each column’s maximum
LeetCode 812: Largest Triangle Area
·2 mins
LeetCode Easy Array Math Geometry Polygons
LeetCode 812 note: with at most 50 points, enumerate every triple and take the largest shoelace area
LeetCode 628: Maximum Product of Three Numbers
·1 min
LeetCode Easy Array Math Sorting
LeetCode 628 note: after sorting there are only two candidates: the three largest, or the two smallest (negatives) times the largest
LeetCode 598: Range Addition II
·2 mins
LeetCode Easy Array Math
LeetCode 598 note: every operation covers the top-left corner, so the most-incremented cells form the intersection of all operations: min(a) × min(b)