Largest Time for Given Digits - Problem

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
  • 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.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,2,3,4]
Output: 23:41
💡 Note: The largest valid time is 23:41. We use digits 2,3 for hours (23 ≤ 23) and digits 4,1 for minutes (41 ≤ 59).
Example 2 — No Valid Time
$ Input: arr = [5,5,5,5]
Output: ""
💡 Note: No valid time can be formed. The smallest hour would be 55:55, but 55 > 23 for hours and 55 > 59 for minutes.
Example 3 — Edge Case with Zeros
$ Input: arr = [0,0,0,2]
Output: 20:00
💡 Note: The largest valid time is 20:00. We use 2,0 for hours (20 ≤ 23) and 0,0 for minutes (00 ≤ 59).

Constraints

  • arr.length == 4
  • 0 ≤ arr[i] ≤ 9

Visualization

Tap to expand
Largest Time for Given Digits INPUT Given 4 digits: 1 2 3 4 [0] [1] [2] [3] 24-Hour Format HH : MM HH: 00-23, MM: 00-59 Goal: Find LATEST time Use each digit exactly once arr = [1, 2, 3, 4] ALGORITHM STEPS 1 Sort Descending [1,2,3,4] --> [4,3,2,1] 2 Try Hours First Pick largest valid HH 4X? No. 3X? No. 2X? OK! 3 Build 23:XX Remaining: [4, 1] Pick largest valid MM 4 Validate Minutes 41 <= 59? OK! Final: 23:41 Greedy Selection: H1: max(d) where d<=2 --> 2 H2: max(d) where 2d<=23 --> 3 M1: max(d) where d<=5 --> 4 M2: remaining digit --> 1 FINAL RESULT 12 3 6 9 23:41 Latest Valid Time Hours: 23 (valid: 0-23) Minutes: 41 (valid: 0-59) Output: "23:41" Key Insight: The greedy approach works because we want the LARGEST time. Sort digits descending, then greedily pick the largest valid digit for each position (H1, H2, M1, M2) while respecting constraints: H1 in [0,2], H2 in [0,9] if H1<2 else [0,3], M1 in [0,5], M2 in [0,9]. Time: O(1), Space: O(1) TutorialsPoint - Largest Time for Given Digits | Optimized - Sort and Generate Greedily
Asked in
Google 45 Facebook 32 Amazon 28
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen