Validate Date from Three Numbers
Level: L3 Topics: Logic, Edge Cases, Calendar Arithmetic
Problem Statement
You are given three unordered integers. Determine whether they can be interpreted as a valid calendar date in the format (year, month, day).
The three numbers have no predefined ordering — any of the three could be the year, month, or day. Your task is to check if there exists at least one valid assignment of the three numbers to (year, month, day) that forms a legitimate date.
Background & Constraints
- A valid month is in the range 1 to 12.
- A valid day depends on the month (and year, for February in leap years).
- Year can be any positive integer (assume the Gregorian calendar).
- Leap year rules: divisible by 4, except centuries unless also divisible by 400.
- Days per month: Jan=31, Feb=28/29, Mar=31, Apr=30, May=31, Jun=30, Jul=31, Aug=31, Sep=30, Oct=31, Nov=30, Dec=31.
- The same number can appear more than once among the three inputs (e.g.,
(1, 1, 2012)).
Examples
Input: (2000, 14, 3)
- Try year=2000, month=3, day=14: March 14, 2000. Valid.
- Output: Valid
Input: (2000, 3, 2000)
- Two values are 2000. If year=2000, the remaining values are 3 and 2000. Month=3, day=2000? Invalid (day too large). Month=2000, day=3? Invalid (month > 12).
- If year=3, month=2000? Invalid.
- Output: Invalid
Input: (1, 1, 2012)
- Year=2012, month=1, day=1: January 1, 2012. Valid.
- Output: Valid
Note: Although (1, 1, 2012) might look ambiguous (is it year=1, month=1, day=2012?), at least one valid assignment exists, so it is valid.
Hints & Common Pitfalls
- There are only 6 permutations of three numbers (or 3 if some are equal). Try all permutations as
(year, month, day)and check each. - Pin down the month first: it must be 1-12, which is the most restrictive constraint. Then the year is typically the largest remaining number (but not always — consider year=1).
- Handle leap years carefully: February 29 is valid only in leap years.
- Edge case: all three numbers are the same, e.g.,
(5, 5, 5)— year=5, month=5, day=5 (May 5, year 5) is valid. - Do not assume the year must be a 4-digit number.
Follow-Up Questions
- Ambiguity check: Instead of just checking validity, return whether the date is unambiguous. A date is unambiguous if exactly one assignment of (year, month, day) produces a valid date. For example,
(2000, 14, 3)is unambiguous because only year=2000, month=3, day=14 works (month=14 is always invalid). But(2000, 4, 3)is ambiguous because both year=2000, month=4, day=3 (April 3) and year=2000, month=3, day=4 (March 4) are valid. How would you report this?