Leetcode 949. Largest Time for Given Digits

Problem Explanation

The task at hand involves generating the largest valid 24-hour time from an array of 4 digits. The time format will be HH:MM where HH ranges from "00" to "23" and MM ranges from "00" to "59".

For instance, if the input array is [1,2,3,4], the largest valid time would be "23:41".

If the digits in the array cannot generate a valid time, we will return an empty string. For example, if the input array is [5,5,5,5], it is impossible to generate a valid 24-hour time, hence the output will be an empty string.

Approach

The solution demonstrated here utilizes a simple brute-force approach by generating all permutations of the 4 digits in the array. It makes use of nested loops to generate these permutations and subsequently check if they form valid 'hour' and 'minute' parts of a 24-hour time notation. If a permutation forms valid 'hour' and 'minute' times, it tracks the maximum time formed as it iterates.

Let's take a look at the steps, using [1,2,3,4] as an illustrative example:

  1. Initialise an empty string ans.
  2. Loop through each element in the array (i.e., hours and minutes) - a. Make sure the indices selected for elements are unique. If not, skip the iteration. b. Generate the hours and minutes strings. The minutes string is formed by using the remaining two indices not used in the hour formation. c. Check if the hours are less than "24" and minutes are less than "60" to ensure valid 24-hour time. d. If valid, compare this time with ans and update ans with the larger time.
  3. Once all possibilities are checked, return ans, which will be the largest valid 24-hour time.

C++ Solution

1
2cpp
3class Solution {
4 public:
5  string largestTimeFromDigits(vector<int>& arr) {
6    string ans;
7    for (int i = 0; i < 4; ++i)
8      for (int j = 0; j < 4; ++j)
9        for (int k = 0; k < 4; ++k) {
10          if (i == j || i == k || j == k) // Make sure indices are unique.
11            continue;
12          const string hours = to_string(arr[i]) + to_string(arr[j]);
13          const string minutes = to_string(arr[k]) + to_string(arr[6 - i - j - k]);  // Remaining indices used.
14          if (hours < "24" && minutes < "60") // Check for valid time.
15            ans = max(ans, hours + ':' + minutes);  // Update with the larger time.
16        }
17    return ans;  // Return the largest valid time.
18  }
19};

Note: A translation of this solution into Python, Java, Javascript, and C# is not directly feasible due to the language-specific syntax and feature used in this problem (especially, forming hours and minutes as string and comparing them directly). However, an adapted form of this solution can certainly be implemented in those languages.# Python Solution Here is the Python solution for the problem. We use itertools' permutations function to find all permutations of the given array. We then iterate through all permutations and find out the maximum valid time.

1
2python
3from itertools import permutations
4
5def largestTimeFromDigits(arr):
6    max_time = -1
7    for h, i, j, k in permutations(arr):
8        hour = h*10 + i
9        minute = j*10 + k
10        if hour < 24 and minute < 60:
11            max_time = max(max_time, hour * 60 + minute)
12
13    if max_time == -1:
14        return ""
15    else:
16        return "{:02d}:{:02d}".format(max_time // 60, max_time % 60)

Java Solution

Java does not have a built-in permutation function. We can generate the permutations ourselves using for loops.

1
2java
3public String largestTimeFromDigits(int[] arr) {
4    String ans = "";
5    for (int i = 0; i < 4; ++i)
6      for (int j = 0; j < 4; ++j)
7        for (int k = 0; k < 4; ++k) {
8          if (i == j || i == k || j == k)
9            continue;
10          String h = "" + arr[i] + arr[j],
11                 m = "" + arr[k] + arr[3 - i - j - k],
12                 t = h + ":" + m;
13          if (h.compareTo("24") < 0 && m.compareTo("60") < 0 && ans.compareTo(t) < 0)
14            ans = t;
15        }
16    return ans;
17 }

JavaScript Solution

In the JavaScript solution, let's use the permutation approach in a similar manner. Here we're using nested loops for iteration.

1
2javascript
3function largestTimeFromDigits(arr) {
4    let ans = -1;
5    for (let i = 0; i < 4; i++){
6        for (let j = 0; j < 4; j++){
7            if (j != i) {
8                for (let k = 0; k < 4; k++){
9                    if (k != i && k != j) {
10                        let l = 6 - i - j - k;
11                        let hours = 10 * arr[i] + arr[j];
12                        let mins = 10 * arr[k] + arr[l];
13                        if (hours < 24 && mins < 60)
14                            ans = Math.max(ans, hours * 60 + mins);
15                    }
16                }
17            }
18        }
19    }
20    return (ans >= 0) ? `${Math.floor(ans / 60).toString().padStart(2, '0')}:${(ans % 60).toString().padStart(2, '0')}`: "";
21}

These solutions iterate over all permutations of array indices and filter out valid times, keeping track of the maximum one. The time complexity is O(1) as there is a constant number of permutations for a four-element array. The space complexity is also O(1).


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫