Similar Problems
Similar Problems not available
Day Of The Year - Leetcode Solution
Companies:
LeetCode: Day Of The Year Leetcode Solution
Difficulty: Easy
Problem Statement:
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.
Example:
Input: date = "2022-07-12" Output: 193 Explanation: July 12th is the 193rd day of the year.
Solution:
The solution to this problem involves a simple calculation based on the given date. We need to calculate the total number of days from January 1st to the given date. To do this, we will first split the input string date using the '-' delimiter.
After splitting the date, we will convert the year, month, and day values to integers and subtract 1 from the month value since the first month starts from 0. We will create an array of integers to store the number of days in each month, taking care of leap years.
Then, we will iterate through the month values and add the number of days in each month to the total days variable. Finally, we will add the day value to the total days and return it.
The following is the Python implementation of the solution:
def dayOfYear(date: str) -> int:
year, month, day = map(int, date.split('-'))
days = [31, 28 if year % 4 != 0 or (year % 100 == 0 and year % 400 != 0) else 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
total_days = sum(days[i] for i in range(month - 1))
return (total_days + day)
Time Complexity: O(1) as the number of days in a year is fixed.
Space Complexity: O(1) as we only use a fixed-size array to store the number of days in each month.
Overall, the solution is very simple and efficient and can easily solve the Day Of The Year problem on leetcode.
Day Of The Year Solution Code
1