Given a string date
representing a date in the form “YYYY-MM-DD”, return the day number of the year.
Before we proceed, here are some clarifying questions and assumptions:
def dayOfYear(date: str) -> int:
# Split the date string into year, month, and day
year, month, day = map(int, date.split('-'))
# Number of days up to the start of each month in a non-leap year
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# Check for leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days_in_month[1] = 29 # Adjust February for leap year
# Sum days in previous months and add current month day
day_of_year = sum(days_in_month[:month-1]) + day
return day_of_year
# Example usage:
print(dayOfYear("2019-01-09")) # Output should be 9
print(dayOfYear("2019-02-10")) # Output should be 41
The time complexity of this solution is (O(1)) because the operations (splitting the date string, calculating the sum of days) are fixed and do not depend on the size of any input data. The space complexity is also (O(1)) since we are using a fixed-size list and a few integer variables.
This approach ensures that the code remains concise and efficient, handling leap years appropriately.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?