We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Day of the Year

Number: 1260

Difficulty: Easy

Paid? No

Companies: Google, ZScaler


Problem Description

Given a string date representing a Gregorian calendar date in the format YYYY-MM-DD, return the day number of the year.


Key Insights

  • Parse the input string to extract year, month, and day.
  • Determine if the year is a leap year to adjust the number of days in February.
  • Use an array (or list) containing the number of days per month for a non-leap year, and update February if necessary.
  • Sum the days of the months preceding the given month and add the day to get the final day number.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

We first split the date string into its year, month, and day components. Based on the year, we check if it is a leap year by using the condition: if the year is divisible by 400 or divisible by 4 but not by 100, then it is a leap year. A list (or array) representing the number of days in each month for a non-leap year is defined, and if the year is a leap year, February's day count is updated to 29. Finally, we compute the day number by summing the days in all preceding months and adding the day of the current month.


Code Solutions

# Function to calculate the day of the year
def dayOfYear(date):
    # Split the date string into year, month, day and convert to integers
    year, month, day = map(int, date.split('-'))
    
    # Define days in each month for a non-leap year
    days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    # Check for leap year: if divisible by 400 or divisible by 4 but not by 100
    if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
        days_in_month[1] = 29  # Update February
    
    # Calculate the day number by summing the days before the current month and adding the day
    day_number = sum(days_in_month[:month - 1]) + day
    return day_number

# Example usage:
print(dayOfYear("2019-02-10"))  # Expected output: 41
← Back to All Questions