949. Largest Time for Given Digits
Description
Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.
Return the latest 24-hour time in "HH:MM" format. If no valid time can be made, return an empty string.
Example 1:
Input: arr = [1,2,3,4] Output: "23:41" Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.
Example 2:
Input: arr = [5,5,5,5] Output: "" Explanation: There are no valid 24-hour times as "55:55" is not valid.
Constraints:
arr.length == 40 <= arr[i] <= 9
Solutions
Solution 1: Enumerate Hours and Minutes
Thinking
Form the latest valid time from four digits. There are only \(24\times 60\) legal hour-minute pairs. Enumerate them from large to small and accept the first whose digit counts match the input.
Enumerate valid hours \(h \in [0,23]\) and minutes \(m \in [0,59]\) from large to small, and use a count array to check whether the four digits match the input. The first hit is the latest valid time.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
Solution 2: Brute Force (Permutations)
Thinking
Enumerating times is constant work; we may instead permute the four indices, build an hour and a minute, and keep the maximum legal value. \(4!=24\) permutations are equally affordable.
Enumerate all permutations of the four digits, check whether they form a valid time, and keep the maximum.
The time complexity is \(O(4^3)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |