Number of Days in a Month Problem
#1118
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1118.
Given a year year and a month month, return the number of days of that month.
Example 1:
Input: year = 1992, month = 7
Output: 31
Example 2:
Input: year = 2000, month = 2
Output: 29
Example 3:
Input: year = 1900, month = 2
Output: 28
Constraints:
1583 <= year <= 21001 <= month <= 12
Solution
Approach: Leap Year Check and a Table
Every month has a fixed length except February, which has 29 days in a leap year and 28 otherwise. In the Gregorian calendar a year is a leap year when it is divisible by 4 but not by 100, or when it is divisible by 400. So 2000 is a leap year, while 1900 and 2100 are not, even though both are divisible by 4.
Decide that first, then look the answer up in a table of month lengths indexed from 1 to 12, with February filled in from the check.
Complexity: O(1) time and space.
class Solution:
def numberOfDays(self, year: int, month: int) -> int:
leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
days = [0, 31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return days[month]