Given a date string in a format of “Day Month Year”, where:
You are tasked with reformatting the date into the “YYYY-MM-DD” format.
day
, month
, and year
.#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
string reformatDate(string date) {
unordered_map<string, string> monthMap = {
{"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"},
{"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"},
{"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}
};
string day, month, year;
int i = 0;
// Extract day part
while (isdigit(date[i])) {
day.push_back(date[i]);
i++;
}
// Skip the suffix
while (!isspace(date[i])) i++;
i++;
// Extract month part
while (!isspace(date[i])) {
month.push_back(date[i]);
i++;
}
i++;
// Extract year part
while (i < date.size()) {
year.push_back(date[i]);
i++;
}
// Convert day to two digits
if (day.size() == 1) day = "0" + day;
// Get the month in two-digit format
string monthNumerical = monthMap[month];
return year + "-" + monthNumerical + "-" + day;
}
int main() {
string date = "20th Oct 2052";
cout << reformatDate(date) << endl; // Output: "2052-10-20"
return 0;
}
The time complexity of this solution is O(1) because regardless of the length and content of the input (given the constraints), the operations involved (string parsing and mapping) are constant and do not depend on the size of the input.
day
to a two-digit format by adding a leading zero if necessary.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?