Day of the Year - Complete Solution Guide
Day of the Year is LeetCode problem 1154, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 digits date represents a calendar date between Jan 1 st , 1900 and Dec 31 st , 2019.
Detailed Explanation
This problem challenges us to calculate the sequential day number within a given year, based on a standard Gregorian calendar date. The input `date` comes as a string in `YYYY-MM-DD` format, like "2019-01-09". Our task is to return an integer representing which day of the year that date falls on. For example, "2019-01-09" should yield 9, as it's the 9th day. "2019-02-10" would require summing January's 31 days and then adding 10 for February, resulting in 41.
Solution Approach
The provided solution adopts a highly pragmatic, direct approach: simulate the counting of days. First, it efficiently parses the input `date` string by splitting it at the hyphens and converting the resulting year, month, and day components into integers. This sets up our core variables. Next, it initializes an array, `days_in_month`, storing the standard number of days for each month in a non-leap year (e.g., February starts with 28 days). This array acts as a lookup table. The critical logic follows: a conditional check determines if the extracted `year` is a leap year using the standard rules: divisible by 4 but not by 100, OR divisible by 400. If it's a leap year, the solution immediately updates the `days_in_month` array, setting February's entry (index 1) to 29. With the correct month lengths established, the algorithm then iterates from January (index 0) up to the *month prior* to our target month. In each iteration, it accumulates the total days from these full preceding months. Finally, it adds the `day` component from the input date itself. This sum represents the total day number of the year. This method works beautifully because it mimics exactly how one would manually count days, making it intuitively understandable and robust for the given constraints.
Step-by-Step Algorithm
- Step 1: Parse the input date string into year, month, and day integers.
- Step 2: Initialize an array `daysInMonth` to store the number of days in each month (starting from January).
- Step 3: Check if the year is a leap year using the leap year rule (divisible by 4, but not by 100 unless also divisible by 400). If it's a leap year, set the number of days in February to 29.
- Step 4: Iterate through the `daysInMonth` array from January to the month before the input month, summing the number of days in each month. This gives the total number of days passed before the input month.
- Step 5: Add the input day to the accumulated sum to get the final day of the year.
- Step 6: Return the final day of the year.
Key Insights
- **Precise Leap Year Calculation**: The cornerstone of this problem is correctly implementing the Gregorian calendar's leap year rules: `(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)`. Failing to capture this nuance, especially the centurial exception, will lead to incorrect results for February's length in specific years.
- **Month Length Pre-computation/Lookup**: Storing the number of days for each month in an array (`days_in_month`) provides a clean and efficient lookup mechanism. Instead of using `if/else if` cascades for each month, a simple array access `days_in_month[i]` keeps the code concise and readable, especially after dynamically adjusting February's value for leap years.
- **Iterative Summation for Preceding Months**: The solution's strategy of summing days from full months *before* the target month, then adding the target day, is a straightforward and explicit way to count. It avoids complex date arithmetic libraries and directly translates the problem's request into a simple loop, ensuring correctness by adding exact integer values.
Complexity Analysis
Time Complexity: O(1)
Space Complexity: O(1)
Topics
This problem involves: Math, String.
Companies
Asked at: ZScaler.