2409. Count Days Spent Together
EasyView on LeetCode
Time: O(1)
Space: O(1)
Problem Overview
Count calendar days both Alice and Bob are present in Rome.
Intuition
Count calendar days both Alice and Bob are present in Rome. Convert MM-DD strings to day-of-year numbers, then count days d where arriveAlice ≤ d ≤ leaveAlice and arriveBob ≤ d ≤ leaveBob.
Algorithm
- 1Parse each date to day index 1..365 using month length table.
- 2Loop day from 1 to 365 (or use overlap formula: max(0, min(leaveA,leaveB) - max(arriveA,arriveB) + 1)).
- 3Increment when day lies in both inclusive intervals.
- 4Return count.
Example Walkthrough
Input: Alice 08-06 to 08-09, Bob 08-01 to 08-09
- 1.Overlap days 08-06 through 08-09 → 4 days together.
Output: 4
Common Pitfalls
- •Non-leap-year calendar in problem — fixed month lengths.
- •Intervals are inclusive on both ends.
- •Overlap formula avoids loop if you prefer O(1).
2409.cs
C#
// Approach: Convert all dates to day-of-year integers using a prefix-sum of month lengths.
// The overlap is max(0, min(leaveA, leaveB) - max(arriveA, arriveB) + 1), computed by
// iterating all 365 days checking membership in both intervals.
// Time: O(1) Space: O(1)
public class Solution
{
public int CountDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob)
{
int arriveA = ToDays(arriveAlice);
int leaveA = ToDays(leaveAlice);
int arriveB = ToDays(arriveBob);
int leaveB = ToDays(leaveBob);
int ans = 0;
for (int day = 1; day <= 365; ++day)
{
if (arriveA <= day && day <= leaveA && arriveB <= day && day <= leaveB)
++ans;
}
return ans;
}
private readonly int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
private int ToDays(string s)
{
int month = (s[0] - '0') * 10 + (s[1] - '0');
int day = (s[3] - '0') * 10 + (s[4] - '0');
int prevDays = 0;
for (int m = 1; m < month; ++m)
prevDays += days[m];
return prevDays + day;
}
}Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 29. Divide Two Integers(Medium)
- 66. Plus One(Easy)
- 67. Add Binary(Easy)
- 70. Climbing Stairs(Easy)