# JAVA straightforward solution (No brute force here)

• The idea here is to change one digit to the next larger one, then change all the digits after it to the smallest digit, then check if it is a valid time representation. If the digit is already the largest, move to the digit before it, repeat. `arr` is to store the digits in original order. `arr2` is to store the digits in ascending order. arr3 is to store the changed digits. `map` here is to help get the index by O(1) time.

``````class Solution {
public String nextClosestTime(String time) {
int[] arr = new int[4];
int[] arr2 = new int[4];
int[] arr3 = new int[4];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0, j = 0; i < 5; i++) {
if (i == 2) continue;
arr[j] = time.charAt(i) - '0';
arr2[j] = time.charAt(i) - '0';
arr3[j] = time.charAt(i) - '0';
j++;
}
Arrays.sort(arr2);
for (int i = 0; i < 4; i++) {
map.put(arr2[i], i);
}
for (int i = 3; i >= 0; i--) {
int ind = map.get(arr[i]);
if (ind < 3) {
arr3[i] = arr2[ind + 1];
for (int j = i + 1; j < 4; j++) {
arr3[j] = arr2[0];
}
if (arr3[0] * 10 + arr3[1] < 24 && arr3[2] * 10 + arr3[3] < 60) {
return "" + arr3[0] + arr3[1] + ":" + arr3[2] + arr3[3];
}
}
}
return "" + arr2[0] + arr2[0] + ":" + arr2[0] + arr2[0];
}
}``````

• easy to understand, same idea with mine.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.