Python 1507.py
class Solution:
def reformatDate(self, date: str) -> str:
day, month, year = date.split(" ")
# strip st/nd/rd/th
day = int(day[:-2])
# convert names
lookup = [ "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
month = lookup.index(month)
# year is unchanged, day and month need a leading zero
return f"{year}-{month:02d}-{day:02d}"
Difficulty
and has an acceptance rate of about 69% (100k+ submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a single method, reformatDate, that transforms a date string from the human-readable form "Day Month Year" (for example, "20th Oct 2052") into the ISO-8601 style "YYYY-MM-DD". The method assumes the day component ends with one of the ordinal suffixes st, nd, rd, or th, the month is given as a three-letter English abbreviation, and the year is a four-digit number. The implementation proceeds through a deterministic sequence of parsing, conversion, and formatting steps, each expressed with concise Python constructs.
Parsing the Input
The first operation separates the three logical parts of the input string using the space character as a delimiter.
day, month, year = date.split(" ")
This single call to str.split yields three substrings: the day with its ordinal suffix, the month abbreviation, and the year. Because the input format is fixed, the unpacking into day, month, and year is safe and avoids any additional conditional checks.
Normalizing the Day Component
The day portion includes a two-character suffix that must be removed before numeric conversion. The code slices off the last two characters and immediately casts the result to an integer.
day = int(day[:-2])
By converting directly to int, any leading zeros that might be present in the original string are discarded, ensuring a clean numeric representation for later formatting.
Converting Month Name to Number
Month conversion relies on a predefined lookup list where the index corresponds to the month number. The list starts with an empty string at index 0 so that "Jan" maps to index 1, "Feb" to 2, and so forth. The method finds the position of the month abbreviation using list.index.
lookup = [ "", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
month = lookup.index(month)
Because the list contains a constant 13 elements, the index operation executes in constant time, and the resulting integer directly represents the month number required for the final format.
Formatting the Output
The final step assembles the year, month, and day into the target string. A formatted string literal (f-string) is used with width specifications to guarantee two-digit month and day fields, automatically inserting leading zeros when necessary.
return f"{year}-{month:02d}-{day:02d}"
The :02d format specifier pads the integer with a leading zero if it is less than 10, satisfying the ISO-8601 requirement without extra conditional logic.
Edge Cases Handled
The implementation gracefully manages several variations inherent to the input format. The day suffix removal (day[:-2]) works uniformly for all four possible ordinal endings (st, nd, rd, th), because each suffix occupies exactly two characters. The month lookup list includes an empty placeholder at index 0, which prevents an off-by-one error and ensures that the month abbreviation maps correctly to its numeric counterpart. The zero-padding in the output format automatically handles single-digit days and months, producing strings like "2021-01-05" without additional checks.
Performance Optimizations
The code leverages Python’s built-in string operations and list indexing, both of which are highly optimized at the interpreter level. Splitting the input once avoids repeated scans of the string. The month conversion uses a static list and a direct index call; given the list’s fixed size, the lookup incurs negligible overhead compared to a dictionary or conditional chain. The final f-string construction is performed in a single step, minimizing temporary objects and memory allocations. Overall, the method executes with minimal computational work and low memory footprint, making it well-suited for processing large batches of dates.
ELI5 - Simplified Explanation
Think of this code like a helper that takes a messy date written in words and puts it into a tidy, standard format. First, the code looks at the date and takes it apart into three little pieces, which are the day, the month, and the year.
The day part has some extra letters at the end like st, nd, rd, or th, so the code snips those off to keep just the number. Next, there is a special list that acts like a dictionary. The code looks through this list to find the name of the month and figures out which number it matches, such as one for January or two for February.
Finally, the code puts everything back together in a new order. It puts the year first, then the month, and then the day. It also makes sure the month and day numbers are always written with two slots, adding a zero in front if they are just a single digit. This makes the date look perfectly uniform, kind of like organizing building blocks into a straight line.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | PHP | TS | |||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1413: Minimum Value to Get Positive Step by Step Sum
- problem 1460: Make Two Arrays Equal by Reversing Subarrays
- problem 1598: Crawler Log Folder
- problem 1944: Number of Visible People in a Queue
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality