Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Generate all permutations
To solve this problem, we need to find the latest valid 24-hour time that can be made using all four digits exactly once. We can achieve this through the following steps:
- Generate Permutations:
- Generate all possible permutations of the four digits.
- Validate Time:
- For each permutation, verify if it can represent a valid 24-hour time.
- Track Latest Time:
- Keep track of the maximum time that meets the validation criteria in terms of hours and minutes.
- Return Result:
- Format and return the maximum valid time we found. If none is valid, return an empty string.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(1)- Generating permutations (n! where n is 4) leads to a time complexity of
O(24)(since 4! = 24 permutations). - Validating each permutation takes constant time
O(1). - Overall, the approach runs in constant time
O(1).
- Generating permutations (n! where n is 4) leads to a time complexity of
- 🧺 Space complexity:
O(1)for storing the permutations and the calculations.