DDSA Solutions

2409. Count Days Spent Together

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

  1. 1Parse each date to day index 1..365 using month length table.
  2. 2Loop day from 1 to 365 (or use overlap formula: max(0, min(leaveA,leaveB) - max(arriveA,arriveB) + 1)).
  3. 3Increment when day lies in both inclusive intervals.
  4. 4Return count.

Example Walkthrough

Input: Alice 08-06 to 08-09, Bob 08-01 to 08-09

  1. 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