Reformat Date Problem
#1507
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1507.
Given a date string in the form Day Month Year, where:
Dayis in the set{"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.Monthis in the set{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.Yearis in the range[1900, 2100].
Convert the date string to the format YYYY-MM-DD, where:
YYYYdenotes the 4 digit year.MMdenotes the 2 digit month.DDdenotes the 2 digit day.
Example 1:
Input: date = "20th Oct 2052"
Output: "2052-10-20"
Example 2:
Input: date = "6th Jun 1933"
Output: "1933-06-06"
Example 3:
Input: date = "26th May 1960"
Output: "1960-05-26"
Constraints:
- The given dates are guaranteed to be valid, so no error handling is necessary.
Solution
Approach: Split and Look Up
The input always has three parts separated by single spaces, so split it into day, month and year:
- Day: the number followed by a two-letter suffix (
st,nd,rdorth). Drop the last two characters and parse the rest. - Month: look the abbreviation up in the list
Jan, Feb, ..., Dec. Its index plus one is the month number. - Year: already four digits, so use it as it is.
Then build YYYY-MM-DD, padding the month and the day with a leading zero when they are a single digit (6th Jun 1933 becomes 1933-06-06).
Complexity: O(1) time and space, since the input has a fixed, short format.
class Solution:
def reformatDate(self, date: str) -> str:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
day, month, year = date.split()
day = int(day[:-2]) # drop the "st" / "nd" / "rd" / "th" suffix
return "%s-%02d-%02d" % (year, months.index(month) + 1, day)