Problem
Given a date
string in the form Day Month Year
, where:
Day
is in the set{"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}
.Month
is in the set{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
.Year
is in the range[1900, 2100]
.
Convert the date string to the format YYYY-MM-DD
, where:
YYYY
denotes the 4 digit year.MM
denotes the 2 digit month.DD
denotes the 2 digit day.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
- The given dates are guaranteed to be valid, so no error handling is necessary.
Solution
Method 1 – String Parsing and Mapping
Intuition
We can split the date string into its parts, map the month abbreviation to its number, and format the day and month with leading zeros as needed.
Approach
- Split the input string into day, month, and year.
- Remove the suffix from the day and pad with zero if needed.
- Map the month abbreviation to its two-digit number.
- Concatenate year, month, and day in the required format.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
, since the input is always a single date string of bounded length. - 🧺 Space complexity:
O(1)
, as only a few variables and a fixed mapping are used.