Problem Description
Given a date string in the format "Day Month Year", where Day is a number with a suffix (like "20th" or "6th"), Month is a three-letter abbreviation (e.g., "Oct", "Jun"), and Year is a four-digit number, convert the date string into the format "YYYY-MM-DD". For example, given "20th Oct 2052", return "2052-10-20".
Key Insights
- Extract the day by removing the suffix ("st", "nd", "rd", "th") and converting the remaining part to an integer.
- Use a mapping from month abbreviations to their corresponding two-digit numerical format.
- Pad day (and month if needed) with a leading zero to ensure they are two digits.
- Concatenate the formatted year, month, and day with hyphens.
Space and Time Complexity
Time Complexity: O(1) - Processing and formatting the fixed-length input is constant. Space Complexity: O(1) - Only a fixed amount of extra space is used for variables.
Solution
The solution involves parsing the given date string by splitting it into three parts: day, month, and year. Remove the suffix from the day to get the numerical day and convert it into a two-digit format. Use a predefined dictionary (or hash map) that maps month abbreviations to their corresponding two-digit string. Finally, assemble the year, month, and day into a string formatted as "YYYY-MM-DD". This approach uses simple string operations and dictionary lookups, ensuring constant time and space complexity.