Minimum Sum of Squared Difference solution and explanation
7 more videos on this problem
Biweekly Contest 82 | 6118. Minimum Sum of Squared DifferencecodingMohan · 23:58 · 3K views
2333. Minimum Sum of Squared Difference (Leetcode Medium)Programming Live with Larry · 52:55 · 973 views
LeetCode 2333 | Mnimum sum of squared differenec | Python SolutionAI Learning Corner · 15:16 · 471 views
【每日一题】LeetCode 2333. Minimum Sum of Squared DifferenceHuifeng Guan · 24:54 · 454 views
LEETCODE Weekly Contest 288 | PROBLEM 2331 , 2332, 2333 | GREEDY | BRUTE FORCEcode Explainer · 16:43 · 395 views
Leetcode 2333. Minimum Sum of Squared Difference - SortedDict containerCode-Yao · 9:18 · 335 views
Leetcode 2333. Minimum Sum of Squared Difference - buckets sort ideaCode-Yao · 11:54 · 236 views
2333. Minimum Sum of Squared DifferenceJust Coding, with Jie · 15:17 · 138 views
The problem
You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.
The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n.
You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times.
Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.
Note: You are allowed to modify the array elements to become negative integers.
Example 1:
Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0 Output: 579 Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.
Example 2:
Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1 Output: 43 Explanation: One way to obtain the minimum sum of square difference is: - Increase nums1[0] once. - Increase nums2[2] once. The minimum of the sum of square difference will be: (2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43. Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.
Constraints:
n == nums1.length == nums2.length1 <= n <= 1050 <= nums1[i], nums2[i] <= 1050 <= k1, k2 <= 109
Approach overview
Problem Overview: You are given two arrays nums1 and nums2. Each operation decreases any element in either array by 1, up to k1 + k2 total operations. The goal is to minimize the sum of squared differences (nums1[i] - nums2[i])^2 across all indices.
The key observation: operations only matter on the absolute differences diff[i] = |nums1[i] - nums2[i]|. Reducing the largest differences first minimizes the squared penalty because squaring amplifies large values.
Approach 1: Max-Heap to Reduce Largest Differences (O(n log n))
Compute the absolute difference for every index and push them into a heap (priority queue). Always extract the largest difference and reduce it by 1 using one operation. Push the updated value back into the heap and repeat until operations are exhausted or all differences reach zero. This greedy strategy works because decreasing the largest value reduces the squared sum the most at every step. Heap push and pop cost O(log n), giving total time complexity O((n + k) log n) in the worst case and O(n) space.
Approach 2: Greedy Sort and Level Differences (O(n log n))
Instead of repeatedly popping from a heap, sort the difference array in descending order using sorting. Process the largest block of values and reduce them until they match the next smaller difference. This "leveling" technique applies operations in batches instead of one-by-one updates. When operations are insufficient to reach the next level, distribute them evenly across the current largest elements. The idea relies on greedy reduction of the biggest squared contributors. Sorting costs O(n log n), and the adjustment pass runs in O(n) time with O(1) extra space beyond the array.
Approach 3: Binary Search on Maximum Allowed Difference (O(n log m))
Another optimization treats the problem as finding the smallest threshold T such that reducing every diff[i] above T requires at most k1 + k2 operations. Binary search the threshold between 0 and the maximum difference using binary search. For each candidate threshold, iterate through the array and compute how many decrements are required to bring values down to that level. Once the threshold is found, distribute remaining operations across elements at that boundary. The feasibility check runs in O(n), producing overall time complexity O(n log m) where m is the maximum difference, with O(1) extra space.
Recommended for interviews: The max-heap approach is the most intuitive and easiest to implement under pressure. It clearly demonstrates greedy reasoning and correct prioritization of the largest difference. The sorting-based leveling approach is more optimized and reduces repeated heap operations, which interviewers often appreciate once the greedy insight is established.
Approach 1: Max-Heap to Minimize Largest Differences
This approach involves using a max-heap (priority queue) to track and modify the largest differences first. By focusing on reducing the largest differences, we can effectively minimize the impact on the sum of squared differences.
The core idea is to repeatedly decrease the difference that contributes most to the sum of squared differences. We use the combined allowance of k1 and k2 modifications to decrement the largest absolute difference one at a time until we exhaust our allowed modifications or all differences are reduced to zero.
import heapq
def min_sum_of_squares(nums1, nums2, k1, k2):
n = len(nums1)
# Calculate differences
differences = [abs(a - b) for a, b in zip(nums1, nums2)]
# Create a max heap
max_heap = [-diff for diff in differences]
heapq.heapify(max_heap)
total_k = k1 + k2
while total_k > 0:
max_diff = -heapq.heappop(max_heap)
if max_diff == 0:
break
max_diff -= 1
total_k -= 1
heapq.heappush(max_heap, -max_diff)
# Calculate the resulting sum of squares
result = sum(diff**2 for diff in max_heap)
return result
# Example usage:
print(min_sum_of_squares([1, 4, 10, 12], [5, 8, 6, 9], 1, 1)) # Output: 43#include <iostream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
int minSumOfSquares(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {
priority_queue<int> maxHeap;
int n = nums1.size();
for (int i = 0; i < n; i++) {
maxHeap.push(abs(nums1[i] - nums2[i]));
}
int totalK = k1 + k2;
while (totalK > 0 && !maxHeap.empty()) {
int maxDiff = maxHeap.top();
maxHeap.pop();
if (maxDiff == 0) break;
maxHeap.push(maxDiff - 1);
totalK--;
}
int result = 0;
while (!maxHeap.empty()) {
int diff = maxHeap.top();
maxHeap.pop();
result += diff * diff;
}
return result;
}
int main() {
vector<int> nums1 = {1, 4, 10, 12};
vector<int> nums2 = {5, 8, 6, 9};
int k1 = 1, k2 = 1;
cout << minSumOfSquares(nums1, nums2, k1, k2) << endl; // Output: 43
return 0;
}This Python solution uses a max-heap to continuously target and reduce the maximum difference. By working with the negation of the differences, Python's min-heap acts as a max-heap.
The total modifications allowed (k1 + k2) are applied to decrease the largest difference, minimizing the sum of squared differences. This process efficiently finds and modifies the largest element due to the logarithmic complexity of heap operations.
Time Complexity: O(n log n) due to the heap operations over n elements, where insertion and deletion are logarithmic operations.
Space Complexity: O(n) for storing differences in the heap.
Approach 2: Greedy Sort and Adjust
This method involves sorting the absolute differences, and then manipulating them starting from the largest. By sorting, we ensure that we are applying our limited operations to the most impactful differences first, similar to the first approach, but without the overhead of maintaining a priority queue.
The total number of operations available (k1 + k2) are progressively applied to reduce these differences, sequentially altering the largest differences first. This leads to minimal squared differences.
import java.util.*;
public class MinSumOfSquares {
public static int minSumOfSquares(int[] nums1, int[] nums2, int k1, int k2) {
int n = nums1.length;
int[] differences = new int[n];
for (int i = 0; i < n; i++) {
differences[i] = Math.abs(nums1[i] - nums2[i]);
}
Arrays.sort(differences);
int totalK = k1 + k2;
for (int i = n - 1; i >= 0 && totalK > 0; i--) {
if (differences[i] > 0) {
int decrease = Math.min(differences[i], totalK);
differences[i] -= decrease;
totalK -= decrease;
}
}
int result = 0;
for (int diff : differences) {
result += diff * diff;
}
return result;
}
public static void main(String[] args) {
int[] nums1 = {1, 4, 10, 12};
int[] nums2 = {5, 8, 6, 9};
int k1 = 1, k2 = 1;
System.out.println(minSumOfSquares(nums1, nums2, k1, k2)); // Output: 43
}
}function minSumOfSquares(nums1, nums2, k1, k2) {
let differences = nums1.map((v, i) => Math.abs(v - nums2[i]));
differences.sort((a, b) => b - a);
let totalK = k1 + k2;
for (let i = 0; i < differences.length && totalK > 0; i++) {
if (differences[i] > 0) {
let decrease = Math.min(differences[i], totalK);
differences[i] -= decrease;
totalK -= decrease;
}
}
return differences.reduce((sum, diff) => sum + diff * diff, 0);
}
// Example usage:
console.log(minSumOfSquares([1, 4, 10, 12], [5, 8, 6, 9], 1, 1)); // Output: 43This Java solution sorts the absolute differences and iteratively decreases them, starting from the largest, by subtracting up to the number of available modifications.
By sorting, we can handle the most significant differences first, effectively minimizing the sum of squared differences. After applying all modifications, we compute the final result by summing up the squares of the modified differences.
Time Complexity: O(n log n) for sorting the differences.
Space Complexity: O(n) for storing the differences array.
Approach 3: Default Approach
func minSumSquareDiff(nums1 []int, nums2 []int, k1 int, k2 int) int64 {
k := k1 + k2
s, mx := 0, 0
n := len(nums1)
d := make([]int, n)
for i, v := range nums1 {
d[i] = abs(v - nums2[i])
s += d[i]
mx = max(mx, d[i])
}
if s <= k {
return 0
}
left, right := 0, mx
for left < right {
mid := (left + right) >> 1
t := 0
for _, v := range d {
t += max(v-mid, 0)
}
if t <= k {
right = mid
} else {
left = mid + 1
}
}
for i, v := range d {
k -= max(v-left, 0)
d[i] = min(v, left)
}
for i, v := range d {
if k <= 0 {
break
}
if v == left {
d[i]--
k--
}
}
ans := 0
for _, v := range d {
ans += v * v
}
return int64(ans)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}Complexity comparison
| Approach | Complexity |
|---|---|
| Max-Heap to Minimize Largest Differences | Time Complexity: O(n log n) due to the heap operations over n elements, where insertion and deletion are logarithmic operations. |
| Greedy Sort and Adjust | Time Complexity: O(n log n) for sorting the differences. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Max-Heap Reduction | O((n + k) log n) | O(n) | Straightforward greedy implementation that always reduces the largest difference first |
| Greedy Sort and Level | O(n log n) | O(1) | When you want fewer updates by reducing groups of values at once |
| Binary Search Threshold | O(n log m) | O(1) | Useful when reasoning about the maximum allowed difference rather than individual operations |
Frequently asked questions
Is Minimum Sum of Squared Difference easy or hard?
Minimum Sum of Squared Difference is rated Medium on LeetCode with a relatively low acceptance rate around 27%. The difficulty comes from recognizing that reducing the largest differences first minimizes the squared cost and implementing the greedy logic efficiently.
How to solve Minimum Sum of Squared Difference in O(n log n)?
Compute absolute differences between corresponding elements and sort them in descending order. Use a greedy leveling strategy: reduce the largest values until they match the next distinct level or operations run out. This avoids repeated heap operations and completes in O(n log n) time due to sorting.
What is the best approach for Minimum Sum of Squared Difference?
The most common solution uses a max-heap (priority queue). Compute absolute differences, always reduce the largest difference using available operations, and push the updated value back. This greedy strategy minimizes the squared penalty at each step and runs in O((n + k) log n) time with O(n) space.
Is Minimum Sum of Squared Difference asked at Google/Amazon/Meta?
Greedy array optimization problems similar to Minimum Sum of Squared Difference frequently appear in interviews at companies like Google, Amazon, and Meta. The problem tests understanding of greedy strategies, priority queues, and handling large operation counts efficiently.
What data structure is used in Minimum Sum of Squared Difference?
A max-heap (priority queue) is the primary data structure used in the greedy solution. It allows efficient retrieval and update of the largest difference at each step. Some optimized solutions instead rely on sorting the difference array and processing it with greedy batch updates.
What is the time complexity of Minimum Sum of Squared Difference?
The heap-based greedy approach runs in O((n + k) log n) time because each operation involves a heap pop and push. A sorting-based greedy optimization runs in O(n log n) time by reducing groups of differences together. Both approaches require O(n) or O(1) additional space depending on implementation.
Minimum Sum of Squared Difference Python or Java solution approach?
In Python, the solution typically uses the heapq module (with negated values for a max-heap) to repeatedly reduce the largest difference. In Java, a PriorityQueue configured as a max-heap is used. Both implementations follow the same greedy logic and run in O((n + k) log n) time.
