Python 1360.py
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
# datetime needs to be there twice
one = datetime.datetime.strptime(max(date1, date2), "%Y-%m-%d")
two = datetime.datetime.strptime(min(date1, date2), "%Y-%m-%d")
return (one - two).days
Difficulty
and has an acceptance rate of about 52% (100k+ 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 defines a Solution class with a single method, daysBetweenDates, that computes the absolute number of days separating two dates expressed as strings in the ISO-8601 format (YYYY-MM-DD). The method relies on Python’s standard datetime module to perform parsing and arithmetic, ensuring that calendar rules such as month lengths and leap years are respected without additional manual logic.
Key Steps
The core of the algorithm consists of three distinct operations. The first operation selects the later of the two input dates by applying the built-in max function to the string representations. Because the format is year-month-day with leading zeros, lexical ordering coincides with chronological ordering, allowing a direct string comparison.
one = datetime.datetime.strptime(max(date1, date2), "%Y-%m-%d")
The second operation mirrors the first but selects the earlier date using min.
two = datetime.datetime.strptime(min(date1, date2), "%Y-%m-%d")
The final operation subtracts the earlier datetime object from the later one, yielding a timedelta instance. Accessing its days attribute extracts the integer count of whole days between the two dates, which the method returns.
return (one - two).days
These three statements together constitute the complete logical flow of the method.
Edge Cases Handled
The design implicitly addresses several edge conditions. When the two input strings represent the same calendar day, the max and min calls return identical values, the subtraction yields a zero-day timedelta, and the method returns 0. The reliance on datetime.strptime ensures that dates falling on February 29 in leap years are parsed correctly, while attempts to parse invalid dates (e.g., “2023-02-30”) would raise a parsing exception, consistent with the expectations of the datetime library. Because the ordering is performed on the string level before parsing, the method correctly handles inputs supplied in any order without requiring an explicit conditional swap.
Performance Characteristics
The implementation leverages highly optimized native code within the datetime module. Parsing each date string and performing a single subtraction are constant-time operations with negligible overhead. No iterative constructs or auxiliary data structures are introduced, keeping the runtime footprint minimal. By avoiding manual calendar calculations, the code benefits from the internal efficiencies of the standard library, resulting in fast execution even when invoked repeatedly.
ELI5 - Simplified Explanation
Imagine having two different pages on a calendar. The point of this code is to find out how many times the sun goes up and down between those two dates.
First, the computer looks at both dates to see which one comes later in time. It uses a special tool called datetime to read the dates correctly, just like how you might read the month and day on a wall calendar. It puts the date that happened further away in one spot and the date that happened sooner in another.
Once the dates are sorted, the computer simply subtracts the smaller one from the larger one. It is basically counting the jumps on a calendar from the starting day until the finishing day. By subtracting them, it finds the specific number of days that live in that gap.
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 | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Go | Python | TS | ||||
| Progiez | C++ | Java | Python | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lzl124631x | C++ | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1576: Replace All ?'s to Avoid Consecutive Repeating Characters
- problem 1716: Calculate Money in Leetcode Bank
- problem 2409: Count Days Spent Together
- 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