1. Simulation

class Solution:
    def numberOfDays(self, year: int, month: int) -> int:
        if month == 2:
            if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
                return 29
            return 28
        if month == 4 or month == 6 or month == 9 or month == 11:
            return 30
        return 31

Time & Space Complexity

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

2. Array

class Solution:
    def numberOfDays(self, year: int, month: int) -> int:
        days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        isLeap = year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
        if month == 2 and isLeap:
            return 29
        return days[month - 1]

Time & Space Complexity

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

3. Math

class Solution:
    def numberOfDays(self, year: int, month: int) -> int:
        res = 28 + (month + month // 8) % 2 + 2 % month + 2 * (1 // month)
        isLeap = year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
        if month == 2 and isLeap:
            res += 1
        return res

Time & Space Complexity

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