KatInterview

681. Next Closest Time

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the next closest time using only the digits from a given time string in "HH:MM" format. "Next closest" implies the smallest possible time difference, which might mean the new time is on the next day (a wrap-around).

Solution

Next Closest Time in Python

class Solution:
    def nextClosestTime(self, time: str) -> str:
        # 1. Parse time to get initial minutes and collect allowed digits.
        h, m = map(int, time.split(':'))
        current_minutes = h * 60 + m
        
        allowed_digits = {int(d) for d in time if d != ':'}
        
        # 2. Simulate minute by minute.
        while True:
            # Increment by one minute, handling wrap-around.
            current_minutes = (current_minutes + 1) % (24 * 60)
            
            # Get new hours and minutes.
            next_h, next_m = divmod(current_minutes, 60)
            
            # Get the four digits of the new time.
            d1, d2 = divmod(next_h, 10)
            d3, d4 = divmod(next_m, 10)
            
            # 3. Check if all digits are allowed.
            if all(d in allowed_digits for d in [d1, d2, d3, d4]):
                # 4. If valid, format and return.
                return f"{next_h:02d}:{next_m:02d}"

Next Closest Time in Java

class Solution {
    public String nextClosestTime(String time) {
        // 1. Parse time to get initial minutes and collect allowed digits.
        int h = Integer.parseInt(time.substring(0, 2));
        int m = Integer.parseInt(time.substring(3, 5));
        int currentMinutes = h * 60 + m;
        
        Set<Integer> allowedDigits = new HashSet<>();
        for (char c : time.toCharArray()) {
            if (c != ':') {
                allowedDigits.add(c - '0');
            }
        }
        
        // 2. Simulate minute by minute.
        while (true) {
            // Increment by one minute, handling wrap-around.
            currentMinutes = (currentMinutes + 1) % (24 * 60);
            
            // Get new hours and minutes.
            int nextH = currentMinutes / 60;
            int nextM = currentMinutes % 60;
            
            // 3. Check if all digits of the new time are allowed.
            if (allowedDigits.contains(nextH / 10) &&
                allowedDigits.contains(nextH % 10) &&
                allowedDigits.contains(nextM / 10) &&
                allowedDigits.contains(nextM % 10)) {
                
                // 4. If valid, format and return.
                return String.format("%02d:%02d", nextH, nextM);
            }
        }
    }
}

Next Closest Time in C++

class Solution {
public:
    string nextClosestTime(string time) {
        // 1. Parse time to get initial minutes and collect allowed digits.
        int h = stoi(time.substr(0, 2));
        int m = stoi(time.substr(3, 2));
        int current_minutes = h * 60 + m;
        
        unordered_set<int> allowed_digits;
        for (char c : time) {
            if (c != ':') {
                allowed_digits.insert(c - '0');
            }
        }
        
        // 2. Simulate minute by minute.
        while (true) {
            // Increment by one minute, handling wrap-around.
            current_minutes = (current_minutes + 1) % (24 * 60);
            
            // Get new hours and minutes.
            int next_h = current_minutes / 60;
            int next_m = current_minutes % 60;
            
            // Get the four digits of the new time.
            vector<int> next_digits = {next_h / 10, next_h % 10, next_m / 10, next_m % 10};
            
            // 3. Check if all digits are allowed.
            bool isValid = true;
            for (int digit : next_digits) {
                if (allowed_digits.find(digit) == allowed_digits.end()) {
                    isValid = false;
                    break;
                }
            }
            
            // 4. If valid, format and return.
            if (isValid) {
                string hh = (next_h < 10) ? "0" + to_string(next_h) : to_string(next_h);
                string mm = (next_m < 10) ? "0" + to_string(next_m) : to_string(next_m);
                return hh + ":" + mm;
            }
        }
        
        return ""; // Should not be reached due to problem constraints.
    }
};

Next Closest Time in TypeScript

function nextClosestTime(time: string): string {
    // 1. Parse time to get initial minutes and collect allowed digits.
    const [hStr, mStr] = time.split(':');
    const h = parseInt(hStr);
    const m = parseInt(mStr);
    
    const allowedDigits = new Set<number>();
    for (const char of time) {
        if (char !== ':') {
            allowedDigits.add(parseInt(char));
        }
    }
    
    let currentMinutes = h * 60 + m;
    
    // 2. Simulate minute by minute.
    while (true) {
        // Increment by one minute, handling wrap-around.
        currentMinutes = (currentMinutes + 1) % (24 * 60);
        
        // Get new hours and minutes.
        const nextH = Math.floor(currentMinutes / 60);
        const nextM = currentMinutes % 60;
        
        // Get the four digits of the new time.
        const d1 = Math.floor(nextH / 10);
        const d2 = nextH % 10;
        const d3 = Math.floor(nextM / 10);
        const d4 = nextM % 10;
        
        // 3. Check if all digits are allowed.
        if (allowedDigits.has(d1) && 
            allowedDigits.has(d2) &&
            allowedDigits.has(d3) &&
            allowedDigits.has(d4)) {
            
            // 4. If valid, format and return.
            const hh = String(nextH).padStart(2, '0');
            const mm = String(nextM).padStart(2, '0');
            return `${hh}:${mm}`;
        }
    }
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.