Problem solution · Python

Minimum Time to Break Locks II

Minimum Time to Break Locks II: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
67 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Minimum Time to Break Locks II, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 67 lines of Python from the credited upstream file 3385.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Time to Break Locks II · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def findMinimumTime(self, strength: list[int]) -> int:    costs = [[(s + turn - 1) // turn             for s in strength]             for turn in range(1, len(strength) + 1)]    return self._hungarian(costs)[-1]   def _hungarian(self, costs):    """    Returns an array `res` of length n (costs.length), with `res[i]` equaling    the minimum cost to assign the first (i + 1) turns to the first (i + 1)    locks using Hungarian algorithm, where costs[i][j] is the energy required    to break j-th lock in i-th turn.     https://en.wikipedia.org/wiki/Hungarian_algorithm    """    numLocks = len(costs)    turnPotentials = [0] * numLocks    lockPotentials = [0] * (numLocks + 1)    lockAssignments = [-1] * (numLocks + 1)    res = []     for currentTurn in range(numLocks):      currentLock = numLocks      lockAssignments[currentLock] = currentTurn      minReducedCosts = [math.inf] * (numLocks + 1)      previousLockAssignments = [-1] * (numLocks + 1)      locksInOptimalPath = [False] * (numLocks + 1)       while lockAssignments[currentLock] != -1:        locksInOptimalPath[currentLock] = True        assignedTurn = lockAssignments[currentLock]        minCostDelta = math.inf        nextLock = None         for lock in range(numLocks):          if not locksInOptimalPath[lock]:            reducedCost = (                costs[assignedTurn][lock] -                turnPotentials[assignedTurn] -                lockPotentials[lock]            )            oldMin = minReducedCosts[lock]            minReducedCosts[lock] = min(oldMin, reducedCost)            if minReducedCosts[lock] < oldMin:              previousLockAssignments[lock] = currentLock            if minReducedCosts[lock] < minCostDelta:              minCostDelta = minReducedCosts[lock]              nextLock = lock         for lock in range(numLocks + 1):          if locksInOptimalPath[lock]:            turnPotentials[lockAssignments[lock]] += minCostDelta            lockPotentials[lock] -= minCostDelta          else:            minReducedCosts[lock] -= minCostDelta         currentLock = nextLock       while currentLock != numLocks:        lockAssignments[currentLock] = lockAssignments[previousLockAssignments[currentLock]]        currentLock = previousLockAssignments[currentLock]       res.append(-lockPotentials[numLocks])     return res 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗