|
| 1 | +import bisect |
| 2 | + |
| 3 | +# My initial solution. Not correct solution |
| 4 | +class Solution(object): |
| 5 | + def nextClosestTime(self, time): |
| 6 | + """ |
| 7 | + :type time: str |
| 8 | + :rtype: str |
| 9 | + """ |
| 10 | + digits = list(time) |
| 11 | + digits.pop(2) |
| 12 | + sortedDigits = sorted(digits) |
| 13 | + for idx in range(len(digits) - 1, -1, -1): |
| 14 | + digit = digits[idx] |
| 15 | + nextPossibleDigitIdx = bisect.bisect_right(sortedDigits, digit) |
| 16 | + if nextPossibleDigitIdx >= len(digits): |
| 17 | + continue |
| 18 | + if idx == 3: |
| 19 | + digits[3] = sortedDigits[nextPossibleDigitIdx] |
| 20 | + break |
| 21 | + elif idx == 2 and int(sortedDigits[nextPossibleDigitIdx]) < 6: |
| 22 | + digits[2] = sortedDigits[nextPossibleDigitIdx] |
| 23 | + break |
| 24 | + elif idx == 1: |
| 25 | + if int(digits[0]) < 2: |
| 26 | + digits[1] = sortedDigits[nextPossibleDigitIdx] |
| 27 | + break |
| 28 | + elif int(digits[0]) == 2 and int(sortedDigits[nextPossibleDigitIdx]) < 4: |
| 29 | + digits[1] = sortedDigits[nextPossibleDigitIdx] |
| 30 | + break |
| 31 | + elif idx == 0: |
| 32 | + if int(sortedDigits[nextPossibleDigitIdx]) < 3: |
| 33 | + digits[0] = sortedDigits[nextPossibleDigitIdx] |
| 34 | + break |
| 35 | + else: |
| 36 | + digits[1] = digits[0] |
| 37 | + digits[2] = digits[0] |
| 38 | + digits[3] = digits[0] |
| 39 | + hours = digits[0:2] |
| 40 | + minuites = digits[2:] |
| 41 | + return "".join(hours) + ":" + "".join(minuites) |
| 42 | + |
| 43 | + |
| 44 | +# https://tinyurl.com/vupwnhw |
| 45 | +class Solution(object): |
| 46 | + def nextClosestTime(self, time): |
| 47 | + """ |
| 48 | + :type time: str |
| 49 | + :rtype: str |
| 50 | + """ |
| 51 | + hour, minuite = time.split(":") |
| 52 | + |
| 53 | + # Generate all possible 2 digit values |
| 54 | + # There are at most 16 sorted values here |
| 55 | + digits = sorted(set(hour + minuite)) |
| 56 | + twoDigitValues = [a+b for a in digits for b in digits] |
| 57 | + |
| 58 | + # Check if the next valid minute is within the hour |
| 59 | + minuiteIndex = twoDigitValues.index(minuite) |
| 60 | + if minuiteIndex + 1 < len(twoDigitValues) and twoDigitValues[minuiteIndex + 1] < "60": |
| 61 | + return hour + ":" + twoDigitValues[minuiteIndex + 1] |
| 62 | + |
| 63 | + # Check if the next valid hour is within the day |
| 64 | + hourIndex = twoDigitValues.index(hour) |
| 65 | + if hourIndex + 1 < len(twoDigitValues) and twoDigitValues[hourIndex + 1] < "24": |
| 66 | + return twoDigitValues[hourIndex + 1] + ":" + twoDigitValues[0] |
| 67 | + |
| 68 | + # Return the earliest time of the next day |
| 69 | + return twoDigitValues[0] + ":" + twoDigitValues[0] |
0 commit comments