Magicsheet logo

Number of Days in a Month

Easy
25%
Updated 8/1/2025

Asked by 1 Company

Topics

Number of Days in a Month

What is this problem about?

The Number of Days in a Month problem asks you to return the number of days in a given month of a given year. The answer depends on the month (28-31 days) and whether the year is a leap year for February. This is an easy math implementation problem.

Why is this asked in interviews?

Amazon asks this straightforward problem to test implementation discipline — correctly handling all 12 months and the leap year edge case for February. Despite its simplicity, it reveals candidates who can write clean, complete code without bugs on edge cases.

Algorithmic pattern used

Lookup table + leap year check. Maintain a days[13] array for the standard days per month. For February (month=2), check if the year is a leap year: (year%4==0 and year%100!=0) or year%400==0. Return 29 for leap year February, otherwise 28.

Example explanation

Month=2, Year=2020: 2020%4=0, 2020%100=20≠0 → leap year → 29 days. Month=2, Year=1900: 1900%4=0, 1900%100=0, 1900%400=300≠0 → NOT a leap year → 28 days. Month=7, Year=any: July always has 31 days.

Common mistakes candidates make

  • Using year%4==0 as the sole leap year condition (misses the century rule).
  • Hardcoding all months instead of using a lookup array.
  • Off-by-one: 0-indexed vs 1-indexed month array.
  • Not handling the century exception (1900 is not a leap year; 2000 is).

Interview preparation tip

The leap year formula — divisible by 4, not 100, or divisible by 400 — is a memorization requirement. Write it once correctly: (y%4==0 and y%100!=0) or y%400==0. For the days lookup, keep a 1-indexed array [0,31,28,31,30,31,30,31,31,30,31,30,31]. This problem often appears as a sub-function in larger date calculation problems. Getting it right quickly and cleanly is the expected behavior for easy problems.

Similar Questions