algoadvance

Leetcode 1154. Day of the Year

Problem Statement:

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. The day number is the number of days from January 1st to the given date.

Example 1:

Input: date = "2019-01-09"
Output: 9

Example 2:

Input: date = "2019-02-10"
Output: 41

Clarifying Questions:

  1. Is the input date always valid?
    • Yes, the problem guarantees that the input date is valid.
  2. Do we need to consider leap years?
    • Yes, we need to consider leap years as they impact the number of days in February.
  3. What is the range of years we need to handle?
    • Given the problem is about the Gregorian calendar, we should handle years from 1582 onwards.

Strategy:

  1. Extract Date Components:
    • Extract the year, month, and day from the input string.
  2. Determine if Leap Year:
    • Define a helper function to check if a given year is a leap year.
    • A year is a leap year if:
      • It is divisible by 4, and
      • It is not divisible by 100 unless also divisible by 400.
  3. Define Days per Month:
    • Define an array for the number of days in each month for both leap and non-leap years.
  4. Calculate Day of the Year:
    • Sum the days in the months preceding the given month.
    • Add the day of the current month to the above sum.

Code:

public class Solution {
    
    public int dayOfYear(String date) {
        String[] dateParts = date.split("-");
        int year = Integer.parseInt(dateParts[0]);
        int month = Integer.parseInt(dateParts[1]);
        int day = Integer.parseInt(dateParts[2]);

        int[] daysInMonthsNonLeap = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int[] daysInMonthsLeap = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        boolean isLeapYear = isLeapYear(year);
        int[] daysInMonths = isLeapYear ? daysInMonthsLeap : daysInMonthsNonLeap;

        int dayOfYear = 0;
        for (int i = 0; i < month - 1; i++) {
            dayOfYear += daysInMonths[i];
        }
        dayOfYear += day;

        return dayOfYear;
    }

    private boolean isLeapYear(int year) {
        if (year % 4 == 0) {
            if (year % 100 == 0) {
                return year % 400 == 0;
            }
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.dayOfYear("2019-01-09")); // Outputs 9
        System.out.println(sol.dayOfYear("2019-02-10")); // Outputs 41
        System.out.println(sol.dayOfYear("2000-03-01")); // Outputs 61
    }
}

Time Complexity:

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI