Problem 1507

Abstract / Summary

Convert date from one format to another by rearranging parts and changing month numbers to names.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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}"
13 lines | 456 bytes | submitted January 11, 2024 | GitHub   42% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (100k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.41 | σ = 0.91

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
32 links | 20 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   January 11, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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