Magicsheet logo

Largest Time for Given Digits

Medium
100%
Updated 6/1/2025

Largest Time for Given Digits

1. What is this problem about?

The Largest Time for Given Digits coding problem gives you an array of 4 digits. Your task is to find the largest 24-hour time that can be formed using these digits. The time should be in the format "HH:MM". A valid 24-hour time ranges from 00:00 to 23:59. If no valid time can be formed, you return an empty string.

2. Why is this asked in interviews?

This problem is asked by Microsoft and Amazon because it tests a candidate's ability to handle permutations and constraints. Since there are only 4 digits, there are only 24 possible permutations (4!), making it an ideal problem for exhaustive enumeration or backtracking. It tests attention to detail, specifically the different ranges for the four digits (e.g., the first digit can't be > 2, the second digit depends on the first, and the third digit can't be > 5).

3. Algorithmic pattern used

This problem follows the Enumeration and Backtracking interview pattern. Since the input size is extremely small (fixed at 4), the simplest approach is to generate all permutations of the 4 digits. For each permutation, check if it forms a valid time. Among all valid times, track the one that represents the latest point in the day (which can be compared easily if you convert the time to total minutes from 00:00).

4. Example explanation

Digits: [1, 2, 3, 4]. Permutations to check:

  • "12:34" (Valid)
  • "23:41" (Valid)
  • "24:13" (Invalid, HH > 23)
  • "43:21" (Invalid, HH > 23) Among all valid ones like "23:41" and "12:34", "23:41" is the largest.

5. Common mistakes candidates make

The most frequent mistake is trying to build the time greedily (e.g., picking the largest digit for the first position). This often fails because picking a large first digit might leave you with invalid digits for the remaining slots (e.g., [1, 9, 6, 0] - if you pick '1' for the first pos, you can't form "19:..." because 6 is invalid for the first minute digit). Another error is forgetting that "00:00" is a valid time.

6. Interview preparation tip

For "Enumeration, Backtracking interview pattern" problems with small, fixed inputs, don't over-engineer. A simple permutation generator is often more robust and easier to debug than a complex greedy approach with dozens of if-else conditions.

Similar Questions