Minimum Cost to Set Cooking Time solution and explanation
5 more videos on this problem
2162. Minimum Cost to Set Cooking Time || LeetCode 2162 || Biweekly LeetCode 71Bro Coders · 11:26 · 1K views
Minimum Cost to Set Cooking Time | 2162 LeetCode | Implementation | Leetcode BiWeekly Contest 71CodeWithSunny · 17:37 · 862 views
LeetCode BiWeekly Contest 71 || 2160 2161 2162 2163 || C++ || Timestamps || Best Explanation|| HindiBro Coders · 36:56 · 407 views
Biweekly Contest 71 | PROBLEM 2160 , 2161, 2162 | MATHS | GREEDYcode Explainer · 21:15 · 385 views
2162. Minimum Cost to Set Cooking Time (Leetcode Medium)Programming Live with Larry · 23:42 · 329 views
LeetCode 2162: Minimum Cost to Set Cooking TimeAlitaCode · 28:18 · 41 views
The problem
A generic microwave supports cooking times for:
- at least
1second. - at most
99minutes and99seconds.
To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example,
- You push
954(three digits). It is normalized as0954and interpreted as9minutes and54seconds. - You push
0008(four digits). It is interpreted as0minutes and8seconds. - You push
8090. It is interpreted as80minutes and90seconds. - You push
8130. It is interpreted as81minutes and30seconds.
You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue.
There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost.
Return the minimum cost to set targetSeconds seconds of cooking time.
Remember that one minute consists of 60 seconds.
Example 1:
Input: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600 Output: 6 Explanation: The following are the possible ways to set the cooking time. - 1 0 0 0, interpreted as 10 minutes and 0 seconds. The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1). The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost. - 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds. The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1). The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12. - 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds. The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1). The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9.
Example 2:
Input: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76 Output: 6 Explanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds. The finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6 Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.
Constraints:
0 <= startAt <= 91 <= moveCost, pushCost <= 1051 <= targetSeconds <= 6039
Approach overview
Problem Overview: You control a microwave where entering digits sets cooking time in MM:SS format, but digits are typed sequentially on a keypad. Moving the finger between digits costs moveCost and pressing a digit costs pushCost. Given a starting finger position and a target cooking time in seconds, the goal is to compute the minimum cost required to input the time.
The key constraint is that the microwave only accepts up to four digits. That means the time must be represented as a valid minutes and seconds combination where seconds < 60. Multiple representations can exist for the same total time, so you must evaluate all valid encodings and choose the cheapest keypad sequence.
Approach 1: Using Sorting (Enumeration of Valid Times) (Time: O(1), Space: O(1))
The core idea is to enumerate all valid (minutes, seconds) pairs that produce the target seconds. For each candidate, build the digit sequence that would be typed on the keypad. Remove leading zeros where appropriate because the microwave ignores unnecessary prefix digits. For every sequence, simulate typing: track the current finger position, add moveCost whenever the digit changes, and add pushCost for every press.
Sorting can be used to prioritize shorter digit sequences or lower-cost candidates first, though the candidate set is extremely small (at most two valid representations). Each candidate sequence is evaluated independently, and the minimum total cost is returned. Since the number of possible representations is constant, the overall complexity stays O(1). This approach mainly relies on arithmetic reasoning from Math and controlled Enumeration.
Approach 2: Using a Hash Map (Digit Cost Tracking) (Time: O(1), Space: O(1))
This variation focuses on reducing repeated keypad cost calculations. A hash map stores the cost of moving from one digit to another or the previously computed typing cost for certain transitions. As each candidate time representation is evaluated, digit transitions are checked using constant-time hash lookups rather than recomputing movement logic every time.
The algorithm still enumerates valid (minutes, seconds) pairs but optimizes the cost simulation. For each digit in the sequence, the hash map determines whether a movement cost applies and retrieves the stored transition cost instantly. This keeps the simulation simple and avoids repeated condition checks. The method relies on a lightweight hash table to streamline the keypad simulation while maintaining constant time complexity.
Recommended for interviews: The enumeration approach is what interviewers typically expect. It shows that you recognize multiple valid time representations and can simulate the keypad precisely. The hash map variation is a small optimization and demonstrates awareness of reducing repeated operations, but the main signal of skill is correctly enumerating candidates and computing the typing cost.
Approach 1: Approach 1: Using Sorting
In this approach, the problem can be solved by sorting the elements first and then ... (details based on the specific problem). This makes it easier to find the desired result efficiently by operating on a sorted array.
def solve():
# Implementation here
if __name__ == '__main__':
solve()import java.util.*;
public class Solution {
public static void solve() {
// Implementation here
}
public static void main(String[] args) {
solve();
}
}#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void solve() {
// Code implementation here
}
int main() {
solve();
return 0;
}function solve() {
// Code implementation here
}
solve();#include <stdio.h>
#include <stdlib.h>
void solve() {
// Code implementation here
}
int main() {
solve();
return 0;
}using System;
public class Solution {
public static void Solve() {
// Code implementation here
}
public static void Main(string[] args) {
Solve();
}
}Python's built-in sorting function is used to efficiently organize data before further processing.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) because the sorted array can take additional space.
Approach 2: Approach 2: Using a Hash Map
This approach uses a hash map (or dictionary) to store elements and perform lookups in constant time. This can be highly effective for problems that require frequent access or membership testing for large datasets.
def solve():
hashmap = {}
# Code implementation here
if __name__ == '__main__':
solve()import java.util.HashMap;
public class Solution {
public static void solve() {
HashMap<Integer, Integer> hashmap = new HashMap<>();
// Code implementation here
}
public static void main(String[] args) {
solve();
}
}#include <iostream>
#include <unordered_map>
using namespace std;
void solve() {
unordered_map<int, int> hashmap;
// Code implementation here
}
int main() {
solve();
return 0;
}function solve() {
const hashmap = new Map();
// Code implementation here
}
solve();#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct HashMap {
int key;
int value;
};
void solve() {
// Code implementation here
}
int main() {
solve();
return 0;
}using System;
using System.Collections.Generic;
public class Solution {
public static void Solve() {
Dictionary<int, int> hashmap = new Dictionary<int, int>();
// Code implementation here
}
public static void Main(string[] args) {
Solve();
}
}Python utilizes its dictionary structure, which provides constant time access to elements for quick lookup and insertions.
Time Complexity: O(n) for insertion, O(1) for lookups.
Space Complexity: O(n) for dictionary storage.
Approach 3: Default Approach
func minCostSetTime(startAt int, moveCost int, pushCost int, targetSeconds int) int {
m, s := targetSeconds/60, targetSeconds%60
f := func(m, s int) int {
if m < 0 || m > 99 || s < 0 || s > 99 {
return 0x3f3f3f3f
}
arr := []int{m / 10, m % 10, s / 10, s % 10}
i := 0
for ; i < 4 && arr[i] == 0; i++ {
}
t := 0
prev := startAt
for ; i < 4; i++ {
if arr[i] != prev {
t += moveCost
}
t += pushCost
prev = arr[i]
}
return t
}
return min(f(m, s), f(m-1, s+60))
}Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Using Sorting | Time Complexity: O(n log n) due to sorting. |
| Approach 2: Using a Hash Map | Time Complexity: O(n) for insertion, O(1) for lookups. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Enumeration with Sorting | O(1) | O(1) | General solution. Enumerates all valid minute-second combinations and simulates keypad typing. |
| Hash Map Cost Tracking | O(1) | O(1) | Useful when optimizing repeated digit transition cost calculations during simulation. |
Frequently asked questions
Is Minimum Cost to Set Cooking Time easy or hard?
Minimum Cost to Set Cooking Time is classified as a Medium difficulty problem. The challenge comes from identifying multiple valid time representations and correctly simulating keypad movement costs without missing edge cases.
Minimum Cost to Set Cooking Time Python/Java solution
Implement the solution by generating valid minute-second pairs and simulating keypad input. Track the previous digit, add moveCost when the finger moves, and add pushCost for every digit press. This logic translates directly to Python, Java, C++, and JavaScript.
How to solve Minimum Cost to Set Cooking Time in O(1)?
Convert the target seconds into possible (minutes, seconds) pairs such that seconds remain below 60. For each valid representation, construct the digit sequence and simulate typing while tracking moveCost and pushCost. Since the number of representations is constant, the total runtime remains O(1).
What is the best approach for Minimum Cost to Set Cooking Time?
The best approach enumerates all valid minute and second combinations that equal the target seconds and simulates the keypad typing cost. Each candidate sequence is evaluated by adding moveCost when the finger changes digits and pushCost for each press. Because only a few representations exist, the solution runs in O(1) time and O(1) space.
Is Minimum Cost to Set Cooking Time asked at Google/Amazon/Meta?
This type of problem appears in interviews at companies like Amazon, Google, and other large tech firms because it tests careful simulation, edge-case handling, and reasoning with constraints. It combines math-based decomposition with keypad state simulation.
What data structure is used in Minimum Cost to Set Cooking Time?
The primary technique is enumeration with simple arithmetic. Some implementations also use a hash map to cache digit transition costs or simplify keypad simulation, though the problem can be solved using only basic variables.
What is the time complexity of Minimum Cost to Set Cooking Time?
The time complexity is O(1). Only a constant number of minute–second representations can produce the target cooking time, so the algorithm evaluates a small fixed set of candidates and simulates keypad presses for each.
