Maximum possible time that can be formed from four digits

Given an array arr[] having 4 integer digits only. The task is to return the maximum 24 hour time that can be formed using the digits from the array.
Note that the minimum time in 24 hour format is 00:00, and the maximum is 23:59. If a valid time cannot be formed then return -1.

Examples:

Input: arr[] = {1, 2, 3, 4}
Output: 23:41

Input: arr[] = {5, 5, 6, 6}
Output: -1

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Create a HashMap and store the frequency of each digit in the map which can be used to know how many of such digits are available.
Now, in order to generate a valid time following conditions must be satisfied:

• First digit of hours must be from the range [0, 2]. Start checking in decreasing order in order to maximize the time i.e. from 2 to 0. Once the digit is chosen, decrement it’s occurrence in the map by 1.
• Second digit of hours must be from the range [0, 3] if first digit was chosen as 2 else [0, 9]. Update the HashMap accordingly after choosing the digit.
• First digit of minutes must be from the range [0, 5] and second digit of minutes must be from the range [0, 9].

If any of the above condition fails i.e. no digit could be chosen at any point then print -1 else print the time.

Below is the implementation of the above approach:

C++

 // C++ implementation of the approach #include using namespace std;    // Function to return the updated frequency map // for the array passed as argument map getFrequencyMap(int arr[], int n) {     map hashMap;     for (int i = 0; i < n; i++) {            hashMap[arr[i]]++;     }     return hashMap; }    // Function that returns true if the passed digit is present // in the map after decrementing it's frequency by 1 bool hasDigit(map* hashMap, int digit) {        // If map contains the digit     if ((*hashMap)[digit]) {            // Decrement the frequency of the digit by 1         (*hashMap)[digit]--;            // True here indicates that the digit was found in the map         return true;     }        // Digit not found     return false; }    // Function to return the maximum possible time_value in 24-Hours format string getMaxtime_value(int arr[], int n) {     map hashMap = getFrequencyMap(arr, n);     int i;     bool flag;     string time_value = "";        flag = false;        // First digit of hours can be from the range [0, 2]     for (i = 2; i >= 0; i--) {         if (hasDigit(&hashMap, i)) {             flag = true;             time_value += (char)i + 48;             break;         }     }        // If no valid digit found     if (!flag)         return "-1";        flag = false;        // If first digit of hours was chosen as 2 then     // the second digit of hours can be     // from the range [0, 3]     if (time_value == '2') {         for (i = 3; i >= 0; i--) {             if (hasDigit(&hashMap, i)) {                 flag = true;                 time_value += (char)i + 48;                 break;             }         }     }        // Else it can be from the range [0, 9]     else {         for (i = 9; i >= 0; i--) {             if (hasDigit(&hashMap, i)) {                 flag = true;                 time_value += (char)i + 48;                 break;             }         }     }     if (!flag)         return "-1";        // Hours and minutes separator     time_value += ":";        flag = false;        // First digit of minutes can be from the range [0, 5]     for (i = 5; i >= 0; i--) {         if (hasDigit(&hashMap, i)) {             flag = true;             time_value += (char)i + 48;             break;         }     }     if (!flag)         return "-1";        flag = false;        // Second digit of minutes can be from the range [0, 9]     for (i = 9; i >= 0; i--) {         if (hasDigit(&hashMap, i)) {             flag = true;             time_value += (char)i + 48;             break;         }     }     if (!flag)         return "-1";        // Return the maximum possible time_value     return time_value; }    // Driver code int main() {     int arr[] = { 0, 0, 0, 9 };     int n = sizeof(arr) / sizeof(int);     cout << (getMaxtime_value(arr, n));     return 0; } // contributed by Arnab Kundu

Java

 // Java implementation of the approach    import java.util.*;    public class GFG {        // Function to return the updated frequency map     // for the array passed as argument     static HashMap getFrequencyMap(int arr[])     {         HashMap hashMap = new HashMap<>();         for (int i = 0; i < arr.length; i++) {             if (hashMap.containsKey(arr[i])) {                 hashMap.put(arr[i], hashMap.get(arr[i]) + 1);             }             else {                 hashMap.put(arr[i], 1);             }         }         return hashMap;     }        // Function that returns true if the passed digit is present     // in the map after decrementing it's frequency by 1     static boolean hasDigit(HashMap hashMap, int digit)     {            // If map contains the digit         if (hashMap.containsKey(digit) && hashMap.get(digit) > 0) {                // Decrement the frequency of the digit by 1             hashMap.put(digit, hashMap.get(digit) - 1);                // True here indicates that the digit was found in the map             return true;         }            // Digit not found         return false;     }        // Function to return the maximum possible time in 24-Hours format     static String getMaxTime(int arr[])     {         HashMap hashMap = getFrequencyMap(arr);         int i;         boolean flag;         String time = "";            flag = false;            // First digit of hours can be from the range [0, 2]         for (i = 2; i >= 0; i--) {             if (hasDigit(hashMap, i)) {                 flag = true;                 time += i;                 break;             }         }            // If no valid digit found         if (!flag) {             return "-1";         }            flag = false;            // If first digit of hours was chosen as 2 then         // the second digit of hours can be         // from the range [0, 3]         if (time.charAt(0) == '2') {             for (i = 3; i >= 0; i--) {                 if (hasDigit(hashMap, i)) {                     flag = true;                     time += i;                     break;                 }             }         }            // Else it can be from the range [0, 9]         else {             for (i = 9; i >= 0; i--) {                 if (hasDigit(hashMap, i)) {                     flag = true;                     time += i;                     break;                 }             }         }         if (!flag) {             return "-1";         }            // Hours and minutes separator         time += ":";            flag = false;            // First digit of minutes can be from the range [0, 5]         for (i = 5; i >= 0; i--) {             if (hasDigit(hashMap, i)) {                 flag = true;                 time += i;                 break;             }         }         if (!flag) {             return "-1";         }            flag = false;            // Second digit of minutes can be from the range [0, 9]         for (i = 9; i >= 0; i--) {             if (hasDigit(hashMap, i)) {                 flag = true;                 time += i;                 break;             }         }         if (!flag) {             return "-1";         }            // Return the maximum possible time         return time;     }        // Driver code     public static void main(String[] args)     {         int arr[] = { 0, 0, 0, 9 };         System.out.println(getMaxTime(arr));     } }

Python3

 # Python3 implementation of the approach  from collections import defaultdict    # Function to return the updated frequency  # map for the array passed as argument  def getFrequencyMap(arr, n):             hashMap = defaultdict(lambda:0)      for i in range(n):          hashMap[arr[i]] += 1                return hashMap         # Function that returns true if the passed  # digit is present in the map after  # decrementing it's frequency by 1  def hasDigit(hashMap, digit):             # If map contains the digit      if hashMap[digit] > 0:                 # Decrement the frequency of         # the digit by 1          hashMap[digit] -= 1                # True here indicates that the          # digit was found in the map          return True            # Digit not found      return False        # Function to return the maximum possible  # time_value in 24-Hours format  def getMaxtime_value(arr, n):             hashMap = getFrequencyMap(arr, n)      flag = False     time_value = ""             # First digit of hours can be     # from the range [0, 2]      for i in range(2, -1, -1):          if hasDigit(hashMap, i) == True:              flag = True             time_value += str(i)             break            # If no valid digit found      if not flag:         return "-1"            flag = False            # If first digit of hours was chosen as 2 then      # the second digit of hours can be      # from the range [0, 3]     if(time_value == '2'):         for i in range(3, -1, -1):             if hasDigit(hashMap, i) == True:                  flag = True                 time_value += str(i)                  break            # Else it can be from the range [0, 9]     else:         for i in range(9, -1, -1):             if hasDigit(hashMap, i) == True:                  flag = True                 time_value += str(i)                  break                    if not flag:          return "-1"            # Hours and minutes separator      time_value += ":"            flag = False            # First digit of minutes can be     # from the range [0, 5]      for i in range(5, -1, -1):          if hasDigit(hashMap, i) == True:              flag = True             time_value += str(i)              break                if not flag:         return "-1"            flag = False            # Second digit of minutes can be      # from the range [0, 9]      for i in range(9, -1, -1):          if hasDigit(hashMap, i) == True:              flag = True             time_value += str(i)              break                if not flag:         return "-1"            # Return the maximum possible      # time_value      return time_value         # Driver code  if __name__ == "__main__":             arr = [0, 0, 0, 9]      n = len(arr)     print(getMaxtime_value(arr, n))         # This code is contributed by  # Rituraj Jain

Output:

09:00

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : andrew1234, rituraj_jain