MediumNo. 2162

Minimum Cost to Set Cooking Time — LeetCode 2162 Python Solution

Topics
Math, Enumeration
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

PythonSolution
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

Time
O(n) or O(1)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0204Count PrimesMedium
0479Largest Palindrome ProductHard
0829Consecutive Numbers SumHard
0906Super PalindromesHard
1925Count Square Sum TriplesEasy
1952Three DivisorsEasy

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.

Free to download. Check it runs on your machine, then pick a plan.