Python 2409.py
class Solution:
def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
# brute force
months = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] # prepend zero such that months[1] is January
result = 0
for m in range(1, 12 + 1):
for d in range(1, months[m] + 1):
today = f"{m:02}-{d:02}"
if today > leaveAlice or today > leaveBob:
break
if arriveAlice <= today <= leaveAlice and arriveBob <= today <= leaveBob:
result += 1
return result
Difficulty
and has an acceptance rate of about 48% (60k+ submissions).
Typical patterns to solve this problem:
- Math
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the number of calendar days on which Alice and Bob are simultaneously present, given their arrival and departure dates in “MM-DD” format. The algorithm iterates over every day of the year, builds a string representation for each date, and checks whether that day falls within both individuals’ intervals. A counter is incremented for each overlapping day, and the final count is returned.
Key Steps
The method begins by defining a month-length table that includes a leading zero so that the index matches the month number.
months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
A result accumulator is initialized to zero.
result = 0
Two nested loops enumerate every month (1 through 12) and every day within that month. The inner loop constructs a string today in the required “MM-DD” format, using zero-padding to guarantee two-digit components.
for m in range(1, 13):
for d in range(1, months[m] + 1):
today = f"{m:02}-{d:02}"
Before performing the overlap test, the algorithm checks whether the current today exceeds either departure date. If it does, the inner loop is terminated early because later days in the same month will also be beyond the departure bound.
if today > leaveAlice or today > leaveBob:
break
The core overlap condition verifies that today lies within both Alice’s and Bob’s intervals. When the condition holds, the result counter is incremented.
if arriveAlice <= today <= leaveAlice and arriveBob <= today <= leaveBob:
result += 1
After all months have been processed, the accumulated count is returned.
return result
Edge Cases Handled
The string-based comparison works correctly for dates that cross month boundaries because the “MM-DD” format preserves lexical ordering identical to chronological ordering within a single year. Consequently, intervals that start later in the year and end earlier (e.g., “12-01” to “01-15”) are not possible under the problem constraints, and the code naturally excludes such inputs without additional logic.
When either arrival date is later than the other’s departure date, the overlap condition fails for every day, resulting in a zero count. The early-break condition also prevents unnecessary iteration once the later of the two departure dates is passed, ensuring that no days beyond the valid range are examined.
The month table includes February as 28 days, matching the non-leap-year assumption of the problem. Therefore, dates such as “02-29” are never generated, and the algorithm safely avoids invalid date generation.
Performance Optimizations Observed
The most notable optimization is the early termination of the inner day loop when the current date exceeds either participant’s departure date. By breaking out of the day loop, the algorithm avoids iterating over the remaining days of the month once it is certain that no further overlap can occur for that month. This reduces the total number of comparisons, especially when both participants leave early in the year.
Additionally, the use of pre-computed month lengths eliminates the need for runtime calendar calculations or library calls, keeping the inner loop lightweight. The string formatting operation f"{m:02}-{d:02}" is performed only once per day, and the subsequent lexical comparisons are simple constant-time operations.
Overall, the solution balances straightforward brute-force enumeration with a targeted early-exit strategy, yielding a concise implementation that remains efficient for the bounded input size of a single year.
ELI5 - Simplified Explanation
Imagine a big shiny calendar on the wall that shows every single day of the year. Some days are special because Alice is busy, and some days are special because Bob is busy. This code is like a little helper that looks at every day of the year one by one.
First, the helper looks at a list that tells it how many days are in each month, like how January has thirty-one days. Then, it starts a loop to go through every month and every day. For each day, the helper creates a little label that looks like a date.
It checks if the day has already passed the time when either Alice or Bob left. If it is too late, the helper stops looking because there is no point in checking the rest of the year.
After that, the helper asks a question about the current day. It checks if the day is between the time Alice arrived and left, and also if the day is between the time Bob arrived and left. If the answer is yes, it means both Alice and Bob are there at the same time. Every time that happens, the helper keeps track of it by adding one to a total count. It keeps doing this until the end of the year so it knows exactly how many days they get to spend together.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||
|---|---|---|---|---|---|---|---|
| author | solutions | ||||||
| www | AlgoMonster | Python | Java | C++ | TS | ||
| WalkCCC | Python | Java | C++ | ||||
| leetcode.ca | Python | Java | C++ | Go | |||
| Progiez | Python | Java | C++ | ||||
| github | charles-wangkai | Java | |||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| qiyuangong | Python | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| qiyuangong | Python |
Videos
Similar Problems
- problem 1360: Number of Days Between Two Dates
- problem 2224: Minimum Number of Operations to Convert Time
Solved On The Same Day
- problem 1360: Number of Days Between Two Dates
- problem 1576: Replace All ?'s to Avoid Consecutive Repeating Characters
- problem 1716: Calculate Money in Leetcode Bank
- problem 2515: Shortest Distance to Target String in a Circular Array
- problem 2644: Find the Maximum Divisibility Score
- problem 1110: Delete Nodes And Return Forest
- problem 1296: Divide Array in Sets of K Consecutive Numbers
- problem 1443: Minimum Time to Collect All Apples in a Tree
- problem 1669: Merge In Between Linked Lists
- problem 458: Poor Pigs
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality