Count Days Spent Together - Problem

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

Input & Output

Example 1 — Partial Overlap
$ Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"
Output: 3
💡 Note: Alice is in Rome from Aug 15-18, Bob from Aug 16-19. They overlap on Aug 16, 17, and 18 = 3 days
Example 2 — No Overlap
$ Input: arriveAlice = "10-01", leaveAlice = "10-03", arriveBob = "11-01", leaveBob = "12-03"
Output: 0
💡 Note: Alice leaves on Oct 3, Bob arrives on Nov 1. No overlap period, so 0 days together
Example 3 — Complete Overlap
$ Input: arriveAlice = "09-01", leaveAlice = "10-19", arriveBob = "09-04", leaveBob = "09-09"
Output: 6
💡 Note: Bob's entire stay (Sep 4-9) is within Alice's stay (Sep 1 - Oct 19), so 6 days together

Constraints

  • All dates given in "MM-DD" format
  • All dates occur in the same non-leap year
  • 1 ≤ MM ≤ 12
  • 1 ≤ DD ≤ days in that month

Visualization

Tap to expand
Count Days Spent Together: Date Range OverlapAlice: 08-15 to 08-18, Bob: 08-16 to 08-19Alice: Aug 15-18Bob: Aug 16-19Overlap: Aug 16-18Day 227Day 230Day 228Day 231Step 1: Convert MM-DD to day numbers08-15 → Day 227, 08-18 → Day 23008-16 → Day 228, 08-19 → Day 231Step 2: Find overlap rangeStart = max(227, 228) = 228End = min(230, 231) = 230Step 3: Calculate days togetherDays = 230 - 228 + 1 = 3Output: 3 days together
Understanding the Visualization
1
Input
Two date ranges in MM-DD format for Alice and Bob
2
Process
Convert dates to day numbers and find overlap period
3
Output
Number of days both are present in Rome
Key Takeaway
🎯 Key Insight: Find overlap using max(arrival dates) and min(departure dates) for efficient O(1) solution
Asked in
Google 15 Amazon 12 Microsoft 8
12.0K Views
Medium Frequency
~15 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen