Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1360. Number of Days Between Two Dates - Leetcode Solution

Code Implementation

class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        from datetime import datetime
        fmt = "%Y-%m-%d"
        d1 = datetime.strptime(date1, fmt)
        d2 = datetime.strptime(date2, fmt)
        return abs((d2 - d1).days)
      
class Solution {
public:
    int daysBetweenDates(string date1, string date2) {
        auto days = [](string date) {
            int y, m, d;
            sscanf(date.c_str(), "%d-%d-%d", &y, &m, &d);
            if (m < 3) {
                y--;
                m += 12;
            }
            return 365 * y + y / 4 - y / 100 + y / 400 + (153 * m - 457) / 5 + d - 306;
        };
        return abs(days(date1) - days(date2));
    }
};
      
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

class Solution {
    public int daysBetweenDates(String date1, String date2) {
        LocalDate d1 = LocalDate.parse(date1);
        LocalDate d2 = LocalDate.parse(date2);
        return Math.abs((int)ChronoUnit.DAYS.between(d1, d2));
    }
}
      
var daysBetweenDates = function(date1, date2) {
    const d1 = new Date(date1);
    const d2 = new Date(date2);
    return Math.abs(Math.floor((d2 - d1) / (1000 * 60 * 60 * 24)));
};
      

Problem Description

The problem asks you to find the number of days between two given dates. The dates are provided as strings in the format "YYYY-MM-DD". You are guaranteed that both dates are valid, and the answer should be the absolute difference in days (i.e., it doesn't matter which date is earlier). The dates can be any valid calendar date, and you do not need to worry about time zones or times of day.

  • Input: Two strings, date1 and date2, each representing a date in YYYY-MM-DD format.
  • Output: An integer representing the absolute number of days between the two dates.
  • Constraints: Each date is valid. The answer should be non-negative.

Thought Process

At first glance, the task seems straightforward: subtract one date from the other and get the number of days. However, working with dates requires handling leap years, different month lengths, and the correct parsing of date strings.

A brute-force approach might be to increment one day at a time from the earlier date to the later one, counting the steps. But this would be inefficient, especially for dates that are years apart.

Instead, we can leverage built-in date libraries in most languages that handle all these details for us. By converting the date strings into date objects, we can simply subtract them to get the difference in days. If the language does not have such libraries, we can compute the number of days since a reference date (like 1970-01-01 or 0000-03-01) for both dates and subtract those values.

The key realization is that date arithmetic is a solved problem in most standard libraries, and we should use those tools when available.

Solution Approach

  • Step 1: Parse the Input Dates
    • Convert the input strings date1 and date2 into date objects using the language's date parsing functionality.
  • Step 2: Compute the Difference
    • Subtract one date object from the other. This gives you a time difference, typically in days or milliseconds.
    • If the result is not already in days, convert it by dividing by the appropriate factor (e.g., milliseconds per day).
  • Step 3: Take the Absolute Value
    • Since the order of dates does not matter, take the absolute value of the difference.
  • Step 4: Return the Result
    • Return the calculated number of days as an integer.

If your language does not have convenient date libraries, you can implement a helper function to convert a date into the number of days since a fixed reference point, accounting for leap years and varying month lengths.

Example Walkthrough

Let's take an example:

  • date1 = "2019-06-29"
  • date2 = "2019-06-30"

Step 1: Parse both strings into date objects representing June 29, 2019, and June 30, 2019.

Step 2: Subtract the two dates: June 30, 2019 minus June 29, 2019 is 1 day.

Step 3: Take the absolute value, which is still 1.

Step 4: Return 1 as the answer.

For a more complex example:

  • date1 = "2020-01-15"
  • date2 = "2019-12-31"

The difference is 15 days (from December 31, 2019 to January 15, 2020). The process is the same: parse, subtract, take absolute value, and return.

Time and Space Complexity

  • Brute-force Approach:
    • If you incremented one day at a time from the earlier date to the later one, the time complexity would be O(N), where N is the number of days between the two dates. This is inefficient for large date ranges.
  • Optimized Approach (using date libraries or direct calculation):
    • Parsing the date strings and computing the difference is O(1), since all operations are done in constant time regardless of the actual dates.
    • Space complexity is also O(1), as we only store a few variables (the parsed dates and the result).

Thus, the optimized solution is both time and space efficient.

Summary

To solve the "Number of Days Between Two Dates" problem, we take advantage of date parsing and arithmetic provided by most programming languages. By converting the input strings to date objects and subtracting them, we can efficiently compute the absolute number of days between any two valid dates. This approach is elegant, concise, and leverages built-in functionality to handle leap years and varying month lengths, making the solution robust and easy to understand.