Welcome to Subscribe On Youtube

3986. Number of Elapsed Seconds Between Two Times

Description

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 == 8
  • endTime.length == 8
  • startTime and endTime are valid times in the format "HH:MM:SS"
  • 00 <= HH <= 23
  • 00 <= MM <= 59
  • 00 <= SS <= 59
  • endTime is not earlier than startTime

Solutions

Solution 1: Simulation

Convert each time string into the number of seconds elapsed since $00$:$00$:$00$, i.e. $HH \times 3600 + MM \times 60 + SS$, then return the difference between the two values.

The time complexity is $O(1)$, and the space complexity is $O(1)$.

  • class Solution {
        public int secondsBetweenTimes(String startTime, String endTime) {
            return f(endTime) - f(startTime);
        }
    
        private int f(String s) {
            return Integer.parseInt(s.substring(0, 2)) * 3600 + Integer.parseInt(s.substring(3, 5)) * 60
                + Integer.parseInt(s.substring(6));
        }
    }
    
  • class Solution {
    public:
        int secondsBetweenTimes(string startTime, string endTime) {
            return f(endTime) - f(startTime);
        }
    
    private:
        int f(const string& s) {
            return stoi(s.substr(0, 2)) * 3600
                + stoi(s.substr(3, 2)) * 60
                + stoi(s.substr(6));
        }
    };
    
  • 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)
    
    
  • func secondsBetweenTimes(startTime string, endTime string) int {
    	return f(endTime) - f(startTime)
    }
    
    func f(s string) int {
    	h, _ := strconv.Atoi(s[:2])
    	m, _ := strconv.Atoi(s[3:5])
    	sec, _ := strconv.Atoi(s[6:])
    	return h*3600 + m*60 + sec
    }
    
    
  • function secondsBetweenTimes(startTime: string, endTime: string): number {
        return f(endTime) - f(startTime);
    }
    
    function f(s: string): number {
        return parseInt(s.slice(0, 2)) * 3600 + parseInt(s.slice(3, 5)) * 60 + parseInt(s.slice(6));
    }
    
    

All Problems

All Solutions