Given a date string in the form Day Month Year
, where:
Day
is a numerical day followed by a suffix (st
, nd
, rd
, th
).Month
is the full name of the month with the first letter in uppercase.Year
is a four-digit number.Your task is to reformat the date to the format YYYY-MM-DD
, where:
YYYY
is the four-digit year.MM
is the two-digit month.DD
is the two-digit day.Input: "20th Oct 2052"
Output: "2052-10-20"
Input: "6th Jun 1933"
Output: "1933-06-06"
Input: "26th May 1960"
Output: "1960-05-26"
Day
, Month
, and Year
from the input string.Day
part.Day
and Month
are two digits (prefix with 0
if necessary).Year
, Month
, and Day
into the desired format.def reformat_date(date: str) -> str:
# Split the input string into parts
parts = date.split()
# Extract day (and remove suffix), month, and year
day = parts[0][:-2]
month = parts[1]
year = parts[2]
# Map months to their corresponding two-digit numbers
month_map = {
"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04",
"May": "05", "Jun": "06", "Jul": "07", "Aug": "08",
"Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"
}
# Convert day to two digits
if len(day) == 1:
day = '0' + day
# Format result
formatted_date = f"{year}-{month_map[month]}-{day}"
return formatted_date
# Examples
print(reformat_date("20th Oct 2052")) # Output: "2052-10-20"
print(reformat_date("6th Jun 1933")) # Output: "1933-06-06"
print(reformat_date("26th May 1960")) # Output: "1960-05-26"
The time complexity for this solution is O(1) because:
This ensures that our solution processes the input in constant time, independent of the length of the string or the specific content of the date.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?