Number of Days in a Month - Problem

Welcome to your role as a calendar system developer! You need to build a function that accurately determines the number of days in any given month of any year.

Given two integers year and month, return the exact number of days in that month. This might seem simple, but there's a catch - you need to handle leap years correctly!

Remember: February has 28 days in regular years, but 29 days in leap years. A leap year occurs every 4 years, except for years divisible by 100 (unless they're also divisible by 400).

Examples: January 2023 has 31 days, February 2020 (leap year) has 29 days, February 2021 (not leap year) has 28 days.

Input & Output

example_1.py โ€” Regular month
$ Input: year = 2023, month = 1
โ€บ Output: 31
๐Ÿ’ก Note: January always has 31 days regardless of the year
example_2.py โ€” Leap year February
$ Input: year = 2020, month = 2
โ€บ Output: 29
๐Ÿ’ก Note: 2020 is a leap year (divisible by 4), so February has 29 days
example_3.py โ€” Non-leap year February
$ Input: year = 2021, month = 2
โ€บ Output: 28
๐Ÿ’ก Note: 2021 is not a leap year (not divisible by 4), so February has 28 days

Constraints

  • 1 โ‰ค month โ‰ค 12
  • 1583 โ‰ค year โ‰ค 104
  • Follow Gregorian calendar rules

Visualization

Tap to expand
Calendar Logic VisualizationINPUTYear, MonthIs February?month == 2Special CaseYESNOLeap Year CheckIf (year % 4 == 0 ANDyear % 100 != 0) ORyear % 400 == 0:Return 29, else 28Direct Lookupdays[month-1]Array AccessRESULTDays Count๐ŸŽฏ Key Insight: Only February varies - all other months have fixed lengths!
Understanding the Visualization
1
Month Classification
Identify if the month is February (variable) or others (fixed)
2
Leap Year Detection
For February, apply the leap year formula
3
Direct Calculation
Return the appropriate number of days instantly
Key Takeaway
๐ŸŽฏ Key Insight: The optimal solution recognizes that only February has variable days - all other months are constants. This reduces the problem to a simple lookup with one special case handling.
Asked in
Google 15 Microsoft 12 Amazon 8 Apple 6
28.5K Views
Low 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