Number of Elapsed Seconds Between Two Times Problem
#3986
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3986.
You are given two valid times startTime and endTime, each represented as a string in the format "HH:MM:SS".
Return the number of seconds that have elapsed from startTime to endTime.
Example 1:
Input: startTime = "01:00:00", endTime = "01:00:25"
Output: 25
Explanation:
endTime is 25 seconds ahead of startTime.
Example 2:
Input: startTime = "12:34:56", endTime = "13:00:00"
Output: 1504
Explanation:
endTime is 25 minutes and 4 seconds ahead of startTime, which equals 1504 seconds.
Constraints:
startTime.length == 8endTime.length == 8startTimeandendTimeare valid times in the format"HH:MM:SS"00 <= HH <= 2300 <= MM <= 5900 <= SS <= 59endTimeis not earlier thanstartTime
Solution
Approach: Simulation
Convert each time to the number of seconds since 00:00:00, that is HH * 3600 + MM * 60 + SS, and return the difference between the two values.
Complexity: time O(1), space O(1).
class Solution:
def secondsBetweenTimes(self, startTime: str, endTime: str) -> int:
def f(s: str) -> int:
return int(s[:2]) * 3600 + int(s[3:5]) * 60 + int(s[6:])
return f(endTime) - f(startTime)