Taro Logo

Largest Time for Given Digits

#2 Most AskedMedium
0 views
Topics:
ArraysStringsRecursion

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the exact format of the input array? Will it always contain exactly four integers, or could the size vary?
  2. Are the input digits guaranteed to be single-digit integers (0 through 9), or could there be negative numbers, numbers greater than 9, or null/invalid entries?
  3. If multiple valid 24-hour times can be formed from the given digits, are we expected to return the latest chronological time among them?
  4. What should be returned if no valid 24-hour time can be constructed from the provided digits (e.g., an empty string "", null, or something else)?
  5. How should duplicate values in the input array be handled when using each digit exactly once (e.g., if the input is [2, 2, 2, 2])?

Brute Force Solution

Approach

Imagine you are given four single-digit tiles and need to arrange them to form the latest possible valid time of day on a 24-hour clock. The brute force approach relies on trying every single possible arrangement of the four digits to see which ones make a legal time and then picking the biggest one.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the four given digits and considering every possible way to line them up in a row.
  2. For each specific arrangement, check if it forms a valid time on a 24-hour clock, meaning the first two digits form a number from zero to twenty-three, and the last two digits form a number from zero to fifty-nine.
  3. If the arrangement does not form a valid time, completely ignore it and move on to the next possibility.
  4. If the arrangement does form a valid time, write it down and compare it against any previous valid times you found.
  5. Keep track of the largest or latest time seen so far as you test each new possibility.
  6. Once you have checked every single possible arrangement of the four digits, declare the largest valid time you found as your final answer.
  7. If none of the arrangements form a valid time, conclude that it is impossible to make a clock time out of the given digits.

Code Implementation

import itertools


def largest_time_from_digits(digit_list):
    # Generate all permutations to evaluate every possible sequence of the four input digits
    all_permutations = itertools.permutations(digit_list)
    
    latest_time_found = -1
    
    for current_permutation in all_permutations:
        hour_tens, hour_ones, minute_tens, minute_ones = current_permutation
        
        hour_value = hour_tens * 10 + hour_ones
        
        minute_value = minute_tens * 10 + minute_ones
        
        # Validate the constructed time against 24-hour clock rules to filter out illegal times
        if hour_value < 24 and minute_value < 60:
            total_time_minutes = hour_value * 60 + minute_value
            
            # Track the maximum valid time encountered so far to ensure we return the latest option
            if total_time_minutes > latest_time_found:
                latest_time_found = total_time_minutes
                
    # Handle cases where no valid time can be formed by returning an empty string
    if latest_time_found == -1:
        return ""
        
    final_hour_value = latest_time_found // 60
    
    final_minute_value = latest_time_found % 60
    
    return f"{final_hour_value:02d}:{final_minute_value:02d}"

Big(O) Analysis

Time Complexity
O(1) – Since we are always given exactly four digits for the clock time, the total number of possible arrangements (permutations) is fixed at 4 factorial, which equals 24. We iterate through these 24 permutations, performing a constant number of validation checks and comparisons for each one. Because the input size is strictly constant at four digits, the total operations do not scale with any variable input size n. Therefore, both the time complexity and the operation count are bound by a constant upper limit, simplifying to O(1).
Space Complexity
O(1) – The algorithm evaluates every possible arrangement of the four given digits, which means there are always a fixed maximum of 24 permutations to check. The auxiliary space required to store variables for tracking the current permutation, validating the time, and keeping the latest valid time seen so far consists of a few constant-sized primitive variables. Because the input size is strictly fixed at four digits and does not scale arbitrarily, the recursion stack and temporary storage do not grow with any variable N. Therefore, the extra memory used remains constant regardless of the input values, leading to an auxiliary space complexity of O(1).

Optimal Solution

Approach

Since there are only a very small number of ways to arrange four digits, the most reliable strategy is to test every single possible combination of the given digits to see which ones form a valid time. Among all the valid times you can build, you simply select the one that represents the latest time of day.

Here's how the algorithm would work step-by-step:

  1. Gather all the unique ways to rearrange the four given digits into a four-digit sequence.
  2. For every single rearrangement, check if the first two digits form a valid hour between zero and twenty-three.
  3. Next, check if the last two digits form a valid minute between zero and fifty-nine.
  4. Keep track of any rearrangement where both the hour and the minute are completely valid.
  5. Compare all the valid times you found and choose the one that occurs the latest in the day.
  6. If none of the rearrangements form a valid time, prepare to report that no valid time is possible.

Code Implementation

import itertools


def largest_time_from_digits(digit_list):
    latest_time_found = -1

    # Evaluating every permutation ensures we do not miss any valid time combination.
    for current_permutation in itertools.permutations(digit_list):
        hour_value = current_permutation[0] * 10 + current_permutation[1]
        minute_value = current_permutation[2] * 10 + current_permutation[3]

        # Restricting hours and minutes to standard limits filters out impossible clock times.
        if hour_value < 24 and minute_value < 60:
            total_time_in_minutes = hour_value * 60 + minute_value
            latest_time_found = max(latest_time_found, total_time_in_minutes)

    # Returning an empty string signifies that no valid time could be constructed.
    if latest_time_found == -1:
        return ""

    final_hour_part = latest_time_found // 60
    final_minute_part = latest_time_found % 60

    return f"{final_hour_part:02d}:{final_minute_part:02d}"

Big(O) Analysis

Time Complexity
O(1) – The input size is strictly fixed at exactly four digits for any given problem instance. Since the number of digits never changes, generating all possible permutations results in a constant number of combinations, specifically 24. We iterate through these 24 permutations with a fixed set of checks for valid hours and minutes, performing a constant amount of work each time. Because the total number of operations does not scale with a growing input size, the time complexity simplifies to O(1).
Space Complexity
O(1) – To generate every possible combination of the four digits, the algorithm uses a small temporary array or string of fixed size four to hold each rearrangement. Tracking the maximum valid time found so far only requires a few integer variables to store the best hour and minute combination. Since the number of digits is always exactly four, the total number of permutations is fixed at twenty-four, meaning the extra memory does not grow with any larger input size. Thus, the auxiliary space complexity is constant, simplifying to Big O notation of O(1).

Edge Cases

Input array has fewer than four elements
How to Handle:
Return an empty string immediately as a valid HH:MM time requires exactly four digits.
Input array has more than four elements
How to Handle:
Return an empty string or slice the input to strictly process the first four digits.
No valid 24-hour time can be formed from the given digits
How to Handle:
Return an empty string after checking all possible permutations and finding none that satisfy hour under 24 and minute under 60.
All four digits are identical
How to Handle:
Generate the single unique permutation and evaluate if it forms a valid time.
Input contains digits that make hours greater than 23
How to Handle:
Permutations resulting in hours from 24 to 99 are filtered out during the validation check.
Multiple valid times can be formed
How to Handle:
Iterate through all permutations, compare their numerical values, and retain the maximum valid time string.
Input array contains zeros
How to Handle:
Process them as standard digits while ensuring leading zeros in hours and minutes are correctly formatted.
Maximum possible input size is fixed at four elements
How to Handle:
Since the input size is constant, the algorithm runs in O(1) time complexity by evaluating all 24 permutations.
0/5 completed