Skip to content
Related Articles

Related Articles

Improve Article

Maximum possible time that can be formed from four digits

  • Difficulty Level : Medium
  • Last Updated : 10 Jun, 2021

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 
 

 

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 its 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 <bits/stdc++.h>
using namespace std;
 
// Function to return the updated frequency map
// for the array passed as argument
map<int, int> getFrequencyMap(int arr[], int n)
{
    map<int, int> 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<int, int>* 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<int, int> 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[0] == '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<Integer, Integer> getFrequencyMap(int arr[])
    {
        HashMap<Integer, Integer> 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<Integer, Integer> 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<Integer, Integer> 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[0] == '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

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to return the updated frequency map
    // for the array passed as argument
    static Dictionary<int, int> getFrequencyMap(int []arr)
    {
        Dictionary<int, int> hashMap = new Dictionary<int, int>();
        for (int i = 0; i < arr.Length; i++)
        {
            if (hashMap.ContainsKey(arr[i]))
            {
                hashMap[arr[i]] = hashMap[arr[i]] + 1;
            }
            else
            {
                hashMap.Add(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 bool hasDigit(Dictionary<int, int> hashMap, int digit)
    {
 
        // If map contains the digit
        if (hashMap.ContainsKey(digit) && hashMap[digit] > 0)
        {
 
            // Decrement the frequency of the digit by 1
            hashMap[digit] = 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 in 24-Hours format
    static String getMaxTime(int []arr)
    {
        Dictionary<int, int> hashMap = getFrequencyMap(arr);
        int i;
        bool 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[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 };
        Console.WriteLine(getMaxTime(arr));
    }
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
 
      // JavaScript implementation of the approach
       
      // Function to return the updated frequency map
      // for the array passed as argument
      function getFrequencyMap(arr) {
        var hashMap = {};
        for (var i = 0; i < arr.length; i++) {
          if (hashMap.hasOwnProperty(arr[i])) {
            hashMap[arr[i]] = hashMap[arr[i]] + 1;
          } else {
            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
      function hasDigit(hashMap, digit) {
        // If map contains the digit
        if (hashMap.hasOwnProperty(digit) && hashMap[digit] > 0) {
          // Decrement the frequency of the digit by 1
          hashMap[digit] = 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 in 24-Hours format
      function getMaxTime(arr) {
        var hashMap = getFrequencyMap(arr);
        var i;
        var flag;
        var 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[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
      var arr = [0, 0, 0, 9];
      document.write(getMaxTime(arr));
       
 </script>
Output: 
09:00

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :