Problem Description
Alice and Bob have their travel schedules to Rome specified by arrival and departure dates in the "MM-DD" format. Both will stay in Rome on all days from their arrival date to their departure date (inclusive). The goal is to find out how many days both are in Rome together.
Key Insights
- Convert the "MM-DD" string into a day-of-year representation using an array of days per month.
- Determine the overlapping period by taking the maximum of both arrival dates and the minimum of both departure dates.
- The total overlapping days is the difference plus one, and if there is no overlap, return zero.
Space and Time Complexity
Time Complexity: O(1) – The solution involves a constant amount of work. Space Complexity: O(1) – Only a fixed number of variables are used and no extra space is required.
Solution
We start by converting each date from the "MM-DD" format into its numerical day-of-year equivalent. This is done by precomputing the number of days in each month for a non-leap year. Once every date is converted, the overlapping period is simply the period from the later arrival date (maximum of both arrival days) to the earlier departure date (minimum of both departure days). If the calculated overlap is negative, it means there is no period when both are in Rome together. Otherwise, the number of days spent together is the difference between the overlapping end and start plus one.