Given a string date
representing a Gregorian calendar date formatted as YYYY-MM-DD
, return the day number of the year.
Example 1:
Input: date = "2019-01-09" Output: 9 Explanation: Given date is the 9th day of the year in 2019.
Example 2:
Input: date = "2019-02-10" Output: 41
Constraints:
date.length == 10
date[4] == date[7] == '-'
, and all other date[i]
's are digitsdate
represents a calendar date between Jan 1st, 1900 and Dec 31st, 2019.This problem involves calculating the day of the year given a date in YYYY-MM-DD format. The solution leverages the Gregorian calendar rules for leap years and the number of days in each month.
Approach:
Parse the Date: Extract the year, month, and day from the input string.
Determine Leap Year: Check if the year is a leap year using the Gregorian calendar rules:
Calculate Days: Determine the number of days in each month. February requires special handling based on whether it's a leap year.
Cumulative Sum: Calculate the day of the year by summing the days of the preceding months and adding the current day.
Time Complexity: O(1) - The operations performed are constant time regardless of the input date.
Space Complexity: O(1) - Constant extra space is used to store variables and possibly a small array for the days in each month.
Code Implementation (Python):
class Solution:
def dayOfYear(self, date: str) -> int:
y, m, d = map(int, date.split('-')) # Efficiently parse the date string
# Determine leap year
is_leap = (y % 400 == 0) or (y % 4 == 0 and y % 100 != 0)
# Days in each month (handle leap year for February)
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap:
days_in_month[2] = 29
# Calculate day of the year
day_of_year = d
for i in range(1, m):
day_of_year += days_in_month[i]
return day_of_year
Code Implementation (Java):
class Solution {
public int dayOfYear(String date) {
String[] parts = date.split("-");
int year = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int day = Integer.parseInt(parts[2]);
boolean isLeap = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeap) {
daysInMonth[2] = 29;
}
int dayOfYear = day;
for (int i = 1; i < month; i++) {
dayOfYear += daysInMonth[i];
}
return dayOfYear;
}
}
Other Languages: The approach remains the same across different languages; only the syntax and standard library functions for string manipulation and integer parsing might change. The provided solution includes implementations in C++, Go, TypeScript, and JavaScript, demonstrating this consistency. The core logic of leap year determination and cumulative day calculation remains unchanged.