Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1507. Reformat Date - Leetcode Solution

Code Implementation

class Solution:
    def reformatDate(self, date: str) -> str:
        months = {
            "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04",
            "May": "05", "Jun": "06", "Jul": "07", "Aug": "08",
            "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12"
        }
        day, month, year = date.split()
        day = day[:-2].zfill(2)
        return f"{year}-{months[month]}-{day}"
      
class Solution {
public:
    string reformatDate(string date) {
        unordered_map<string, string> months = {
            {"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"},
            {"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"},
            {"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}
        };
        istringstream ss(date);
        string day, month, year;
        ss >> day >> month >> year;
        day = day.substr(0, day.size() - 2);
        if (day.size() == 1) day = "0" + day;
        return year + "-" + months[month] + "-" + day;
    }
};
      
class Solution {
    public String reformatDate(String date) {
        Map<String, String> months = new HashMap<>();
        months.put("Jan", "01"); months.put("Feb", "02"); months.put("Mar", "03");
        months.put("Apr", "04"); months.put("May", "05"); months.put("Jun", "06");
        months.put("Jul", "07"); months.put("Aug", "08"); months.put("Sep", "09");
        months.put("Oct", "10"); months.put("Nov", "11"); months.put("Dec", "12");
        String[] parts = date.split(" ");
        String day = parts[0].substring(0, parts[0].length() - 2);
        if(day.length() == 1) day = "0" + day;
        String month = months.get(parts[1]);
        String year = parts[2];
        return year + "-" + month + "-" + day;
    }
}
      
var reformatDate = function(date) {
    const months = {
        Jan: "01", Feb: "02", Mar: "03", Apr: "04",
        May: "05", Jun: "06", Jul: "07", Aug: "08",
        Sep: "09", Oct: "10", Nov: "11", Dec: "12"
    };
    const [day, month, year] = date.split(" ");
    const d = day.slice(0, -2).padStart(2, '0');
    return `${year}-${months[month]}-${d}`;
};
      

Problem Description

The task is to convert a date string from the format "Day Month Year" (e.g. "20th Oct 2052") into the standardized format "YYYY-MM-DD" (e.g. "2052-10-20").

  • The Day is a number followed by "st", "nd", "rd", or "th" (e.g. 6th, 1st).
  • The Month is a three-letter English abbreviation (e.g. Jan, Feb).
  • The Year is a four-digit number.
  • All parts are separated by a single space.
  • Return the reformatted date as a string in YYYY-MM-DD format, with two digits for both month and day (use leading zeros if necessary).

Thought Process

At first glance, the problem seems to require parsing and rearranging parts of a string. The main challenge is to extract the day number (removing its suffix), map the month abbreviation to its numeric value, and ensure proper formatting with leading zeros.

A brute-force approach would involve splitting the string, manually checking the month, and handling the day suffixes. However, using a dictionary or map for month abbreviations can make the solution concise and efficient. The key is to reliably extract and format each component, especially since the day can be one or two digits.

Solution Approach

  • Step 1: Split the input string by spaces to separate the day, month, and year.
  • Step 2: For the day, remove the last two characters (the suffix) and pad it with a leading zero if it's a single digit.
  • Step 3: Use a hash map (dictionary) to convert the month abbreviation to its two-digit number.
  • Step 4: Assemble the year, month, and day in the required format, separated by hyphens.
  • Step 5: Return the final string.

We use a hash map for months because it allows constant-time lookup, making the conversion from abbreviation to number both clear and efficient. String manipulation functions (like zfill in Python or padStart in JavaScript) help ensure the day is always two digits.

Example Walkthrough

Let's take the input "6th Jun 1933":

  1. Split into parts: ["6th", "Jun", "1933"]
  2. Extract day: "6th" → remove "th" → "6" → pad to "06"
  3. Map month: "Jun""06"
  4. Year is already "1933"
  5. Combine: "1933-06-06"

Each step ensures that the output is in the correct format and handles edge cases like single-digit days.

Time and Space Complexity

  • Brute-force Approach: Would involve manual parsing and multiple conditional checks, but since the input is always three parts, it's still O(1) time and space.
  • Optimized Approach: Using a hash map and string manipulation, each operation (split, lookup, formatting) is O(1) due to the fixed size of the input.
    • Time Complexity: O(1) – all operations are on a constant-sized string.
    • Space Complexity: O(1) – the hash map is of fixed size, and only a few variables are used.

Summary

The solution leverages simple string manipulation and a hash map for month conversion to reformat the date efficiently. The approach is direct, readable, and robust against edge cases thanks to the use of reliable string and mapping operations. This makes the solution both elegant and practical for real-world use.