Skip to content
MediumBacktrackingAI interview only

Largest Time For Given Digits

Asked atgoogleamazonmicrosoft

01 · Problem

You are given an array arr of exactly four digits. Arrange all four digits, using each one exactly once, into a 24-hour time "HH:MM", where HH is between 00 and 23 and MM is between 00 and 59.

Return the latest such time as a string in "HH:MM" format (always two digits for the hour and two for the minute). If no arrangement forms a valid time, return an empty string "".

02 · Examples

Example 01
Input
arr = [1,2,3,4]
Output
"23:41"

Valid arrangements include 12:34, 21:43 and 23:41. The latest of them is 23:41.

Example 02
Input
arr = [5,5,5,5]
Output
""

Every arrangement gives 55:55, which is not a valid hour, so no time can be formed.

Example 03
Input
arr = [0,0,1,0]
Output
"10:00"

The possible times are 00:01, 00:10, 01:00 and 10:00. The latest is 10:00.

03 · Constraints

  • 01`arr.length == 4`
  • 02`0 <= arr[i] <= 9`
  • 03Each element of `arr` must be used exactly once
  • 04Return `""` when no valid time exists

04 · Optimal complexity

Time
O(1)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.