Pythonic approach to solving the minimum time difference problem

  • 0
    class Solution:
        def findMinDifference(self, timePoints):
            :type timePoints: List[str]
            :rtype: int
            # The number of timePoints
            l = len(timePoints)
            # The maximum difference we can have is 720 minutes, i.e. both time points are exactly 12 hours apart(12*60=720). Therefore are solution must be less than 721 minutes.
            diff = 721
            # Scrolling throught the list using 2 varaibles, i and j
            for i in range(l):
                for j in range(i+1, l):
                    # Getting both time points and splitting them based on ":".
                    t1 = timePoints[i].split(":")
                    t2 = timePoints[j].split(":")
                    # Calculating the time difference based in minutes.
                    timeDiff = (int(t1[0])*60 + int(t1[1])) - (int(t2[0])*60 + int(t2[1]))
                    # If the the second time points is greater than the first, i.e. the second time point is ahead in time, then we multiply the difference by -1 to get that difference. This always ensure our difference is positive and that we subtract the lesser value from the greater value.
                    if timeDiff < 0:
                        timeDiff *= -1
                    # If the time difference is less than 720, than we approached it from the correct angle.
                    if timeDiff < 24*60/2:
                        if timeDiff < diff:
                            diff = timeDiff
                        # If the time difference is greater than 720, than we can approach it from the other"direction". To do that we subtract the time difference from the total number of minutes in a day.
                        timeDiff = (24*60) - timeDiff
                        if timeDiff < diff:
                            diff = timeDiff
                    # If we acheive a time difference of 0, we will not be able to get a better solution. We return 0 and end our program.
                    if diff == 0:
                        return diff
            # Return the minimum time difference.
            return diff

Log in to reply

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