problemeasyalgorithmsleetcode-1118leetcode 1118leetcode1118

Number of Days in a Month

EasyUpdated: Aug 2, 2025
Practice on:

Problem

Given a year year and a month month, return the number of days of that month.

Examples

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

Solution

Method 1 – Simple Lookup and Leap Year Check

Intuition

Months have a fixed number of days except February, which depends on whether the year is a leap year. Leap years are divisible by 4, but not by 100 unless also by 400.

Approach

  1. Use an array to store days for each month.
  2. For February, check if the year is a leap year and return 29 or 28.
  3. For other months, return the value from the array.

Code

C++
class Solution {
public:
    int numberOfDays(int year, int month) {
        if (month == 2) {
            if ((year%4==0 && year%100!=0) || year%400==0) return 29;
            return 28;
        }
        int days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
        return days[month-1];
    }
};
Go
func numberOfDays(year, month int) int {
    if month == 2 {
        if (year%4==0 && year%100!=0) || year%400==0 { return 29 }
        return 28
    }
    days := []int{31,28,31,30,31,30,31,31,30,31,30,31}
    return days[month-1]
}
Java
class Solution {
    public int numberOfDays(int year, int month) {
        if (month == 2) {
            if ((year%4==0 && year%100!=0) || year%400==0) return 29;
            return 28;
        }
        int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
        return days[month-1];
    }
}
Kotlin
class Solution {
    fun numberOfDays(year: Int, month: Int): Int {
        if (month == 2) {
            if ((year%4==0 && year%100!=0) || year%400==0) return 29
            return 28
        }
        val days = arrayOf(31,28,31,30,31,30,31,31,30,31,30,31)
        return days[month-1]
    }
}
Python
class Solution:
    def numberOfDays(self, year: int, month: int) -> int:
        if month == 2:
            if (year%4==0 and year%100!=0) or year%400==0:
                return 29
            return 28
        days = [31,28,31,30,31,30,31,31,30,31,30,31]
        return days[month-1]
Rust
impl Solution {
    pub fn number_of_days(year: i32, month: i32) -> i32 {
        if month == 2 {
            if (year%4==0 && year%100!=0) || year%400==0 { return 29; }
            return 28;
        }
        let days = [31,28,31,30,31,30,31,31,30,31,30,31];
        days[(month-1) as usize]
    }
}
TypeScript
function numberOfDays(year: number, month: number): number {
    if (month === 2) {
        if ((year%4===0 && year%100!==0) || year%400===0) return 29;
        return 28;
    }
    const days = [31,28,31,30,31,30,31,31,30,31,30,31];
    return days[month-1];
}

Complexity

  • ⏰ Time complexity: O(1)
  • 🧺 Space complexity: O(1)

Comments