algoadvance

Leetcode 1154. Day of the Year

Problem Statement:

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

For instance:

Clarifying Questions:

  1. Date Range Validity: Can we assume that the dates provided are always valid and within a reasonable range (e.g., 1900 onwards)?
  2. Leap Year Calculation: Should leap years be considered using the standard rules (every 4 years, but not every 100 years unless it’s divisible by 400)?

Strategy:

  1. Extract Date Components:
    • Parse the given string to extract YYYY, MM, and DD.
  2. Identify Day Counts for Each Month:
    • Use an array to represent the cumulative days until the start of each month (handle leap years separately).
  3. Leap Year Calculation:
    • Implement the leap year check as per the rules (divisible by 4, but not by 100 unless also divisible by 400).
  4. Compute Day of Year:
    • Sum up the days from the months before the current month and add the current day of the month.

Code:

#include <iostream>
#include <string>
#include <vector>

class Solution {
public:
    int dayOfYear(std::string date) {
        int year = std::stoi(date.substr(0, 4));
        int month = std::stoi(date.substr(5, 2));
        int day = std::stoi(date.substr(8, 2));

        std::vector<int> days_in_month_non_leap = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        std::vector<int> days_in_month_leap = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        // Function to check if a year is a leap year
        auto is_leap_year = [](int year) -> bool {
            return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        };

        std::vector<int> days_in_month = is_leap_year(year) ? days_in_month_leap : days_in_month_non_leap;

        // Calculate the day of year
        int day_of_year = 0;
        for (int i = 0; i < month - 1; ++i) {
            day_of_year += days_in_month[i];
        }
        day_of_year += day;

        return day_of_year;
    }
};

int main() {
    Solution solution;
    std::string date1 = "2019-01-09";
    std::cout << solution.dayOfYear(date1) << std::endl; // Output: 9
    
    std::string date2 = "2019-02-10";
    std::cout << solution.dayOfYear(date2) << std::endl; // Output: 41
    
    std::string date3 = "2003-03-01";
    std::cout << solution.dayOfYear(date3) << std::endl; // Output: 60
    
    std::string date4 = "2004-03-01";
    std::cout << solution.dayOfYear(date4) << std::endl; // Output: 61
    
    return 0;
}

Time Complexity:

This ensures the solution is efficient and runs in constant time regardless of the date provided.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI