algoadvance

Given a date string in the form Day Month Year, where:

Your task is to reformat the date to the format YYYY-MM-DD, where:

Example

Input: "20th Oct 2052"
Output: "2052-10-20"

Input: "6th Jun 1933"
Output: "1933-06-06"

Input: "26th May 1960"
Output: "1960-05-26"

Clarifying Questions

  1. Should input strings always be valid and follow the specified format?
    • Yes, assume input strings are always correctly formatted.
  2. What is the range of years we could expect?
    • Any valid four-digit year (e.g., 1000 to 9999).

Strategy

  1. Extract Components: Extract Day, Month, and Year from the input string.
  2. Remove Suffix: Remove the suffix from the Day part.
  3. Month Mapping: Create a mapping from month names to their corresponding two-digit numbers.
  4. Format Components: Ensure that the Day and Month are two digits (prefix with 0 if necessary).
  5. Concatenate Result: Combine Year, Month, and Day into the desired format.

Code

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"

Time Complexity

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.

Try our interview co-pilot at AlgoAdvance.com