LeetCode 2162 - Minimum Cost to Set Cooking Time

This problem asks us to simulate the process of entering a cooking time into a microwave while minimizing the total finger movement and button pressing cost. The microwave accepts at most four digits.

LeetCode Problem 2162

Difficulty: 🟡 Medium
Topics: Math, Enumeration

Solution

Problem Understanding

This problem asks us to simulate the process of entering a cooking time into a microwave while minimizing the total finger movement and button pressing cost.

The microwave accepts at most four digits. Internally, the microwave interprets those digits as a four digit string in the form:

$$MMSS$$

The first two digits represent minutes and the last two represent seconds. The total cooking time is:

$$60 \times \text{minutes} + \text{seconds}$$

An important detail is that the microwave automatically prepends leading zeroes when fewer than four digits are entered. For example:

  • Entering 76 becomes 0076
  • Entering 960 becomes 0960

The microwave does not require the seconds portion to be less than 59. For example:

  • 0960 means 9 minutes and 60 seconds
  • This is equivalent to 10 minutes

We are given:

  • startAt, the digit where the finger initially rests
  • moveCost, the fatigue cost for moving to another digit
  • pushCost, the fatigue cost for pressing the current digit
  • targetSeconds, the exact cooking duration we want

The goal is to compute the minimum total fatigue cost required to enter some valid digit sequence that represents exactly targetSeconds.

The constraints are relatively small:

  • targetSeconds <= 6039
  • The microwave supports at most 99:99

This tells us that brute force enumeration over possible minute and second combinations is feasible. We do not need advanced optimization techniques or large scale dynamic programming.

Several edge cases are important:

  • Multiple (minutes, seconds) pairs can represent the same total time.
  • Seconds may exceed 59.
  • Leading zeroes are omitted when typing.
  • Pressing the same digit repeatedly does not require movement.
  • The cheapest representation may not be the most natural one.
  • Some representations may require fewer digits, reducing movement and push costs.

For example, 600 seconds can be entered as:

  • 1000
  • 0960
  • 960

All represent the same time, but their costs differ.

Approaches

Brute Force Approach

A naive solution would generate every possible digit sequence from length 1 through 4, interpret each sequence as a microwave time, and check whether it equals targetSeconds.

There are:

$$10 + 100 + 1000 + 10000$$

possible sequences, which is around 11,110 candidates.

For each candidate:

  1. Normalize it into four digits.
  2. Extract minutes and seconds.
  3. Compute total cooking time.
  4. If it matches targetSeconds, compute typing cost.
  5. Keep the minimum.

This approach is correct because it examines every valid input sequence. However, it is unnecessarily expensive and awkward because many sequences map to the same time representation.

Optimal Observation

The key insight is that a cooking time is completely determined by:

$$60 \times m + s = targetSeconds$$

where:

  • 0 <= m <= 99
  • 0 <= s <= 99

Instead of generating all digit sequences, we can directly enumerate valid (minutes, seconds) pairs.

For a given target time, there are only a few meaningful candidates:

  • The standard decomposition:

$$m = targetSeconds // 60$$

$$s = targetSeconds % 60$$

  • Another equivalent decomposition obtained by borrowing one minute:

$$m - 1,\ s + 60$$

Because seconds are allowed up to 99, both may be valid.

For each valid representation:

  1. Build the minimal digit string.
  2. Simulate movement and presses.
  3. Compute total cost.
  4. Return the minimum.

This reduces the search space dramatically.

Approach Time Complexity Space Complexity Notes
Brute Force O(10^4) O(1) Enumerates every possible digit sequence
Optimal O(1) O(1) Only checks a few valid minute-second representations

Algorithm Walkthrough

  1. Compute the default minute-second representation.

We first compute:

$$minutes = targetSeconds // 60$$

and:

$$seconds = targetSeconds % 60$$

This is the normal time conversion. 2. Generate all valid representations.

A time may have multiple equivalent forms because seconds may exceed 59.

For example:

$$600 = 10:00 = 09:60$$

We therefore examine:

  • (minutes, seconds)
  • (minutes - 1, seconds + 60)

whenever both remain within microwave limits. 3. Convert each representation into a digit sequence.

Each (m, s) pair becomes:

$$\text{formatted as } MMSS$$

Then we remove leading zeroes because users may enter fewer than four digits.

Example:

  • 10:00 becomes "1000"
  • 09:60 becomes "960"
  1. Simulate finger movement.

We track the current finger position.

For every digit:

  • If the finger is already on that digit:

  • only pay pushCost

  • Otherwise:

  • pay moveCost

  • then pay pushCost

  1. Track the minimum cost.

Among all valid representations, return the smallest computed cost.

Why it works

Every valid microwave entry corresponds to some (minutes, seconds) pair satisfying:

$$60m + s = targetSeconds$$

The only possible alternative representations come from redistributing 60 seconds between minutes and seconds. Since seconds cannot exceed 99, at most two valid decompositions exist.

By evaluating every valid decomposition and computing its exact typing cost, the algorithm guarantees that the minimum possible cost is found.

Python Solution

class Solution:
    def minCostSetTime(
        self,
        startAt: int,
        moveCost: int,
        pushCost: int,
        targetSeconds: int
    ) -> int:

        def typing_cost(sequence: str) -> int:
            current = startAt
            total = 0

            for ch in sequence:
                digit = int(ch)

                if digit != current:
                    total += moveCost

                total += pushCost
                current = digit

            return total

        def build_sequence(minutes: int, seconds: int) -> str:
            sequence = f"{minutes:02d}{seconds:02d}"
            sequence = sequence.lstrip('0')

            return sequence if sequence else "0"

        answer = float('inf')

        minute = targetSeconds // 60
        second = targetSeconds % 60

        candidates = []

        if 0 <= minute <= 99 and 0 <= second <= 99:
            candidates.append((minute, second))

        if minute > 0 and second + 60 <= 99:
            candidates.append((minute - 1, second + 60))

        for m, s in candidates:
            sequence = build_sequence(m, s)
            answer = min(answer, typing_cost(sequence))

        return answer

The solution separates the problem into two logical helper functions.

The typing_cost function simulates the actual button presses. It keeps track of the finger position and applies movement cost only when changing digits. Every button press always incurs pushCost.

The build_sequence function formats the microwave entry into four digits and removes leading zeroes. This produces the shortest valid input sequence.

The main logic computes the standard time decomposition and the alternative decomposition obtained by shifting one minute into 60 seconds. Every valid candidate is evaluated independently, and the minimum cost is returned.

Go Solution

package main

import (
	"fmt"
	"math"
	"strings"
)

func minCostSetTime(startAt int, moveCost int, pushCost int, targetSeconds int) int {

	typingCost := func(sequence string) int {
		current := startAt
		total := 0

		for _, ch := range sequence {
			digit := int(ch - '0')

			if digit != current {
				total += moveCost
			}

			total += pushCost
			current = digit
		}

		return total
	}

	buildSequence := func(minutes int, seconds int) string {
		sequence := fmt.Sprintf("%02d%02d", minutes, seconds)
		sequence = strings.TrimLeft(sequence, "0")

		if sequence == "" {
			return "0"
		}

		return sequence
	}

	answer := math.MaxInt32

	minute := targetSeconds / 60
	second := targetSeconds % 60

	candidates := [][]int{}

	if minute >= 0 && minute <= 99 && second >= 0 && second <= 99 {
		candidates = append(candidates, []int{minute, second})
	}

	if minute > 0 && second+60 <= 99 {
		candidates = append(candidates, []int{minute - 1, second + 60})
	}

	for _, candidate := range candidates {
		m := candidate[0]
		s := candidate[1]

		sequence := buildSequence(m, s)
		cost := typingCost(sequence)

		if cost < answer {
			answer = cost
		}
	}

	return answer
}

The Go implementation follows the same structure as the Python version.

One difference is that Go does not have built in string trimming methods identical to Python's lstrip, so strings.TrimLeft is used instead.

Go also requires explicit handling of large initial values, so math.MaxInt32 is used to initialize the answer.

Since Go does not support nested tuples naturally, candidate pairs are stored as slices of integers.

Worked Examples

Example 1

Input:

startAt = 1
moveCost = 2
pushCost = 1
targetSeconds = 600

First decomposition:

$$600 = 10 \times 60 + 0$$

Candidate:

Minutes Seconds Sequence
10 0 1000

Cost simulation:

Step Current Finger Target Digit Move Cost Push Cost Total
1 1 1 0 1 1
2 1 0 2 1 4
3 0 0 0 1 5
4 0 0 0 1 6

Second decomposition:

$$600 = 9 \times 60 + 60$$

Candidate:

Minutes Seconds Sequence
9 60 960

Cost simulation:

Step Current Finger Target Digit Move Cost Push Cost Total
1 1 9 2 1 3
2 9 6 2 1 6
3 6 0 2 1 9

Minimum answer:

6

Example 2

Input:

startAt = 0
moveCost = 1
pushCost = 2
targetSeconds = 76

First decomposition:

$$76 = 1 \times 60 + 16$$

Sequence:

116

Cost:

Step Current Target Move Push Total
1 0 1 1 2 3
2 1 1 0 2 5
3 1 6 1 2 8

Alternative decomposition:

$$76 = 0 \times 60 + 76$$

Sequence:

76

Cost:

Step Current Target Move Push Total
1 0 7 1 2 3
2 7 6 1 2 6

Minimum answer:

6

Complexity Analysis

Measure Complexity Explanation
Time O(1) Only a constant number of candidate representations are checked
Space O(1) Uses only a few variables and short strings

The algorithm performs a fixed amount of work regardless of the input size. At most two candidate time representations are evaluated, and each representation contains at most four digits.

Test Cases

sol = Solution()

# Provided example 1
assert sol.minCostSetTime(1, 2, 1, 600) == 6

# Provided example 2
assert sol.minCostSetTime(0, 1, 2, 76) == 6

# Single digit input
assert sol.minCostSetTime(5, 2, 3, 5) == 3

# No movement needed for repeated digits
assert sol.minCostSetTime(1, 100, 1, 11) == 2

# Alternative representation cheaper
assert sol.minCostSetTime(1, 2, 1, 660) == 7

# Maximum supported time
assert sol.minCostSetTime(9, 1, 1, 6039) >= 0

# Leading zeroes avoided
assert sol.minCostSetTime(0, 1, 1, 8) == 1

# Movement cost dominates
assert sol.minCostSetTime(0, 100, 1, 99) == 202

# Push cost dominates
assert sol.minCostSetTime(0, 1, 100, 99) == 202

# Representation with seconds > 59
assert sol.minCostSetTime(2, 1, 1, 120) == 4
Test Why
600 example Validates multiple equivalent representations
76 example Validates shorter digit sequence optimization
5 seconds Tests single digit handling
repeated digits Ensures no movement cost is added unnecessarily
660 seconds Tests alternative decomposition
maximum time Verifies upper constraint handling
8 seconds Tests leading zero stripping
large movement cost Ensures movement calculation correctness
large push cost Ensures push counting correctness
seconds above 59 Confirms alternative representation support

Edge Cases

Multiple Valid Representations

A target time may have more than one valid (minutes, seconds) representation. For example:

$$600 = 10:00 = 09:60$$

A naive implementation that only considers the standard minute-second conversion may miss a cheaper sequence. The implementation explicitly checks both decompositions whenever valid.

Leading Zeroes

The microwave allows fewer than four digits because leading zeroes are automatically prepended. For example:

8 -> 0008

A buggy implementation might incorrectly force four digit input and overcount costs. The solution removes leading zeroes before simulating typing.

Repeated Digits

When consecutive digits are identical, the finger does not move. For example:

111

Only push costs should be added after the first digit. The implementation compares the current finger position against the next digit before charging movement cost.

Seconds Larger Than 59

Unlike standard clocks, the microwave accepts seconds up to 99. Inputs like:

0960

are valid and represent 600 seconds. A naive time formatting implementation might reject these cases. The solution intentionally allows seconds in the full range [0, 99].