Minimum Cost to Set Cooking Time — LeetCode 2162 Python Solution

MediumMathEnumeration
Problem
#2162
Reading time
5 min

The problem

A generic microwave supports cooking times for: at least 1 second. at most 99 minutes and 99 seconds.

Example

Input
startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600
Output
6
Explanation
The following are the possible ways to set the cooking time.

Python solution

Python
class Solution:
    def minCostSetTime(
        self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int
    ) -> int:
        def f(m, s):
            if not 0 <= m < 100 or not 0 <= s < 100:
                return inf
            arr = [m // 10, m % 10, s // 10, s % 10]
            i = 0
            while i < 4 and arr[i] == 0:
                i += 1
            t = 0
            prev = startAt
            for v in arr[i:]:
                if v != prev:
                    t += moveCost
                t += pushCost
                prev = v
            return t

        m, s = divmod(targetSeconds, 60)
        ans = min(f(m, s), f(m - 1, s + 60))
        return ans

Complexity

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

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2162. Minimum Cost to Set Cooking Time is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2162. Minimum Cost to Set Cooking Time?
LeetCode 2162. Minimum Cost to Set Cooking Time is rated Medium on LeetCode.
What topics does LeetCode 2162. Minimum Cost to Set Cooking Time cover?
LeetCode 2162. Minimum Cost to Set Cooking Time is tagged Math and Enumeration 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