Skip to main content
Back to problems
#681
Medium Algorithms

Next closest time

Hash Table String Backtracking Enumeration
47.0% acceptance
Mar 31, 2026
742
1078
Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused. You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn next_closest_time(time: String) -> String {
    let bytes = time.as_bytes();
    let digits: Vec<u8> = vec![bytes[0] - b'0', bytes[1] - b'0', bytes[3] - b'0', bytes[4] - b'0'];
    let mut sorted = digits.clone();
    sorted.sort();
    sorted.dedup();
    
    let cur_minutes = (digits[0] * 10 + digits[1]) as i32 * 60 + (digits[2] * 10 + digits[3]) as i32;
    let mut best = -1i32;
    let mut best_diff = i32::MAX;
    
    for &a in &sorted {
      for &b in &sorted {
        let h = a * 10 + b;
        if h >= 24 { continue; }
        for &c in &sorted {
          for &d in &sorted {
            let m = c * 10 + d;
            if m >= 60 { continue; }
            let total = h as i32 * 60 + m as i32;
            let diff = ((total - cur_minutes) % 1440 + 1440) % 1440;
            let diff = if diff == 0 { 1440 } else { diff };
            if diff < best_diff {
              best_diff = diff;
              best = total;
            }
          }
        }
      }
    }
    format!("{:02}:{:02}", best / 60, best % 60)
  }
}