Skip to content

949. Largest Time for Given Digits

Difficulty Topics

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 == 4
  • 0 <= arr[i] <= 9

Solution

largest-time-for-given-digits.py
class Solution:
    def largestTimeFromDigits(self, arr: List[int]) -> str:
        for perm in permutations(sorted(arr, reverse = 1)):
            if perm[0] * 10 + perm[1] < 24 and perm[2] < 6:
                return f"{perm[0]}{perm[1]}:{perm[2]}{perm[3]}"

        return ""
largest-time-for-given-digits.cpp
class Solution {
public:
    string largestTimeFromDigits(vector<int>& A) {
        string ans = "";
        sort(A.begin(),A.end());
        do
        {
            if((A[0]==2 && A[1]<=3 || A[0]<2) && A[2]<=5)
            {
                string temp = to_string(A[0])+to_string(A[1])+":"
                    +to_string(A[2])+to_string(A[3]);
                if(temp > ans) ans = temp;
            }       
        }while(next_permutation(A.begin(),A.end()));
        return ans;
    }
};