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 INPUT August Timeline 15 16 17 18 19 Alice (15-18) Bob (16-19) Overlap Input Values: arriveAlice "08-15" leaveAlice "08-18" arriveBob "08-16" leaveBob "08-19" Days/month: [31,28,31,30...] (Non-leap year) ALGORITHM STEPS 1 Convert to Day Number Parse MM-DD to day of year 08-15 --> 31+28+...+15 = 227 08-16 --> 228, 08-18 --> 230 08-19 --> 231 2 Find Overlap Start max(arriveA, arriveB) max(227, 228) = 228 3 Find Overlap End min(leaveA, leaveB) min(230, 231) = 230 4 Calculate Days end - start + 1 (if valid) 230 - 228 + 1 = 3 FINAL RESULT Days Together: Aug 16 Aug 17 Aug 18 Alice Bob Both Output: 3 OK - 3 days overlap (Aug 16, 17, 18) Key Insight: Convert dates to day-of-year numbers for easy arithmetic. The overlap is found by taking max(arrivals) as start and min(departures) as end. If start <= end, overlap = end - start + 1. Time Complexity: O(1) | Space Complexity: O(1) TutorialsPoint - Count Days Spent Together | Direct Overlap Calculation
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