πŸ“ Problem Details

input strings date1 and date2 string format YYYY-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));
    }
};