Leetcode•Nov 23, 2026

Largest Time for Given Digits

Hazrat Ali

Leetcode

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.

 

Example 1:

Input: arr = [1,2,3,4]
Output: "23:41"
Explanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.

Example 2:

Input: arr = [5,5,5,5]
Output: ""
Explanation: There are no valid 24-hour times as "55:55" is not valid.

Solution


var largestTimeFromDigits = function(arr) {
    let maxTime = -1;

    for (let i = 0; i < 4; i++) {
        for (let j = 0; j < 4; j++) {
            for (let k = 0; k < 4; k++) {
                for (let l = 0; l < 4; l++) {

                    if (i === j || i === k || i === l ||
                        j === k || j === l || k === l) {
                        continue;
                    }

                    let hour = arr[i] * 10 + arr[j];
                    let minute = arr[k] * 10 + arr[l];

                    if (hour < 24 && minute < 60) {
                        maxTime = Math.max(
                            maxTime,
                            hour * 60 + minute
                        );
                    }
                }
            }
        }
    }

    if (maxTime === -1) {
        return "";
    }

    let hour = Math.floor(maxTime / 60);
    let minute = maxTime % 60;

    return (
        String(hour).padStart(2, "0") +
        ":" +
        String(minute).padStart(2, "0")
    );
};

Comments