Minimum Difference Between Largest and Smallest Value in Three Moves

MediumGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums. In one move you may pick any element and change it to any integer value. Using at most three moves, minimize the difference between the largest and smallest values in the array. Return that minimum difference. Arrays with four or fewer elements can always be made all-equal, giving 0. Aim for O(n log n) (or O(n) with partial selection).

Examples

Input: nums = [5,3,2,4]
Output: 0
Change 5, 3, and 2 into 4; every value is 4.
Input: nums = [1,5,0,10,14]
Output: 1
Change 5, 10, and 14 to 1, leaving [1,1,0,1,1] with a difference of 1.
Input: nums = [3,100,20]
Output: 0
Three elements can all be made equal.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems