Leetcode #2409: Count Days Spent Together
In this guide, we solve Leetcode #2409 Count Days Spent Together in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Math, String
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
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.
Python Solution
class Solution:
def countDaysTogether(
self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str
) -> int:
a = max(arriveAlice, arriveBob)
b = min(leaveAlice, leaveBob)
days = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
x = sum(days[: int(a[:2]) - 1]) + int(a[3:])
y = sum(days[: int(b[:2]) - 1]) + int(b[3:])
return max(y - x + 1, 0)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.