Reformat Date - Problem

Given a date string in the form Day Month Year, convert it to the format YYYY-MM-DD.

Input Format:

  • Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}
  • Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
  • Year is in the range [1900, 2100]

Output Format:

  • YYYY denotes the 4-digit year
  • MM denotes the 2-digit month (01-12)
  • DD denotes the 2-digit day (01-31)

Input & Output

Example 1 — Basic Case
$ Input: date = "20th Oct 2052"
Output: "2052-10-20"
💡 Note: Split into day=20th, month=Oct, year=2052. Remove 'th' to get day=20, Oct is month 10, format as 2052-10-20
Example 2 — Single Digit Day
$ Input: date = "6th Jun 1933"
Output: "1933-06-06"
💡 Note: Day 6th becomes 06, Jun is month 06, year 1933. Result: 1933-06-06 with zero padding
Example 3 — End of Year
$ Input: date = "31st Dec 2099"
Output: "2099-12-31"
💡 Note: Last day of year: 31st becomes 31, Dec is month 12, format as 2099-12-31

Constraints

  • Date string is always valid and in the format "Day Month Year"
  • Day is in the set {"1st", "2nd", "3rd", ..., "31st"}
  • Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
  • Year is in the range [1900, 2100]

Visualization

Tap to expand
Reformat Date - Hash Map Lookup INPUT "20th Oct 2052" Split by space: Day "20th" Month "Oct" Year "2052" Original Format: Day Month Year Target Format: YYYY-MM-DD Month Hash Map: {"Jan":"01", "Feb":"02", ...} {"Oct":"10", ...} ALGORITHM STEPS 1 Extract Year Keep "2052" as-is 2052 2 Map Month Lookup "Oct" in map "Oct" --> "10" 3 Parse Day Remove suffix (th/st/nd/rd) "20th" --> "20" 4 Concatenate Join with "-" separator YYYY + "-" + MM + "-" + DD O(1) lookup time for month Hash Map advantage! FINAL RESULT Reformatted Date String: "2052-10-20" Component Breakdown: YYYY 2052 - MM 10 - DD 20 [OK] Validation: Year: 2052 (1900-2100) Month: 10 (01-12) Day: 20 (01-31) Output: "2052-10-20" Key Insight: Using a Hash Map for month lookup provides O(1) constant time conversion from month name to number. The day suffix (st, nd, rd, th) can be removed by extracting only numeric characters from the day string. Zero-padding ensures consistent format: single-digit days/months become "01"-"09" for proper YYYY-MM-DD format. TutorialsPoint - Reformat Date | Hash Map Lookup Approach
Asked in
Amazon 15 Microsoft 12 Facebook 8
25.4K Views
Medium Frequency
~10 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen