Problem 2409

Abstract / Summary

Count the number of days two people stayed in the same city based on their travel schedules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
17 lines | 652 bytes | submitted December 6, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (60k+ submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 5.19 | σ = 1.74

Complexity Analysis

Time: constant
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
18 links | 8 authors | 6 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

11 solutions   December 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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