Count Days Spent Together — LeetCode 2409 Python Solution

EasyMathString
Problem
#2409
Reading time
2 min

The problem

Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob.

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

Python
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

MeasureComplexity
TimeO(C)
SpaceO(C) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2409. Count Days Spent Together is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2409. Count Days Spent Together?
LeetCode 2409. Count Days Spent Together is rated Easy on LeetCode.
What is the time complexity of LeetCode 2409. Count Days Spent Together?
The Python solution on this page runs in O(C).
What is the space complexity of LeetCode 2409. Count Days Spent Together?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 2409. Count Days Spent Together cover?
LeetCode 2409. Count Days Spent Together is tagged Math and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview