Largest Time for Given Digits - Problem
Given an array arr of exactly 4 digits, your task is to find the latest possible 24-hour time that can be formed using each digit exactly once.
A valid 24-hour time follows the format "HH:MM" where:
- HH represents hours: from
00to23 - MM represents minutes: from
00to59
Your goal is to arrange the four digits to create the maximum valid time. For example, if you have digits [1, 2, 3, 4], you want to find the arrangement that gives you the time closest to 23:59.
Return: The latest valid time as a string in "HH:MM" format, or an empty string "" if no valid time can be constructed.
Input & Output
example_1.py โ Basic Example
$
Input:
arr = [1,2,3,4]
โบ
Output:
"23:41"
๐ก Note:
The largest valid time we can make is 23:41. We use 2,3 for hours (23 โค 23) and 4,1 for minutes (41 โค 59). Other arrangements like 43:21 would be invalid since 43 > 23.
example_2.py โ No Valid Time
$
Input:
arr = [5,5,5,5]
โบ
Output:
""
๐ก Note:
No valid time can be formed. Any arrangement would give 55:55, but the maximum valid hour is 23, so 55 hours is invalid.
example_3.py โ Edge Case with Zeros
$
Input:
arr = [0,0,0,0]
โบ
Output:
"00:00"
๐ก Note:
All zeros form the time 00:00, which is valid (midnight). Since there's only one possible arrangement, this is our answer.
Visualization
Tap to expand
Understanding the Visualization
1
Collect the digits
We have 4 digit tiles that need to be arranged in HH:MM format
2
Try all arrangements
Test each of the 24 possible ways to arrange these 4 digits
3
Validate each time
Check if hours โค 23 and minutes โค 59 for each arrangement
4
Find maximum
Among all valid times, select the one closest to 23:59
5
Return result
Return the latest valid time or empty string if none exist
Key Takeaway
๐ฏ Key Insight: Since we have exactly 4 digits with only 24 possible arrangements, generating and testing all permutations is the most straightforward and efficient approach - sometimes brute force IS the optimal solution!
Time & Space Complexity
Time Complexity
O(1)
Fixed 24 permutations regardless of input, so constant time
โ Linear Growth
Space Complexity
O(1)
Only storing a few variables and the result string
โ Linear Space
Constraints
-
arr.length == 4 -
0 โค arr[i] โค 9 - Each digit must be used exactly once
- Time format must be HH:MM where HH โ [00,23] and MM โ [00,59]
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code