Problem · Simulation

Find Optimal Input

Learn this problem
MediumGoogle logoGoogleONSITE INTERVIEW
See Google hiring insights

Problem statement

🐰 Source note (07-17-2026): The source leaves entry length, leading zeros, and the final tie-break unspecified. For stable judging, this version checks integer inputs from 0 to 9999, disallows leading zeros, and chooses the smaller input when both cost and time difference are tied. The judged core task matches the visible source at about 97%.

A microwave accepts a numeric input and a target cooking time. Find the optimal input under the rules below.

  • Legal inputs are integers from 0 through 9999, written without leading zeros.
  • A one- or two-digit input is interpreted directly as seconds. For example, 81 means 81 seconds.
  • For a three- or four-digit input, all but the last two digits are minutes and the final two digits are seconds. The seconds part may exceed 59. For example, 999 means 9 minutes 99 seconds, and 1221 means 12 minutes 21 seconds.
  • Every key press costs 1. Moving between two different consecutive keys costs an additional 2; repeating the same key has no movement cost.
  • The interpreted time must be within an inclusive 10% of targetTime.
  • Choose the candidate with the lowest entry cost. If costs tie, choose the one closest to targetTime. If both cost and difference tie, choose the smaller numeric input.

For a target of 600 seconds, 888 means 568 seconds and costs 3, while 999 means 639 seconds and also costs 3. Since 568 is closer to 600, the optimal input is 888.

Function

findOptimalInput(targetTime: int) → int

Complete findOptimalInput, which receives targetTime in seconds and returns the optimal numeric input.

Examples

Example 1

targetTime = 600return = 888
Input 888 means 8 minutes 88 seconds, or 568 seconds. Input 999 means 9 minutes 99 seconds, or 639 seconds. Both cost 3 and are within 10% of 600, but 888 is closer by absolute time difference (32 seconds versus 39 seconds).

Constraints

  • 1 <= targetTime <= 6039
  • Candidate inputs are integers in [0, 9999] with no leading zeros.
  • The inclusive tolerance test is abs(actualTime - targetTime) * 10 <= targetTime.

More Google problems

drafts saved locally
public int findOptimalInput(int targetTime) {
  // write your code here
}
targetTime600
expected888
checking account