Leetcode 1185. Day of the Week
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".
java.time package which provides a simple API to handle date and time.LocalDate class has a method getDayOfWeek to get the day of the week for a given date.DayOfWeek enum to a string.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"
}
}
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.
The space complexity is O(1) as well since we are only using a fixed amount of additional space regardless of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?