2409. Count Days Spent Together
1 min read
LeetCode Daily Problem: Count Days Spent Together
On this page
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].
Constraints:
- All dates are provided in the format
"MM-DD". - Alice and Bob's arrival dates are earlier than or equal to their leaving dates.
- The given dates are valid dates of a non-leap year.
Approach: Straight simulation
Two steps:
- Convert each
MM-DDdate to a day of the year. - Intersect the two intervals.
Code
python
class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def to_day(date: str):
month, day = int(date[:2]), int(date[-2:])
return sum(months[:month-1]) + day
a_start, a_end, b_start, b_end = to_day(arriveAlice),to_day(leaveAlice), to_day(arriveBob),to_day(leaveBob)
return max(0, min(a_end, b_end) - max(a_start, b_start)+1)Complexity
- Time: O(1) — at most 12 months are summed.
- Space: O(1).
SeriesDaily Problem →
TagsSimulation