We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Largest Time for Given Digits

Number: 986

Difficulty: Medium

Paid? No

Companies: Microsoft, Google, LiveRamp


Problem Description

Given an array of 4 digits, determine the largest possible 24-hour time (formatted as "HH:MM") that can be constructed using each digit exactly once. The hours "HH" must lie between 00 and 23 and the minutes "MM" between 00 and 59. If no valid time can be formed, return an empty string.


Key Insights

  • Generate all permutations of the 4 digits since the array is small.
  • Construct hours and minutes from each permutation and validate if they form a correct time.
  • Track the maximum valid time by comparing the numerical values.
  • Return the result in "HH:MM" format or an empty string if none exists.

Space and Time Complexity

Time Complexity: O(1) since the input size is fixed at 4 digits leading to 4! = 24 permutations. Space Complexity: O(1) extra space used for storing permutations and intermediate variables.


Solution

We use a brute-force permutation approach by generating all possible orders of the four digits. For each permutation, the first two digits form the hour and the last two digits form the minute. We validate if the hour is between 0 and 23 and the minute is between 0 and 59. We convert these validations into a numerical comparison (e.g., hour * 60 + minute) to easily determine the largest time. This method uses simple arithmetic and string manipulation and is efficient due to the very limited number of permutations. Edge cases where no valid time exists result in returning an empty string.


Code Solutions

# Import the permutations function from itertools
from itertools import permutations

def largestTimeFromDigits(arr):
    max_time = -1  # Store the maximum time found in minutes
    # Generate all possible permutations of the 4 digits
    for perm in permutations(arr):
        # Construct hour and minute from permutation
        hours = perm[0] * 10 + perm[1]
        minutes = perm[2] * 10 + perm[3]
        # Check if time is valid: hours in [0,23] and minutes in [0,59]
        if hours < 24 and minutes < 60:
            total_minutes = hours * 60 + minutes  # convert time to minutes
            max_time = max(max_time, total_minutes)  # update maximum
    # If no valid time was found, return an empty string
    if max_time == -1:
        return ""
    # Convert the maximum found minutes back to "HH:MM" format
    max_hours = max_time // 60
    max_minutes = max_time % 60
    return "{:02d}:{:02d}".format(max_hours, max_minutes)

# Example usage
print(largestTimeFromDigits([1,2,3,4]))  # Expected: "23:41"
← Back to All Questions