#2409
Count Days Spent Together
EasyMathString
Approaches
💡
Intuition
Time Space
We can check each day of the year to see if both Alice and Bob are in Rome on that day. This approach is straightforward but inefficient as it checks every day individually.
⚙️
Algorithm
3 steps- 1Step 1: Convert the arrival and leave dates for Alice and Bob into a range of days (from 1 to 365).
- 2Step 2: Iterate through each day of the year and check if it falls within both Alice's and Bob's date ranges.
- 3Step 3: Count the total number of days that are common in both ranges.
solution.py22 lines
1# Full working Python code
2from datetime import datetime, timedelta
3
4def countDaysSpentTogether(arriveAlice, leaveAlice, arriveBob, leaveBob):
5 def date_to_day(date):
6 month, day = map(int, date.split('-'))
7 days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
8 return sum(days_in_month[:month-1]) + day
9
10 startAlice = date_to_day(arriveAlice)
11 endAlice = date_to_day(leaveAlice)
12 startBob = date_to_day(arriveBob)
13 endBob = date_to_day(leaveBob)
14
15 count = 0
16 for day in range(1, 366):
17 if (startAlice <= day <= endAlice) and (startBob <= day <= endBob):
18 count += 1
19 return count
20
21# Example usage
22print(countDaysSpentTogether('08-15', '08-18', '08-16', '08-19'))Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.