LeetCode – Next Closest Time (Java)

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.

Example 1:

Input: “19:34”
Output: “19:39”
Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.

Java Solution

public String nextClosestTime(String time) {
    ArrayList<Integer> list = new ArrayList<>();
    ArrayList<Character> charList = new ArrayList<>();
    TreeSet<Integer> set = new TreeSet<>();
 
    //get digit list
    for (int i = 0; i < time.length(); i++) {
        if (time.charAt(i) >= '0' && time.charAt(i) <= '9') {
            charList.add(time.charAt(i));
        }
    }
 
    //get all possible number combinations
    for (int i = 0; i < charList.size(); i++) {
        for (int j = 0; j < charList.size(); j++) {
            set.add(Integer.parseInt(charList.get(i) + "" + charList.get(j)));
        }
    }
 
    //add to list
    list.addAll(set);
 
    String[] arr = time.split(":");
    int hour = Integer.parseInt(arr[0]);
    int min = Integer.parseInt(arr[1]);
 
    int idxMin = search(list, min);
    int idxHour = search(list, hour);
 
    String hh = "";
    String mm = "";
 
    if (idxMin < list.size() - 1 && list.get(idxMin + 1) < 60) {
        hh = hour + "";
        mm = list.get(idxMin + 1) + "";
    } else {
        if (idxHour < list.size() - 1 && list.get(idxHour + 1) < 24) {
            hh = list.get(idxHour + 1) + "";
            mm = list.get(0) + "";
        } else {
            hh = list.get(0) + "";
            mm = list.get(0) + "";
        }
    }
 
    if (hh.length() < 2) {
        hh = "0" + hh;
    }
 
    if (mm.length() < 2) {
        mm = "0" + mm;
    }
 
    return hh + ":" + mm;
}
 
private int search(ArrayList<Integer> list, int target) {
    int i = 0;
    int j = list.size() - 1;
 
    while (i < j) {
        int m = i + (j - i) / 2;
        if (list.get(m) < target) {
            i = m + 1;
        } else {
            j = m;
        }
    }
 
    return j;
}

2 thoughts on “LeetCode – Next Closest Time (Java)”

Leave a Comment