π Problem Details
- Title:
1360. Number of Days Between Two Dates
- Link: https://leetcode.com/problems/number-of-days-between-two-dates/
- Difficulty: Easy
- Tags/Categories: Strings
input strings
date1
anddate2
string formatYYYY-MM-DD
return the count for the number of days between two dates
πWhat Were My Initial Thoughts?
create a fixed size vector for each date of size 3
index 0 = year
index 1 = month
index 2 = day
compare the values at each index
multiply the abs between the years in date1 and date2 by 365 to represent the number of days difference
multiply the abs between the months in date1 and date2 by 12 to represents the numebr of days difference
get the abs between the days in date1 and date2
based on this sum, substract the number of days in months and days from the year multiple to get the number of days difference
This above approach does not take into account leap years and therefore will not work
π‘ Explanation of Solution
1. Parse both dates into {year,month,day}
2. Convert both dates into a consistent baseline, like total number of days since 1970-01-01
3. Substract the two day counts
β Complexity Analysis
π» Implementation of Solution
class Solution {
public:
// Days in each month (non-leap year)
const vector<int> daysInMonth = { 31,28,31,30,31,30,31,31,30,31,30,31 };
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int countDaysSince1971(string date) {
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));
int totalDays = 0;
// Add days for the years
for (int y = 1971; y < year; ++y) {
totalDays += isLeapYear(y) ? 366 : 365;
}
// Add days for the months in current year
for (int m = 1; m < month; ++m) {
totalDays += daysInMonth[m - 1];
if (m == 2 && isLeapYear(year)) {
totalDays += 1; // Leap day in Feb
}
}
// Add days for the current month
totalDays += day;
return totalDays;
}
int daysBetweenDates(string date1, string date2) {
return abs(countDaysSince1971(date1) - countDaysSince1971(date2));
}
};