#949
Medium Algorithms Largest time for given digits
Array String Backtracking Enumeration
35.8% acceptance
Feb 25, 2026
745
1072
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.
Solution
Rust
Time O(n³)
Space O(1)
impl Solution {
pub fn largest_time_from_digits(arr: Vec<i32>) -> String {
let mut best = -1i32;
let _digits = [0,1,2,3];
// Try all permutations of indices
for a in 0..4 {
for b in 0..4 {
if b == a { continue; }
for c in 0..4 {
if c == a || c == b { continue; }
let d = 6 - a - b - c; // remaining index
let h = arr[a]*10 + arr[b];
let m = arr[c]*10 + arr[d];
if h < 24 && m < 60 {
let t = h * 60 + m;
if t > best { best = t; }
}
}
}
}
if best == -1 { return "".to_string(); }
format!("{:02}:{:02}", best / 60, best % 60)
}
}