AlgoMaster Logo

Days in a Given Month and Year

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Month lengths follow a fixed pattern with one exception. Seven months have 31 days, four have 30 days, and February's length depends on the year. That single dependency is the only real work here.

For every month except February, the answer is fixed at 30 or 31. For February, the year decides between 28 and 29 through the leap year rule: divisible by 4, but century years count only when also divisible by 400.

Key Constraints:

  • Month is between 1 and 12 → You can rely on a valid month, so there is no need to guard against out-of-range values.
  • February is the only variable month → Handle it first as a special case, then the remaining months reduce to a choice between 30 and 31.
  • Leap year affects only February → Compute the leap year condition solely inside the February branch, since it changes nothing for the other months.

Approach 1: Special-Case February

Intuition

Handle February first. If the month is February, return 29 in a leap year and 28 otherwise. The rest of the calendar then has only two possibilities.

The four months with 30 days are April, June, September, and November, which are months 4, 6, 9, and 11. If the month is one of those, the answer is 30. Every other month has 31 days. This computes the leap year condition only when needed, and the remaining logic is a single membership check.

Algorithm

  1. If month is February (2), check whether year is a leap year. Return 29 if it is, otherwise 28.
  2. If month is April, June, September, or November (4, 6, 9, or 11), return 30.
  3. Otherwise, return 31.

Example Walkthrough

Input:

2
month
2020
year

The month is 2, so this is February and the year decides the length. Check the leap year rule for 2020: it is divisible by 4, and it is not a century year, so it is a leap year. February therefore has 29 days.

29
output

Code