Minimum Sum of Squared Difference — LeetCode 2333 Python Solution

MediumGreedyArrayBinary SearchSortingHeap (Priority Queue)
Problem
#2333
Reading time
5 min

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.

Example

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.

Python solution

Python
class Solution:
    def minSumSquareDiff(
        self, nums1: List[int], nums2: List[int], k1: int, k2: int
    ) -> int:
        d = [abs(a - b) for a, b in zip(nums1, nums2)]
        k = k1 + k2
        if sum(d) <= k:
            return 0
        left, right = 0, max(d)
        while left < right:
            mid = (left + right) >> 1
            if sum(max(v - mid, 0) for v in d) <= k:
                right = mid
            else:
                left = mid + 1
        for i, v in enumerate(d):
            d[i] = min(left, v)
            k -= max(0, v - left)
        for i, v in enumerate(d):
            if k == 0:
                break
            if v == left:
                k -= 1
                d[i] -= 1
        return sum(v * v for v in d)

Complexity

MeasureComplexity
TimeO(log n) or O(n log n)
SpaceO(1) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2333. Minimum Sum of Squared Difference is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2333. Minimum Sum of Squared Difference?
LeetCode 2333. Minimum Sum of Squared Difference is rated Medium on LeetCode.
What topics does LeetCode 2333. Minimum Sum of Squared Difference cover?
LeetCode 2333. Minimum Sum of Squared Difference is tagged Greedy, Array, Binary Search, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview