Reformat Date (LeetCode 1507): Parse Once, Format Once
Reformat Date (LeetCode 1507): Parse Once, Format Once
Given a date like 20th Oct 2052, return it as 2052-10-20. Days carry a suffix (st, nd, rd, th) and months are three-letter names.
Split into three parts
The input always has exactly three space-separated tokens. The day is the token without its last two characters, the month comes from a lookup table, and the year is used as-is.
def reformat_date(date):
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
day, mon, year = date.split()
d = int(day[:-2])
m = months.index(mon) + 1
return f'{year}-{m:02d}-{d:02d}'What to say in the interview
Point out that stripping two characters works for every suffix, so you never need to special-case 1st or 22nd. Mention that a dict lookup is O(1) if the interviewer worries about index on a list of twelve.
If you'd like to rehearse small parsing problems like this out loud, the Linkjob AI copilot is what my team builds.
Disclosure: I work on Linkjob AI.
Comments