#1360
Number of Days Between Two Dates
EasyMathStringDate ManipulationMathematical Calculations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
Instead of counting each day, we can calculate the total number of days from a fixed date (like 1900-01-01) to each date and then find the difference. This is much faster.
⚙️
Algorithm
3 steps- 1Step 1: Create a function that calculates the number of days from a fixed date (e.g., 1900-01-01) to the given date.
- 2Step 2: Use this function to get the total days for both dates.
- 3Step 3: Return the absolute difference between the two day counts.
solution.py8 lines
1# Full working Python code
2from datetime import datetime
3
4def daysBetweenDates(date1: str, date2: str) -> int:
5 def countDays(date: str) -> int:
6 d = datetime.strptime(date, '%Y-%m-%d')
7 return (d - datetime(1900, 1, 1)).days
8 return abs(countDays(date1) - countDays(date2))ℹ
Complexity note: This is constant time complexity since we are performing a fixed number of operations regardless of the input size.
- 1Understanding how to manipulate date formats is crucial for solving date-related problems.
- 2Using a fixed reference date simplifies calculations significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.