LeetCode Problem Workspace
Number of Days Between Two Dates
Calculate the exact number of days between two dates using string parsing and arithmetic logic with consistent accuracy.
2
Topics
5
Code langs
3
Related
Practice Focus
Easy · Math plus String
Answer-first summary
Calculate the exact number of days between two dates using string parsing and arithmetic logic with consistent accuracy.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Math plus String
To solve this problem, convert each date string into a total day count from a fixed reference point, such as 1900-01-01. Subtract these totals to get the absolute number of days between the two dates. This approach ensures correct handling of leap years and varying month lengths, relying on precise math and string operations for parsing.
Problem Statement
Given two dates as strings in the format YYYY-MM-DD, write a program to determine the number of days between them. The solution must correctly handle leap years and varying month lengths, and return a non-negative integer representing the difference in days.
For example, given date1 = "2019-06-29" and date2 = "2019-06-30", the output should be 1. Another example is date1 = "2020-01-15" and date2 = "2019-12-31", which should return 15. Constraints: all dates are valid between 1971 and 2100.
Examples
Example 1
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Example details omitted.
Example 2
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Example details omitted.
Constraints
- The given dates are valid dates between the years 1971 and 2100.
Solution Approach
Parse Dates into Year, Month, Day
Split each input string by the '-' character to extract integers representing year, month, and day. This string-to-integer parsing is critical to feed the arithmetic calculations accurately.
Compute Days from a Fixed Reference
Implement a helper function f(date) that counts the total number of days from a base date like 1900-01-01 to the given date. Include leap year logic and month day accumulation. Subtract f(date1) from f(date2) and return the absolute value.
Handle Leap Years and Month Lengths
Use standard rules for leap years: divisible by 4 but not 100 unless divisible by 400. Maintain an array of month lengths for non-leap and leap years. This prevents off-by-one errors in the final day count.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(1) because date calculations involve fixed-size arithmetic regardless of input. Space complexity is O(1) as only constant variables and arrays for month lengths are used.
What Interviewers Usually Probe
- Expect clear handling of string parsing and date conversion logic.
- Look for awareness of leap years and month-specific day counts.
- Check for simplicity in computing total days without iterative counting from one date to another.
Common Pitfalls or Variants
Common pitfalls
- Ignoring leap years and producing off-by-one errors for February dates.
- Swapping date1 and date2 incorrectly or not taking absolute difference.
- Assuming all months have 30 or 31 days instead of using correct month lengths.
Follow-up variants
- Calculate business days only between two dates, skipping weekends.
- Include time in hours and minutes to compute the difference precisely.
- Determine the day of the week for each date in addition to the difference.
FAQ
What is the main approach to solve Number of Days Between Two Dates?
Convert each date to total days from a fixed reference using arithmetic and string parsing, then take the absolute difference.
How do leap years affect the calculation?
Leap years add an extra day in February, so the helper function must account for years divisible by 4, excluding 100 unless divisible by 400.
Can I assume months have fixed lengths?
No, each month has a specific number of days, and February varies by leap year; using an array of month lengths avoids miscalculations.
Do I need to worry about negative results?
No, always return the absolute difference between the two day counts regardless of which date comes first.
Is this problem best categorized under Math plus String?
Yes, it requires parsing strings into numerical components and applying arithmetic to compute the day difference accurately.
Solution
Solution 1: Mathematics
First, we define a function `isLeapYear(year)` to determine whether the given year `year` is a leap year. If it is a leap year, return `true`, otherwise return `false`.
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))Continue Topic
math
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
Math plus String
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Easy
Stay on this level to stabilize interview delivery.
arrow_forward