Reformat Date

Easy
0/40
Average time to solve is 15m
3 upvotes
Asked in companies
Expedia GroupIntuitWingify

Problem statement

You are given a string ‘S’ representing a date in the “Day Month Year” format, where:

1. Day is represented as {"1st", "2nd", "3rd", "4th",”5th”, ...,”29th”, "30th", "31st"}.

2. Month is represented as {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.

3. Year is represented as {2020,2021 etc}
Your task is to convert the given date into “YYYY-MM-DD” format, where:
1. YYYY is a 4 digit year.

2. MM is a 2 digit month.

3. DD is a 2 digit day.

Note:

1. The given dates are guaranteed to be valid.

2. If you can’t represent a month in 2 digits then append  0 in front of the month. Eg: if the month is Jan, represent it as 01 and not as 1 in the answer.

3. If you can’t represent a day in 2 digits then append 0 in front of the day. Eg: if the day is 5, represent it as 05 and not as 5 in the answer.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of the input contains an integer ‘T’ denoting the number of test cases. 

The first and the only line of each test case contains one string ‘S’, as described in the problem statement.
Output Format:
For each test case, print a single line containing a single string representing the date in “YYYY-MM-DD” format.

The output of every test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10 ^ 4

Day belongs in the set  {"1st", "2nd", "3rd", "4th",”5th”, ...,”29th”, "30th", "31st"}.
Month belongs in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
1000 <= Year <= 2021 


Time Limit: 1 second.
Sample Input 1:
1
27th Apr 1998
Sample Output 1:
1998-04-27
Explanation for sample input 1:
“27th Apr 1998” will be converted to “1998-04-27” in “YYYY-MM-DD” format.
Hint

Handle the conversions of day, month, and year separately.

Approaches (1)
Brute Force Approach

In this brute force approach, We will keep a map (say ‘MONTHS’) that will map the month given in words to digit, Eg: Apr to 4 and Jan to 1.

 

  • ‘MONTHS’= {{ "Jan", "01" },{ "Feb", "02" },{ "Mar", "03" },{ "Apr", "04" },{ "May", "05" },{ "Jun", "06" },{ "Jul", "07" },{ "Aug", "08" },{ "Sep", "09" },{ "Oct", "10" },{ "Nov", "11" }, { "Dec", "12" } }

 

Now we will parse the date from left to right and extract the DAY, MONTH and YEAR from the input and finally return YEAR-MONTHS[MONTH]-DAY as the output.

Time Complexity

O(1).

 

Since the size of the given string is very small hence we can consider the time complexity to be O(1).

Space Complexity

O(1). 

 

Since we are using constant extra space the space complexity is O(1).

Code Solution
(100% EXP penalty)
Reformat Date
Full screen
Console