
Problem Statement
The problem presents an array arr
containing exactly four integer digits. The task is to construct the latest possible valid time in a 24-hour format using each of these digits exactly once. The 24-hour time format is structured as "HH:MM", where "HH" represents the hour and must be between 00 and 23, and "MM" represents the minutes and must be between 00 and 59. The solution should return this time as a string in the format "HH:MM". If it is impossible to construct a valid time from the digits provided, the function should return an empty string. This entails a careful permutation of the available digits to maximize the hour and minutes within their respective limits.
Examples
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 == 4
0 <= arr[i] <= 9
Approach and Intuition
To determine the latest possible time, we can adopt the following approach:
- Generate all possible permutations of the array
arr
. - Validate each permutation by fitting it into the time format "HH:MM" to ensure the hours are between 00 and 23 and the minutes are between 00 and 59.
- Track and update the maximum valid time found during this permutation check.
- If no valid time is identified during the permuations, return an empty string. Otherwise, return the maximum time found.
Intuition
- The need to generate permutations ensures that we evaluate every possible combination of the digits, ensuring the latest possible time isn't missed.
- Validating each permutation against the time constraints (00 to 23 for hours and 00 to 59 for minutes) ensures only feasible times are considered.
- By always updating the maximum time found during the evaluation, we ensure the result reflects the latest time possible.
With this approach, despite its brute force nature due to the limited size of the input (only 24 permutations), we can efficiently find the correct and latest time according to the given constraints.
Solutions
- Java
- Python
class Solution {
private int maxTime = -1;
public String calculateLargestTime(int[] digits) {
maxTime = -1;
generatePermutations(digits, 0);
if (maxTime == -1)
return "";
else
return String.format("%02d:%02d", maxTime / 60, maxTime % 60);
}
protected void generatePermutations(int[] digits, int index) {
if (index == digits.length) {
evaluateTime(digits);
return;
}
for (int idx = index; idx < digits.length; ++idx) {
exchange(digits, idx, index);
generatePermutations(digits, index + 1);
exchange(digits, idx, index);
}
}
protected void evaluateTime(int[] permutation) {
int hours = permutation[0] * 10 + permutation[1];
int minutes = permutation[2] * 10 + permutation[3];
if (hours < 24 && minutes < 60)
maxTime = Math.max(maxTime, hours * 60 + minutes);
}
protected void exchange(int[] array, int x, int y) {
if (x != y) {
int temporary = array[x];
array[x] = array[y];
array[y] = temporary;
}
}
}
The Java solution provided is designed to find the largest possible time that can be constructed using the given set of four digits. This task is solved by generating all permutations of the digits and then calculating the maximum valid time.
Here’s a concise breakdown of the process:
First, the method
calculateLargestTime
initializesmaxTime
to-1
. This variable is used to store the maximum number of minutes that can be represented by the permutations which form valid time.The method
generatePermutations
recursively generates all permutations of the input array of digits.For each permutation, the method
evaluateTime
calculates the hours and minutes. It then checks if these values form a valid time (i.e., hours less than 24 and minutes less than 60). If the condition is satisfied, it updatesmaxTime
if the current time in minutes is greater than the previously storedmaxTime
.The helper method
exchange
is used for swapping elements in the array of digits during the generation of permutations.If after evaluating all permutations, no valid time is found (
maxTime
remains-1
), thecalculateLargestTime
method returns an empty string. Otherwise, it formats the time in "HH:MM" format using the maximum minutes calculated.
Implement these steps using recursive permutation generation that efficiently checks and updates the possible maximum valid time. This approach ensures that the final result is the largest possible valid time or an indication that no valid time can be constructed.
class Solution:
def computeLargestTime(self, digits: List[int]) -> str:
highest_time = -1
def calculate_maximum_time(permutation):
nonlocal highest_time
hours, min1, min2, sec = permutation
hour_value = hours*10 + min1
minute_value = min2*10 + sec
if hour_value < 24 and minute_value < 60:
highest_time = max(highest_time, hour_value * 60 + minute_value)
def exchange_elements(arr, first, second):
if first != second:
arr[first], arr[second] = arr[second], arr[first]
def generate_permutations(arr, initial):
if initial == len(arr):
calculate_maximum_time(arr)
return
for position in range(initial, len(arr)):
exchange_elements(arr, position, initial)
generate_permutations(arr, initial+1)
exchange_elements(arr, position, initial)
generate_permutations(digits, 0)
if highest_time == -1:
return ""
else:
return "{:02d}:{:02d}".format(highest_time // 60, highest_time % 60)
The provided Python function computeLargestTime
aims to determine the largest 24-hour format time that can be obtained from a given list of four digits. Follow these steps in the given code to achieve this:
Define a function
calculate_maximum_time
to compute the time from a permutation of digits. The function checks if the constructed hours and minutes fall within valid time boundaries (hours < 24 and minutes < 60). If valid, it updates thehighest_time
variable to the maximum possible minutes since midnight.Include a helper
exchange_elements
for swapping elements in the array to facilitate generating permutations by maintaining array integrity.Use the recursive function
generate_permutations
to create all possible permutations of the input digits. For each complete permutation, callcalculate_maximum_time
.Inside
generate_permutations
, iterate through each position in the array to swap the current index with the index of the permutation depth, recursively call to generate further permutations, and subsequently backtrack by reversing the swap.After attempting all permutations, check the
highest_time
. If no valid time was identified (still -1), return an empty string. Otherwise, format thehighest_time
(converted back from minutes to hours and minutes) as a string in "HH:MM" format.
This solution effectively utilizes backtracking to explore all possible permutations of the digits and checks each to see if it forms a valid time, keeping track of the maximum.
No comments yet.