top of page

Reformat Date (LeetCode 1507): Parse Once, Format Once

Nov 4
1 min read

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.

 
 
 

Recent Posts

See All
Image Smoother (LeetCode 661): Clean Neighbor Loops

For each cell of a grayscale image, replace it with the floor of the average of itself and its up to eight neighbors. Idea Loop over the 3x3 block around each cell, skip coordinates outside the grid,

 
 
 

Comments


bottom of page