Minimum Space Wasted From Packaging — LeetCode 1889 Python Solution

HardArrayBinary SearchPrefix SumSorting
Problem
#1889
Pattern
Prefix Sum
Reading time
3 min

The problem

You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply).

Example

Input
packages = [2,3,5], boxes = [[4,8],[2,8]]
Output
6
Explanation
It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.

Python solution

Python
class Solution:
    def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:
        mod = 10**9 + 7
        ans = inf
        packages.sort()
        for box in boxes:
            box.sort()
            if packages[-1] > box[-1]:
                continue
            s = i = 0
            for b in box:
                j = bisect_right(packages, b, lo=i)
                s += (j - i) * b
                i = j
            ans = min(ans, s)
        if ans == inf:
            return -1
        return (ans - sum(packages)) % mod

Complexity

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

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1889. Minimum Space Wasted From Packaging is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1889. Minimum Space Wasted From Packaging?
LeetCode 1889. Minimum Space Wasted From Packaging is rated Hard on LeetCode.
What topics does LeetCode 1889. Minimum Space Wasted From Packaging cover?
LeetCode 1889. Minimum Space Wasted From Packaging is tagged Array, Binary Search, Prefix Sum and Sorting 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