algoadvance

Given a string date representing a date in the form “YYYY-MM-DD”, return the day number of the year.

Clarifying Questions

Before we proceed, here are some clarifying questions and assumptions:

  1. Can we assume the input date is always valid and formatted as “YYYY-MM-DD”?
    • Yes.
  2. Is the year always in the Gregorian calendar, and should we account for leap years?
    • Yes, and we should account for leap years.
  3. Is performance a key concern for this problem?
    • The problem size indicates that performance constraints are minimal, so we can aim for an efficient solution but don’t need to optimize for extremely large datasets.

Strategy

  1. Date Parsing:
    • Parse the input string to extract the year, month, and day.
  2. Days Calculation:
    • Calculate the number of days that have passed in the current year up to the given date.
    • Use a list to store the cumulative days at the start of each month. This allows us to easily sum days for the given month and day.
    • Account for leap years:
      • A year is a leap year if it is divisible by 4 but not divisible by 100, unless it is also divisible by 400.

Code

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

Time Complexity

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.

Try our interview co-pilot at AlgoAdvance.com