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

Number of Days in a Month

Number: 1088

Difficulty: Easy

Paid? Yes

Companies: Amazon


Problem Description

Given a year and a month, determine the number of days in that month. Note that February can have 28 or 29 days, depending on whether the given year is a leap year.


Key Insights

  • Use the standard list of months with 31 and 30 days.
  • Special handling is required for February:
    • A leap year is divisible by 4, but not by 100 unless it is also divisible by 400.
  • The solution uses constant time and space complexities, as it only involves conditional checks.

Space and Time Complexity

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


Solution

To solve the problem, we first check if the month is February. If it is, we determine if the year is a leap year using the given conditions. If it is a leap year, February has 29 days; otherwise, it has 28 days. For other months, we can use a mapping or conditions to output 31 days for months: January, March, May, July, August, October, and December; and 30 days for the remaining months: April, June, September, and November. This approach uses simple conditional checks without the need for additional data structures.


Code Solutions

# Function to determine the number of days in a given month of a given year.
def number_of_days(year: int, month: int) -> int:
    # Check if the month is February
    if month == 2:
        # Check for leap year: divisible by 4 and (not divisible by 100 or divisible by 400)
        if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)):
            return 29  # Leap year February has 29 days
        else:
            return 28  # Non-leap year February has 28 days
    # Months with 31 days: January, March, May, July, August, October, December
    if month in {1, 3, 5, 7, 8, 10, 12}:
        return 31
    # Remaining months have 30 days: April, June, September, November
    return 30

# Example test cases
print(number_of_days(1992, 7))  # Expected output: 31
print(number_of_days(2000, 2))  # Expected output: 29
print(number_of_days(1900, 2))  # Expected output: 28
← Back to All Questions