MEDIC - Editorial

Problem Link - When to take medicine Practice Problem in 1400 to 1600 difficulty problems

Problem Statement:

In this problem, you are given a starting date, and you’re supposed to take medicine every alternate day. The challenge is to count how many days you take the medicine on the “right” day, which is defined as:

  • You take the medicine on a day if the day of the month is either odd or even, depending on whether the starting day (given in the input) is odd or even.

You need to calculate how many times you take the medicine correctly before you mess up (i.e., when the day of the month is wrong, based on the alternating pattern).

Approach:

  • Leap Year Function: A helper function to check if a given year is a leap year.
  • Day Calculation: A function to check how many days are in a given month, considering whether the year is a leap year or not. A year is a leap year if it is divisible by 4, but not divisible by 100, unless also divisible by 400.
  • Main Logic:
    • Start with the given date.
    • Alternate the day by adding 2 days.
    • If the current day matches the alternating pattern (odd or even), we increment the count. Check if the day of the month is valid (either odd or even).
    • Stop when the alternation pattern is violated.

Complexity:

  • Time Complexity: The complexity per test case is proportional to the number of days in a year (since we are iterating day by day). For a year, this would be at most 365 days (or 366 in a leap year).
  • Space Complexity: The space complexity is O(1) as we are only storing a few variables and not using any large data structures.