algoadvance

Leetcode 1185. Day of the Week

Problem Statement

Given a date, return the day of the week for that date. The input is given as three integers representing the day, month, and year respectively.

The return value should be a string. Each day of the week should be represented as one of the following strings: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday".

Clarifying Questions

  1. Question: Are the input dates within a certain range?
    • Answer: Yes, the year is between 1971 and 2100 inclusive.
  2. Question: Should we consider leap years?
    • Answer: Yes, leap years should be considered as per the Gregorian calendar rules.
  3. Question: Can dates be invalid?
    • Answer: No, you can assume the input date is valid.

Strategy

  1. To solve this problem, we’ll map the date to the corresponding day of the week.
  2. The given range allows us to use standard libraries for date handling.
  3. In Java, we can utilize the java.time package which provides a simple API to handle date and time.
  4. Specifically, the LocalDate class has a method getDayOfWeek to get the day of the week for a given date.
  5. We can then convert the DayOfWeek enum to a string.

Code

import java.time.LocalDate;
import java.time.DayOfWeek;

public class Solution {
    public String dayOfTheWeek(int day, int month, int year) {
        // Create a LocalDate instance using the given year, month, and day
        LocalDate date = LocalDate.of(year, month, day);
        
        // Get the DayOfWeek for the date
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        
        // Convert to string representation
        return dayOfWeek.toString().substring(0, 1).toUpperCase() +
               dayOfWeek.toString().substring(1).toLowerCase();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // Test case
        System.out.println(solution.dayOfTheWeek(31, 8, 2019)); // Expected: "Saturday"
        System.out.println(solution.dayOfTheWeek(18, 7, 1999)); // Expected: "Sunday"
        System.out.println(solution.dayOfTheWeek(15, 8, 1993)); // Expected: "Sunday"
    }
}

Time Complexity

The time complexity of this solution is O(1) since creating the date and fetching the day of the week are constant-time operations. The java.time library is optimized for handling such operations efficiently.

Space Complexity

The space complexity is O(1) as well since we are only using a fixed amount of additional space regardless of the input size.

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