S1Q2 · Absolute Time Difference Between Two Times¶
⚡ Quick Reference
Function: absolute_time_difference(time1: str, time2: str) -> str
Core idea: convert both times to total minutes, take the absolute difference, convert back to HH:MM.
def absolute_time_difference(time1, time2):
def to_minutes(t):
h, m = map(int, t.split(':'))
return h * 60 + m
diff = abs(to_minutes(time1) - to_minutes(time2))
return f"{diff // 60:02}:{diff % 60:02}"
Key rules:
- Convert HH:MM → total minutes: h * 60 + m
- Absolute difference = abs(minutes1 - minutes2)
- Convert back: hours = diff // 60, minutes = diff % 60
- Zero-pad with {val:02} to always produce two-digit output
Problem Statement¶
Problem
Write a function absolute_time_difference(time1, time2) that returns the absolute time difference between two HH:MM strings, also in HH:MM format.
Examples:
time1="14:30", time2="06:45"
"07:45"
time1="02:30", time2="03:10"
"00:40"
time1="23:59", time2="00:00"
"23:59"
Tracing all examples¶
| time1 | time2 | minutes1 | minutes2 | diff | Result |
|---|---|---|---|---|---|
"14:30" |
"06:45" |
870 | 405 | 465 | 465//60=7, 465%60=45 → "07:45" ✓ |
"06:45" |
"14:30" |
405 | 870 | 465 | → "07:45" ✓ (symmetric) |
"02:30" |
"03:10" |
150 | 190 | 40 | 40//60=0, 40%60=40 → "00:40" ✓ |
"23:59" |
"00:00" |
1439 | 0 | 1439 | 1439//60=23, 1439%60=59 → "23:59" ✓ |
Solution approaches¶
def absolute_time_difference(time1, time2):
# Parse time1
h1, m1 = map(int, time1.split(':'))
total1 = h1 * 60 + m1
# Parse time2
h2, m2 = map(int, time2.split(':'))
total2 = h2 * 60 + m2
# Absolute difference in minutes
diff_minutes = abs(total1 - total2)
# Convert back to HH:MM
hours = diff_minutes // 60
minutes = diff_minutes % 60
return f"{hours:02}:{minutes:02}"
Key takeaways¶
Convert to minutes for arithmetic, back to HH:MM for output
Time arithmetic is much simpler in a single unit (minutes). Convert both times to total minutes, subtract, take the absolute value, then reconstruct HH:MM with // 60 and % 60.
{val:02} - zero-pad to two digits
f"{hours:02}" pads with a leading zero if the value is a single digit. Without it, "00:40" would become "0:40" - wrong format. Always use :02 for both hours and minutes.
abs() makes the result order-independent
abs(total1 - total2) gives the same result regardless of which time is larger. No need to check which is earlier - the function is symmetric by design.