Leetcode #1118: Number of Days in a Month
In this guide, we solve Leetcode #1118 Number of Days in a Month in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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 <= 2100 1 <= month <= 12
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: year = 1992, month = 7
Output: 31
Python Solution
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]
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.