← All solutions
October 24Easy

Count days spent together

  • Math
  • String

Problem

Alice and Bob are traveling to Rome for separate business meetings.

You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format "MM-DD", corresponding to the month and day of the date.

Return the total number of days that Alice and Bob are in Rome together.

You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].

Solution

class Solution:
    def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
        lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        arriveLast = arriveBob
        leaveFirst = leaveAlice
        if arriveAlice > arriveBob:
            arriveLast = arriveAlice
        if leaveAlice > leaveBob:
            leaveFirst = leaveBob

        if leaveFirst < arriveLast:
            return 0
        monthArrive, dayArrive = arriveLast.split("-")
        monthLeave, dayLeave = leaveFirst.split("-")
        ans = -int(dayArrive)
        for month in range(int(monthArrive), int(monthLeave)):
            ans += lengths[month-1]

        ans += int(dayLeave) + 1
        return ans