πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- we can search up how many days are in each month and hard code them in an array 
- need to account for leap years (once every 4 years)

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

- helper function to check if the current year is a leap year
	- is the current year divisible by 4?
	- not divisible by 100
	- unless it is also divisible ny 400

βŒ› Complexity Analysis

Time Complexity: O(1)
	- the problem is solved in constant time with a specific time complexity of O(12)
	- regardles of the input date, we are only every going to iterate through 12 months of the year

Space Complexity: O(1)
	- our months array is fixed in size and will not grow

πŸ’» Implementation of Solution

class Solution {
 
public:
 
    int daysInEachMonth[12] = { 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 dayOfYear(string date) {
        
        //e.g. str --> YYYY-MM-DD
        int year = stoi(date.substr(0, 4));
        int month = stoi(date.substr(5, 2));
        int day = stoi(date.substr(8,2));
 
        int totalDays = day; // Start with the current day's value
 
 
        // Adjust for leap year if date is after February
        if(month > 2 && isLeapYear(year)) {
            totalDays++;
        }
 
        // Sum the days of previous months
        for(int i = 0; i < month - 1; i++) {
            totalDays += daysInEachMonth[i];
        }
 
        return totalDays;   
    }
};