Number of Days in a Month - Problem

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

You need to handle leap years correctly. A leap year occurs:

  • Every 4 years, BUT
  • NOT every 100 years, BUT
  • Every 400 years

For example, 2000 and 2004 are leap years, but 1900 is not.

Remember that February has 28 days in regular years and 29 days in leap years.

Input & Output

Example 1 — Leap Year February
$ Input: year = 2020, month = 2
Output: 29
💡 Note: 2020 is a leap year (divisible by 4, not by 100), so February has 29 days
Example 2 — Regular Month
$ Input: year = 2019, month = 8
Output: 31
💡 Note: August always has 31 days regardless of leap year
Example 3 — Non-Leap February
$ Input: year = 1900, month = 2
Output: 28
💡 Note: 1900 is not a leap year (divisible by 100 but not by 400), so February has 28 days

Constraints

  • 1583 ≤ year ≤ 2100
  • 1 ≤ month ≤ 12

Visualization

Tap to expand
Number of Days in a Month INPUT February 2020 SMT WTFS 123 4567 8910 111213 141516 ...29 year 2020 month 2 2020 is a Leap Year! How many days? ALGORITHM STEPS 1 Create days array [31,28,31,30,31,30,31,31,30,31,30,31] 2 Check if leap year year % 4 == 0 AND (year % 100 != 0 OR year % 400 == 0) 3 If Feb and leap year month==2 AND isLeap --> return 29 4 Otherwise lookup return days[month - 1] For year=2020, month=2: isLeap=true --> return 29 FINAL RESULT February 2020 29 days Output: 29 Why 29? 2020 % 4 = 0 [OK] 2020 % 100 = 20 != 0 [OK] Leap year confirmed! OK - Verified Key Insight: Array Lookup Approach Pre-store days for each month in an array: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] For any month, simply return days[month-1]. Special case: If month=2 (February) AND it's a leap year, return 29 instead. Leap year: divisible by 4, but not by 100, unless also divisible by 400. TutorialsPoint - Number of Days in a Month | Array Lookup Approach
Asked in
Google 15 Microsoft 12 Amazon 8
26.8K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen