Minimum Operations to Make Subarray Elements Equal - Problem

You are given an integer array nums and an integer k. Your goal is to find the minimum number of operations needed to make at least one subarray of size k have all elements equal.

In each operation, you can increase or decrease any element in the array by exactly 1.

Example: If nums = [1, 3, 5, 4] and k = 3, you need to find the cheapest way to make either [1, 3, 5] or [3, 5, 4] have all equal elements.

The key insight is that for any subarray, the optimal target value is the median of that subarray, as it minimizes the total distance to all elements.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 3, 5, 4], k = 3
โ€บ Output: 2
๐Ÿ’ก Note: We can choose subarray [3, 5, 4]. Sorted: [3, 4, 5], median = 4. Operations: |3-4| + |5-4| + |4-4| = 1 + 1 + 0 = 2. This is better than subarray [1, 3, 5] which would need 4 operations.
example_2.py โ€” All Equal
$ Input: nums = [2, 2, 2, 2], k = 2
โ€บ Output: 0
๐Ÿ’ก Note: Any subarray of size 2 already has all elements equal, so no operations are needed.
example_3.py โ€” Single Element Subarray
$ Input: nums = [1, 5, 9], k = 1
โ€บ Output: 0
๐Ÿ’ก Note: When k = 1, any subarray of size 1 has only one element, which is already 'equal to itself', so 0 operations needed.

Visualization

Tap to expand
๐Ÿ˜๏ธ The Neighborhood Meeting ProblemHouses on Street: [1, 3, 5, 4]๐Ÿ 1๐Ÿ 3๐Ÿ 5๐Ÿ 4Option 1: Group [1,3,5] meets at house 3Walking: |1-3|=2 + |3-3|=0 + |5-3|=2 = 4 steps totalOption 2: Group [3,5,4] meets at house 4Walking: |3-4|=1 + |5-4|=1 + |4-4|=0 = 2 steps total โœ“๐ŸŽฏ Best Choice: Option 2 with only 2 operations!๐Ÿ’ก Key Insight: Median (middle value when sorted) minimizes total distance
Understanding the Visualization
1
Find All Groups
Identify all possible groups of k consecutive neighbors
2
Calculate Meeting Cost
For each group, find the median house and calculate total walking distance
3
Choose Best Option
Select the group with minimum total walking distance
Key Takeaway
๐ŸŽฏ Key Insight: The median of any group minimizes the sum of absolute deviations - this is a fundamental property in statistics that makes our algorithm optimal!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ log k)

n subarrays ร— (k log k) for sorting each subarray to find median

n
2n
โš  Quadratic Growth
Space Complexity
O(k)

Space needed to create sorted copy of each subarray

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค k โ‰ค nums.length
  • 1 โ‰ค nums[i] โ‰ค 109
  • Time limit: 2 seconds
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
43.2K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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