{x}
blog image

Count Days Spent Together

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

 

Example 1:

Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
Output: 3
Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3.

Example 2:

Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"
Output: 0
Explanation: There is no day when Alice and Bob are in Rome together, so we return 0.

 

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.

Solution Explanation for LeetCode 2409: Count Days Spent Together

This problem involves calculating the number of days two individuals, Alice and Bob, are both present in Rome given their arrival and departure dates. The solution focuses on efficient date manipulation to avoid complex calendar calculations.

Approach

The core idea is to:

  1. Determine the overlapping period: Find the latest arrival date (max) and the earliest departure date (min) between Alice and Bob. This defines the period when they are both in Rome.

  2. Convert dates to day numbers: Represent each date as a day number of the year. This simplifies comparison and avoids dealing with varying month lengths. We accomplish this by summing the days of preceding months plus the day of the current month.

  3. Calculate the overlap: Subtract the day number of the latest arrival from the day number of the earliest departure and add 1 to include both endpoints. If the result is negative, it means there's no overlap, and we return 0.

Time and Space Complexity

  • Time Complexity: O(1). The algorithm performs a fixed number of operations regardless of the input dates. The conversion to day numbers involves iterating through at most 12 months (a constant).

  • Space Complexity: O(1). The algorithm uses a constant amount of extra space to store the days array (month lengths) and intermediate variables.

Code Implementation (Python)

class Solution:
    def countDaysTogether(
        self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str
    ) -> int:
        days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]  # Days in each month
 
        def date_to_day(date_str: str) -> int:
            month, day = map(int, date_str.split('-'))
            day_num = sum(days[:month]) + day
            return day_num
 
        # Find the overlapping period
        start_day = max(date_to_day(arriveAlice), date_to_day(arriveBob))
        end_day = min(date_to_day(leaveAlice), date_to_day(leaveBob))
 
        # Calculate the number of overlapping days
        overlapping_days = max(0, end_day - start_day + 1)  # Handle cases with no overlap
        return overlapping_days
 

Code Implementation (Java)

class Solution {
    private int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Days in each month
 
    private int dateToDay(String dateStr) {
        String[] parts = dateStr.split("-");
        int month = Integer.parseInt(parts[0]);
        int day = Integer.parseInt(parts[1]);
        int dayNum = 0;
        for (int i = 1; i < month; i++) {
            dayNum += days[i];
        }
        dayNum += day;
        return dayNum;
    }
 
    public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) {
        int startDay = Math.max(dateToDay(arriveAlice), dateToDay(arriveBob));
        int endDay = Math.min(dateToDay(leaveAlice), dateToDay(leaveBob));
        return Math.max(0, endDay - startDay + 1);
    }
}

The other languages (C++, Go) follow a similar structure, adapting the syntax and data structures accordingly. The key is the efficient conversion from date strings to day numbers and the logic for finding and calculating the overlap.