Largest Time For Given Digits Problem
Description
LeetCode Problem 949.
Given an arrayarr 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 HHis between00and23, andMMis between00and59. The earliest 24-hour time is 00:00, and the latest is 23:59.
Return the latest 24-hour timein"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.
Example 3:
Input: arr = [0,0,0,0]
Output: "00:00"
Example 4:
Input: arr = [0,0,1,0]
Output: "10:00"
Constraints:
- arr.length == 4
- 0 <= arr[i] <= 9
Solution
Approach: Try All 24 Orders
Four digits can be arranged in only 4! = 24 ways, so we can simply try them all and keep the latest valid time. Trying to build the answer greedily digit by digit is a common trap: for [2,0,6,6], starting with the largest possible hour 20 leaves 66 for the minutes, yet 06:26 is valid.
- Pick three different positions
i,j,kwith three nested loops. The fourth position isl = 6 - i - j - k, because the positions0 + 1 + 2 + 3sum to6. - The hour is
arr[i] * 10 + arr[j]and the minute isarr[k] * 10 + arr[l]. - If the hour is below
24and the minute is below60, convert the time to minutes after midnight (hours * 60 + minutes) and keep the largest. - If nothing was valid, return
"". Otherwise format the result asHH:MM, padding each part with a leading zero.
Comparing times as a single number of minutes avoids comparing hours and minutes separately. Remember the leading zeros: [0,0,1,0] gives "10:00" and [0,0,0,0] gives "00:00", not "0:0".
Complexity: O(1) time and space: there are always 4 digits and 24 orders.
class Solution:
def largestTimeFromDigits(self, arr: List[int]) -> str:
best = -1 # latest valid time in minutes after midnight, -1 if none
# Try every order of the four digits: i, j, k are distinct positions and l is the one left
# (the positions 0 + 1 + 2 + 3 add up to 6).
for i in range(4):
for j in range(4):
for k in range(4):
if i == j or j == k or i == k:
continue
l = 6 - i - j - k
hours = arr[i] * 10 + arr[j]
minutes = arr[k] * 10 + arr[l]
if hours < 24 and minutes < 60:
best = max(best, hours * 60 + minutes)
if best == -1:
return ""
return "%02d:%02d" % (best // 60, best % 60)
Now write it from memory
Close the write-up and solve it yourself against the tests.