Calculating Simple Time Difference in Python

1 min read 263 words

The challenge

In this challenge, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any.

Examples:

# If the alarm goes off now, it will not go off for another 23 hours and 59 minutes.
solve(["14:51"]) = "23:59"

# The max interval that the alarm will not go off is 11 hours and 40 minutes.
solve(["23:00","04:22","18:05","06:24"]) == "11:40"

In the second example, the alarm goes off 4 times in a day.

The solution in Python code

Option 1:

from datetime import datetime

def solve(arr):
    dts = [datetime(2000, 1, 1, *map(int, x.split(':'))) for x in sorted(arr)]
    delta = max(int((b - a).total_seconds() - 60) for a, b in zip(dts, dts[1:] + [dts[0].replace(day=2)]))
    return '{:02}:{:02}'.format(*divmod(delta//60, 60))

Option 2:

def solve(arr):
    arr = sorted(int(m[:2]) * 60 + int(m[3:]) for m in set(arr))
    arr += [arr[0] + 1440]
    h, m = divmod(max(arr[i + 1] - arr[i] - 1 for i in range(len(arr) - 1)), 60)
    return "{:02}:{:02}".format(h, m)

Option 3:

def minutes(s):
    return int(s[0:2]) * 60 + int(s[-2:])

def timeformat(m):
    return "{:02d}:{:02d}".format(m // 60, m % 60)

def solve(arr):
    arr = list(set(arr))
    m = [minutes(arr) for arr in sorted(arr)]
    difference = [(m[(i+1)%len(m)] - a - 1)  % (60*24) for i, a in enumerate(m)]

    return(timeformat(max(difference)))

Test cases to validate our solution

test.it("Basic tests")
test.assert_equals(solve(["14:51"]), "23:59")
test.assert_equals(solve(["23:00","04:22","18:05","06:24"]),"11:40") 
test.assert_equals(solve(["21:14", "15:34", "14:51", "06:25", "15:30"]),"09:10")
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags