algoadvance

Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month, and year respectively. The output should be the name of the day of the week in English (e.g., “Sunday”, “Monday”).

Example:

Clarifying Questions

  1. Are the given dates within a valid range?
    • Yes, the input date is guaranteed to be a valid date.
  2. Is the input always provided in day, month, and year order?
    • Yes, the input is always in the order of day, month, and year.
  3. What format should the output be in?
    • The output should be a string representing the day of the week (e.g., “Monday”).

Strategy

To determine the day of the week for a given date, we can make use of Python’s datetime module. This module provides convenient methods to handle dates and can directly give us the day of the week.

Steps:

  1. Import the datetime module.
  2. Create a date object using datetime.date(year, month, day).
  3. Use the weekday() method of the date object to get the day of the week as an integer (0 = Monday, …, 6 = Sunday).
  4. Map this integer to the corresponding day name in English.

Code

import datetime

def dayOfTheWeek(day: int, month: int, year: int) -> str:
    # Create date object
    date = datetime.date(year, month, day)
    
    # Map of week day index to the day name
    day_map = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    
    # Get the day of the week as an integer (0-6, Monday-Sunday)
    day_index = date.weekday()
    
    # Return the corresponding day name
    return day_map[day_index]

# Example Usage
print(dayOfTheWeek(31, 8, 2019)) # Output: "Saturday"

Time Complexity

This approach takes advantage of Python’s built-in datetime module, which is optimized and reliable for handling dates and calculating the day of the week.

Try our interview co-pilot at AlgoAdvance.com