Skip to content

Instantly share code, notes, and snippets.

@toritsejuFO
Last active May 28, 2021 08:09
Show Gist options
  • Save toritsejuFO/882eb41ba9a7ea8412f4218c7ff5c405 to your computer and use it in GitHub Desktop.
Save toritsejuFO/882eb41ba9a7ea8412f4218c7ff5c405 to your computer and use it in GitHub Desktop.
from datetime import timedelta
def convert_to_minutes(time):
hours, minutes = time.split(':')
return timedelta(hours=int(hours), minutes=int(minutes)).seconds // 60
def get_min_diff(times):
min_diff = None
for idx, _ in enumerate(times):
# Do nothing on first iteration to avoid out of range error
if idx == 0:
continue
# Compare adjacent differences
diff = times[idx] - times[idx - 1]
if min_diff == None or diff < min_diff:
min_diff = diff
return min_diff
def min_time_diff(times):
"""Main function
ASSUMPTIONS MADE: When a valid input type (a list) is passed,
each time string in the list is always a valid time format 'HH:MM'
Seriously though, why would Esther wake up and write down "io:90" or "hello" or "4",
doesn't make sense, she should probably get more sleep then :).
"""
# Handle invalid inputs
if times == None or type(times) != list or len(times) == 0: return []
# Handle these two cases in O(1)
if len(times) == 1: return convert_to_minutes(times[0])
if len(times) == 2: return abs(convert_to_minutes(times[0]) - convert_to_minutes(times[1]))
# Time complexity is O(n), since it loops through each element once
# Conversion happens in place, so space complexity remains O(1)
for idx, time in enumerate(times):
times[idx] = convert_to_minutes(time)
# Python built in sort function takes O(n log n)
times.sort()
# This takes O(n), since it loops through each element once
min_diff = get_min_diff(times)
# Total time complexity would be n + (n log n) + n,
# which is ultimately (n log n), being a superset of n
return min_diff
if __name__ == '__main__':
times = ['16:15', '16:00', '12:20']
diff = min_time_diff(times)
print(diff)
assert diff == 15
@meekg33k
Copy link

meekg33k commented May 28, 2021

Hello @toritsejuFO, congratulations 🎉 your solution has been selected as one of the winning solutions in Week 7 of #AlgorithmFridays.

Your solution is clean and readable and passed the test cases. I particularly like how you structured your code into separate functions. Really neat!

Out of the many winning solutions, only 3 will be selected for the $20 prize in a raffle draw. The raffle draw will hold today, Friday May 28 at 3.00pm WAT (7.00 am PST)

If you are interested in being a part of the raffle draw, please send me a DM on Twitter @meekg33k so I can share the event invite with you.

NB: Only solutions of participants who indicated interest in the raffle draw will be considered.

Thanks once again for participating and see you later today for Week 8 of #AlgorithmFridays.

@toritsejuFO
Copy link
Author

Thanks @meekg33k, appreciate your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment