Number of Days in a Month — LeetCode 1118 Python Solution
EasyLeetCode PremiumMath
- Problem
- #1118
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a year year and a month month, return the number of days of that month.
Example
- Input
- year = 1992, month = 7
- Output
- 31
Python solution
Python
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
| Measure | Complexity |
|---|---|
| Time | O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1118. Number of Days in a Month is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1118. Number of Days in a Month?
- LeetCode 1118. Number of Days in a Month is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1118. Number of Days in a Month?
- The Python solution on this page runs in O(1).
- What is the space complexity of LeetCode 1118. Number of Days in a Month?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1118. Number of Days in a Month cover?
- LeetCode 1118. Number of Days in a Month is tagged Math on LeetCode.
- Is LeetCode 1118. Number of Days in a Month a premium problem?
- Yes. LeetCode 1118. Number of Days in a Month is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.