Reformat Date solution and explanation
9 more videos on this problem
reformat date | reformat date leetcode | leetcode 1507Naresh Gupta · 6:24 · 1K views
Reformat Date | LeetCode 1507 | LeetCode Biweekly 30 | Java | HindiPepcoding · 12:34 · 1K views
Leetcode | 1507. Reformat Date | Easy | Java SolutionDeveloper Docs · 9:33 · 1K views
1507. Reformat Date | Leetcode | Interview Question Mahindra ComvivaChhavi Bansal · 13:21 · 899 views
Vol5 - Leetcode - Problem 1507 - Reformat date - Golang - Phỏng vấn - Thuật toánYuh lập trình viên · 15:20 · 855 views
1507. Reformat Date (Leetcode Easy)Programming Live with Larry · 4:39 · 666 views
Biweekly Contest 30 || Problem 1507 , 1508 , 1509 || LEETCODEcode Explainer · 12:32 · 588 views
Reformat Date Java Solution | Leetcode 1507Competitive Coding · 5:06 · 382 views
[LeetCode] 1507. Reformat DateCode Granate · 4:43 · 128 views
[SOLVED!] Reformat Date - LeetCode 1507 - JavaScott Hacks Code · 4:59 · 46 views
The problem
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.
Approach overview
Problem Overview: You receive a human-readable date string like "20th Oct 2052". The goal is to convert it into ISO format "2052-10-20". The challenge is extracting the day while removing ordinal suffixes (st, nd, rd, th) and converting the month abbreviation into its numeric representation.
Approach 1: String Parsing and Dictionary Mapping (Time: O(n), Space: O(1))
The most direct solution splits the input string into three parts: day, month, and year. The day portion contains a numeric value followed by a suffix (for example "6th" or "21st"), so you extract the numeric characters and pad with a leading zero if needed. The month abbreviation (Jan, Feb, etc.) is converted using a fixed dictionary that maps each month to its two-digit number. The year already appears in the required format. Finally, concatenate the parts as year-month-day. This approach relies only on basic string operations such as splitting, substring extraction, and dictionary lookup.
The key insight is that the month set is small and fixed (12 values), so a constant-time mapping works best. Each part of the string is processed once, giving linear time relative to the input length. Because the dictionary size never changes, the space usage is constant.
Approach 2: Regular Expression and String Manipulation (Time: O(n), Space: O(n))
Another option uses regular expressions to extract structured components from the input. A regex pattern can capture the numeric day, ignore the ordinal suffix, and isolate the month abbreviation and year. After matching, convert the month abbreviation through the same lookup table used in the previous method. Format the output string using zero-padded day and month values.
This method is useful when input formats vary slightly or when you want cleaner extraction logic in languages with strong regex support. However, regex introduces extra overhead and temporary match objects, which increases memory usage compared to simple splitting. The time complexity remains linear because the pattern scans the input string once.
Recommended for interviews: The string parsing and dictionary mapping approach is the expected solution. It shows that you can reason about input structure and build a straightforward transformation with constant auxiliary memory. Regex solutions work, but interviewers typically prefer explicit parsing since it demonstrates stronger control over string manipulation and avoids unnecessary abstraction. If you explain both options, start with manual parsing to show clarity, then mention regex as an alternative implementation.
Approach 1: String Parsing and Dictionary Mapping
In this approach, we will parse the given date string to extract the day, month, and year. We will then use a dictionary to map the month abbreviations to their respective numeric representations. Finally, the result is formatted to 'YYYY-MM-DD'.
def reformatDate(date: str) -> str:
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"
}
day, month, year = date.split()
day = day[:-2] # Remove the suffix
return f"{year}-{month_map[month]}-{int(day):02d}"
print(reformatDate("20th Oct 2052"))import java.util.HashMap;
import java.util.Map;
public class ReformatDate {
static Map<String, Integer> monthMap = new HashMap<>();
static {
monthMap.put("Jan", 1);
monthMap.put("Feb", 2);
monthMap.put("Mar", 3);
monthMap.put("Apr", 4);
monthMap.put("May", 5);
monthMap.put("Jun", 6);
monthMap.put("Jul", 7);
monthMap.put("Aug", 8);
monthMap.put("Sep", 9);
monthMap.put("Oct", 10);
monthMap.put("Nov", 11);
monthMap.put("Dec", 12);
}
public static String reformatDate(String date) {
String[] parts = date.split(" ");
String day = parts[0].substring(0, parts[0].length() - 2);
String month = String.format("%02d", monthMap.get(parts[1]));
String year = parts[2];
return String.format("%s-%s-%02d", year, month, Integer.parseInt(day));
}
public static void main(String[] args) {
String date = "20th Oct 2052";
System.out.println(reformatDate(date));
}
}#include <iostream>
#include <sstream>
#include <iomanip>
#include <unordered_map>
using namespace std;
unordered_map<string, int> monthMap = {
{"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Apr", 4},
{"May", 5}, {"Jun", 6}, {"Jul", 7}, {"Aug", 8},
{"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12}
};
string reformatDate(string date) {
istringstream iss(date);
string day, month, year;
iss >> day >> month >> year;
int dayNum = stoi(day.substr(0, day.length() - 2));
ostringstream oss;
oss << year << "-" << setw(2) << setfill('0') << monthMap[month] << "-" << setw(2) << setfill('0') << dayNum;
return oss.str();
}
int main() {
string date = "20th Oct 2052";
cout << reformatDate(date) << endl;
return 0;
}function reformatDate(date) {
const monthMap = {
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 dayNum = day.substring(0, day.length - 2);
return `${year}-${monthMap[month]}-${dayNum.padStart(2, '0')}`;
}
console.log(reformatDate("20th Oct 2052"));#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int getMonthNumber(const char* month) {
for(int i = 0; i < 12; i++) {
if(strcmp(month, months[i]) == 0) {
return i + 1;
}
}
return -1; // should never happen
}
char* reformatDate(char* date) {
int day, year, month;
char monthStr[4];
sscanf(date, "%d%*[^ ] %s %d", &day, monthStr, &year);
month = getMonthNumber(monthStr);
char* result = malloc(11);
sprintf(result, "%04d-%02d-%02d", year, month, day);
return result;
}
int main() {
char date[] = "20th Oct 2052";
char* reformattedDate = reformatDate(date);
printf("%s\n", reformattedDate);
free(reformattedDate);
return 0;
}using System;
using System.Collections.Generic;
public class Program
{
static Dictionary<string, int> monthMap = new Dictionary<string, int> {
{"Jan", 1}, {"Feb", 2}, {"Mar", 3}, {"Apr", 4},
{"May", 5}, {"Jun", 6}, {"Jul", 7}, {"Aug", 8},
{"Sep", 9}, {"Oct", 10}, {"Nov", 11}, {"Dec", 12}
};
public static string ReformatDate(string date) {
var parts = date.Split(' ');
var day = int.Parse(parts[0].Substring(0, parts[0].Length - 2));
var month = monthMap[parts[1]];
var year = parts[2];
return string.Format("{0}-{1:D2}-{2:D2}", year, month, day);
}
public static void Main() {
Console.WriteLine(ReformatDate("20th Oct 2052"));
}
}The Python solution makes use of dictionary mapping for months and formatted string literals for assembling the date. The day is converted to an integer for zero-padded formatting.
Time Complexity: O(1) for parsing a fixed-length string and map lookup.
Space Complexity: O(1) for a fixed size map and intermediate variables.
Approach 2: Regular Expression and String Manipulation
Here, we utilize a regular expression to extract the day, month, and year separately. This approach eliminates multiple string operations by capturing groups when matching patterns directly.
import re
def reformatDate(date: str) -> str:
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"
}
match = re.match(r'(\d+)(?:th|rd|st|nd) (\w+) (\d{4})', date)
if match:
day, month, year = match.groups()
return f"{year}-{month_map[month]}-{int(day):02d}"
return ""
print(reformatDate("20th Oct 2052"))#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>
const char* months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int getMonthNumber(const char* month) {
for(int i = 0; i < 12; i++) {
if(strcmp(month, months[i]) == 0) {
return i + 1;
}
}
return -1;
}
char* reformatDate(const char* date) {
regex_t regex;
regmatch_t pmatch[4];
int reti;
reti = regcomp(®ex, "^(\\d+)(?:th|rd|st|nd) (\\w+) (\\d{4})$", REG_EXTENDED);
if (reti) return NULL;
reti = regexec(®ex, date, 4, pmatch, 0);
if (!reti) {
char day[3], monthStr[4], year[5];
snprintf(day, pmatch[1].rm_eo - pmatch[1].rm_so + 1, "%s", date + pmatch[1].rm_so);
snprintf(monthStr, pmatch[2].rm_eo - pmatch[2].rm_so + 1, "%s", date + pmatch[2].rm_so);
snprintf(year, pmatch[3].rm_eo - pmatch[3].rm_so + 1, "%s", date + pmatch[3].rm_so);
int month = getMonthNumber(monthStr);
char* result = malloc(11);
sprintf(result, "%04s-%02d-%02d", year, month, atoi(day));
regfree(®ex);
return result;
}
regfree(®ex);
return NULL;
}
int main() {
const char date[] = "20th Oct 2052";
char* reformattedDate = reformatDate(date);
if (reformattedDate) {
printf("%s\n", reformattedDate);
free(reformattedDate);
}
return 0;
}Python's regular expression module (re) is used for efficient extraction of groups, simplifying the parsing process. This avoids direct string manipulation beyond initial parsing.
Time Complexity: O(1) for the fixed length string processing with regex.
Space Complexity: O(1), it only uses limited additional space for regex and variables.
Approach 3: Default Approach
function reformatDate(date: string): string {
const s = date.split(' ');
const months = ' JanFebMarAprMayJunJulAugSepOctNovDec';
const day = parseInt(s[0].substring(0, s[0].length - 2));
const month = Math.floor(months.indexOf(s[1]) / 3) + 1;
return `${s[2]}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
}func reformatDate(date string) string {
s := strings.Split(date, " ")
day, _ := strconv.Atoi(s[0][:len(s[0])-2])
months := " JanFebMarAprMayJunJulAugSepOctNovDec"
month := strings.Index(months, s[1])/3 + 1
year, _ := strconv.Atoi(s[2])
return fmt.Sprintf("%d-%02d-%02d", year, month, day)
}class Solution {
/**
* @param String $date
* @return String
*/
function reformatDate($date) {
$arr = explode(' ', $date);
$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',
];
$year = $arr[2];
$month = $months[$arr[1]];
$day = intval($arr[0]);
if ($day > 0 && $day < 10) {
$day = '0' . $day;
}
return $year . '-' . $month . '-' . $day;
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| String Parsing and Dictionary Mapping | Time Complexity: O(1) for parsing a fixed-length string and map lookup. |
| Regular Expression and String Manipulation | Time Complexity: O(1) for the fixed length string processing with regex. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| String Parsing and Dictionary Mapping | O(n) | O(1) | Best general solution. Clear logic, constant memory, and easy to implement in interviews. |
| Regular Expression and String Manipulation | O(n) | O(n) | Useful when parsing structured text or when regex utilities simplify extraction. |
Frequently asked questions
Is Reformat Date easy or hard?
Reformat Date is categorized as an Easy problem. It focuses on string parsing, handling ordinal suffixes, and mapping month abbreviations, making it a good practice problem for beginners learning string manipulation.
Reformat Date Python/Java solution
Python and Java solutions usually split the string by spaces, extract the numeric part of the day, and map the month abbreviation using a dictionary or HashMap. After zero-padding the day and using the mapped month number, the result is formatted as YYYY-MM-DD.
How to solve Reformat Date in O(n)?
Split the date string into three tokens: day, month, and year. Strip the suffix from the day (st, nd, rd, th), convert the month abbreviation using a fixed map like {"Jan":"01"}, and pad the day to two digits if needed. Combine the parts as year-month-day. Each step scans or processes the string once, resulting in O(n) time.
What is the best approach for Reformat Date?
The best approach uses string parsing with a dictionary that maps month abbreviations to their numeric values. Split the input into day, month, and year, remove the ordinal suffix from the day, and format the output as YYYY-MM-DD. This solution runs in O(n) time and uses O(1) extra space.
Is Reformat Date asked at Google/Amazon/Meta?
Reformat Date is a common easy-level string manipulation problem that appears in coding interview preparation sets. Variations of date parsing and formatting are frequently used by companies like Amazon and Google to test basic string handling and attention to edge cases.
What data structure is used in Reformat Date?
A hash map (dictionary) is typically used to convert month abbreviations such as Jan, Feb, and Mar into numeric values like 01, 02, and 03. The rest of the solution relies on basic string operations like splitting and substring extraction.
What is the time complexity of Reformat Date?
The optimal solution runs in O(n) time where n is the length of the input string. Each character is processed at most once while splitting and extracting components. The month lookup uses a constant-size dictionary, so it does not affect complexity.
