Concise and straightforward Python solution


  • 0
    G

    Since all the possible time points is limited (24 * 60 possibilities), we simply keep adding 1 minute from the original time, and check if the set of the new time's digits is in the set of original time's digits. When we find the first one meet our requirement, we find the result. We can use str's build-in function zfill to fill the zero of each number. The time complexity is O(1).
    Here is the solution:

    class Solution(object):
        def nextClosestTime(self, time):
            """
            :type time: str
            :rtype: str
            """
            h, m = time.split(':')
            d_set = set(time)
            i, j = int(h), int(m)
            while True:
                j = j + 1
                if j == 60:
                    j = 0
                    i += 1
                    if i == 24:
                        i = 0
                if set(str(i).zfill(2) + str(j).zfill(2)) <= d_set:
                    break
            return str(i).zfill(2) + ':'+ str(j).zfill(2)
    

Log in to reply
 

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