Problem 1360

Abstract / Summary

Calculate the number of days between two given dates using standard date handling methods.

Note

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

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

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (100k+ 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 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.

written by openai gpt

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.

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 = 5 | μ = 5.22 | σ = 1.93

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 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
25 links | 14 authors | 8 languages

Videos

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

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