We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reformat Date

Difficulty: Easy


Problem Description

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.

Key Insights

  • The input date string needs to be parsed to extract the day, month, and year.
  • The day string may contain ordinal suffixes ("st", "nd", "rd", "th") that need to be removed to convert it to a numerical format.
  • The month string must be mapped to its corresponding numerical representation.
  • The output format requires leading zeros for the day and month if they are single digits.

Space and Time Complexity

Time Complexity: O(1) - The operations performed to format the date do not depend on the size of the input data. Space Complexity: O(1) - The space used is constant, as it only stores a fixed number of variables.


Solution

To solve the problem, we can use the following steps:

  1. Split the input date string into its components (day, month, year).
  2. Remove the ordinal suffix from the day and convert it to an integer.
  3. Map the month from its string representation to a numeric value.
  4. Format the year, month, and day into the output string in the specified format.

Code Solutions

def reformatDate(date: str) -> str:
    # Month mapping from string to numeric representation
    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"
    }
    
    # Split the date into day, month, year
    day, month, year = date.split()
    
    # Remove the ordinal suffix from the day and convert to two digits
    day = day[:-2].zfill(2)
    
    # Convert month to its numeric representation
    month = month_map[month]
    
    # Return the reformatted date
    return f"{year}-{month}-{day}"
← Back to All Questions