Leetcode #1360: Number of Days Between Two Dates
In this guide, we solve Leetcode #1360 Number of Days Between Two Dates in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Write a program to count the number of days between two dates. The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Math, String
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Python Solution
class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
def isLeapYear(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def daysInMonth(year: int, month: int) -> int:
days = [
31,
28 + int(isLeapYear(year)),
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
]
return days[month - 1]
def calcDays(date: str) -> int:
year, month, day = map(int, date.split("-"))
days = 0
for y in range(1971, year):
days += 365 + int(isLeapYear(y))
for m in range(1, month):
days += daysInMonth(year, m)
days += day
return days
return abs(calcDays(date1) - calcDays(date2))
Complexity
The time complexity is , where represents the number of years from the given date to 1971-01-01, and represents the number of months of the given date. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.