This problem asks to determine the number of days in a given month and year. The solution leverages the fact that the number of days in a month is fixed except for February, which has 28 days in a common year and 29 days in a leap year.
Approach:
The core idea is to first determine if the input year is a leap year. A leap year is divisible by 4, but not by 100, unless it's also divisible by 400. Once this is determined, we can use a lookup table (array) to get the number of days for the given month. This approach avoids complex conditional logic for each month and improves readability.
Time Complexity: O(1) - The time taken is constant regardless of the input year or month because the operations performed (leap year check and array lookup) are constant-time operations.
Space Complexity: O(1) - The space used is constant; we use a fixed-size array to store the number of days in each month. The size of the array does not depend on the input.
Code Implementation:
The code below demonstrates the solution in various programming languages. Each implementation follows the same basic logic:
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
days
where days[i]
represents the number of days in the ith month. The element for February (days[2]
) is conditionally set to 28 or 29 based on the leap year status.days
array corresponding to the input month
.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]
Java:
class Solution {
public int numberOfDays(int year, int month) {
boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
int[] days = new int[] {0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return days[month];
}
}
C++:
class Solution {
public:
int numberOfDays(int year, int month) {
bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
vector<int> days = {0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return days[month];
}
};
Go:
func numberOfDays(year int, month int) int {
leap := (year%4 == 0 && year%100 != 0) || (year%400 == 0)
days := []int{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if leap {
days[2] = 29
}
return days[month]
}
Typescript:
function numberOfDays(year: number, month: number): number {
const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const days = [0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return days[month];
}
All the code snippets above follow the same efficient algorithmic approach, demonstrating its versatility across different languages. The choice of language depends on your preference and the environment where you'll be using the code.