Super Washing Machines — LeetCode 517 Python Solution

HardGreedyArray
Problem
#517
Pattern
Greedy
Reading time
2 min

The problem

You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.

Example

Input
machines = [1,0,5]
Output
3
Explanation
1st move: 1 0 <-- 5 => 1 1 4

Python solution

Python
class Solution:
    def findMinMoves(self, machines: List[int]) -> int:
        n = len(machines)
        k, mod = divmod(sum(machines), n)
        if mod:
            return -1
        ans = s = 0
        for x in machines:
            x -= k
            s += x
            ans = max(ans, abs(s), x)
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the number of washing machines
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 517. Super Washing Machines is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 517. Super Washing Machines?
LeetCode 517. Super Washing Machines is rated Hard on LeetCode.
What is the time complexity of LeetCode 517. Super Washing Machines?
The Python solution on this page runs in O(n), where n is the number of washing machines.
What is the space complexity of LeetCode 517. Super Washing Machines?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 517. Super Washing Machines cover?
LeetCode 517. Super Washing Machines is tagged Greedy and Array 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