Given a string date
representing a Gregorian calendar date formatted as YYYY-MM-DD
, return the day number of the year.
For example:
date = "2019-01-09"
should return 9
because it's the 9th day of 2019.date = "2019-02-10"
should return 41
.Write a function that takes a date string as input and returns an integer representing the day of the year. Consider leap years when calculating the day number. How would you optimize your solution for speed and memory usage? What is the Big O time and space complexity of your solution?
The brute force solution would involve parsing the date string, determining if the year is a leap year, and then summing the days in each month up to the given month.
Code (Python):
def dayOfYear_brute_force(date):
year, month, day = map(int, date.split('-'))
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days_in_month[2] = 29
day_number = 0
for i in range(1, month):
day_number += days_in_month[i]
day_number += day
return day_number
Big O Analysis:
The optimal solution is similar to the brute force approach, but can be slightly improved by pre-calculating leap year status and reducing redundant operations.
Code (Python):
def dayOfYear(date):
year, month, day = map(int, date.split('-'))
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
days_before_month = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
day_number = days_before_month[month - 1] + day
if is_leap and month > 2:
day_number += 1
return day_number
Big O Analysis: