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

Number: 1283

Difficulty: Easy

Paid? No

Companies: Oracle, TikTok, Goldman Sachs, Veritas, Expedia, Twilio


Problem Description

Given a date string in the format "Day Month Year", where Day is a number with a suffix (like "20th" or "6th"), Month is a three-letter abbreviation (e.g., "Oct", "Jun"), and Year is a four-digit number, convert the date string into the format "YYYY-MM-DD". For example, given "20th Oct 2052", return "2052-10-20".


Key Insights

  • Extract the day by removing the suffix ("st", "nd", "rd", "th") and converting the remaining part to an integer.
  • Use a mapping from month abbreviations to their corresponding two-digit numerical format.
  • Pad day (and month if needed) with a leading zero to ensure they are two digits.
  • Concatenate the formatted year, month, and day with hyphens.

Space and Time Complexity

Time Complexity: O(1) - Processing and formatting the fixed-length input is constant. Space Complexity: O(1) - Only a fixed amount of extra space is used for variables.


Solution

The solution involves parsing the given date string by splitting it into three parts: day, month, and year. Remove the suffix from the day to get the numerical day and convert it into a two-digit format. Use a predefined dictionary (or hash map) that maps month abbreviations to their corresponding two-digit string. Finally, assemble the year, month, and day into a string formatted as "YYYY-MM-DD". This approach uses simple string operations and dictionary lookups, ensuring constant time and space complexity.


Code Solutions

# Define a dictionary mapping month abbreviations to 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"
}

def reformatDate(date):
    # Split the input string into day, month, and year
    parts = date.split()
    day_str, month_str, year_str = parts[0], parts[1], parts[2]
    
    # Remove the suffix from the day (like "st", "nd", "rd", or "th")
    day_num = day_str[:-2]
    
    # Format day as two-digits, pad with a leading zero if necessary
    day_formatted = day_num.zfill(2)
    
    # Get the two-digit month from the dictionary mapping
    month_formatted = month_map[month_str]
    
    # Return the formatted date string "YYYY-MM-DD"
    return year_str + "-" + month_formatted + "-" + day_formatted

# Example usage:
print(reformatDate("20th Oct 2052"))  # Output: "2052-10-20"
← Back to All Questions