algoadvance

Leetcode 1507. Reformat Date

Problem Statement

Given a date string in the form Day Month Year, where:

Your task is to convert this date to the format YYYY-MM-DD, where:

Example:

Clarifying Questions

  1. Input Constraints:
    • Can the input date string have leading/trailing spaces?
    • Is the input always valid (i.e., always in the correct Day Month Year format)?
  2. Output Format:
    • Should the output be a string in YYYY-MM-DD format?
  3. Edge Cases:
    • Is Day always going to be within a valid range for the given month?

Assuming the input is always correctly formatted and within valid ranges:

  1. **No leading/trailing spaces as it’s directly from the problem.
  2. **Output must be a string in YYYY-MM-DD format.
  3. **Days are always valid.

Strategy

  1. Extract Parts: Extract the day, month, and year from the input string.
  2. Map the Month: Create a mapping of month names to month numbers.
  3. Format Day: Remove the suffix from the day and ensure it’s two digits.
  4. Combine & Return: Combine year, month, and day into the YYYY-MM-DD format.

Time Complexity

The time complexity should be O(1) as we’re doing a fixed amount of operations regardless of the input length.

Code

Let’s implement this in Java:

import java.util.HashMap;
import java.util.Map;

public class ReformatDate {
    public static String reformatDate(String date) {
        // Map of month names to month numbers
        Map<String, String> monthMap = new HashMap<>();
        monthMap.put("Jan", "01");
        monthMap.put("Feb", "02");
        monthMap.put("Mar", "03");
        monthMap.put("Apr", "04");
        monthMap.put("May", "05");
        monthMap.put("Jun", "06");
        monthMap.put("Jul", "07");
        monthMap.put("Aug", "08");
        monthMap.put("Sep", "09");
        monthMap.put("Oct", "10");
        monthMap.put("Nov", "11");
        monthMap.put("Dec", "12");
        
        // Split the input date by spaces
        String[] parts = date.split(" ");
        
        // Extract day, month and year
        String day = parts[0];
        String month = parts[1];
        String year = parts[2];
        
        // Remove suffix in the day
        day = day.substring(0, day.length() - 2);
        // Ensure day is two digits
        if (day.length() == 1) {
            day = "0" + day;
        }
        
        // Get the month number from the map
        String monthNumber = monthMap.get(month);
        
        // Combine into the desired format
        return year + "-" + monthNumber + "-" + day;
    }

    public static void main(String[] args) {
        String date = "20th Oct 2052";
        System.out.println(reformatDate(date));  // Output: 2052-10-20
    }
}

This code will take the input in the specified format and convert it to the YYYY-MM-DD format successfully.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI