HackerRank Time Conversion Java Solution Explained


Problem Overview

Original Problem: Time Conversion | HackerRank

Difficulty: Easy

Category: String Manipulation

Description: Convert a time string from 12-hour AM/PM format (e.g., "08:10:20PM") to 24-hour (military) format (e.g., "20:10:20"). The output should be a string representing the time in 24-hour format.

This problem, part of HackerRank’s One Week Preparation Kit, is an excellent way for beginners to practice string parsing and conditional logic in Java, skills essential for coding interviews.

Understanding the Problem

The Time Conversion problem requires transforming a time string from the 12-hour clock format (with AM/PM) to the 24-hour clock format. For example, "08:10:20PM" becomes "20:10:20", and "12:00:00AM" becomes "00:00:00". The input is always a valid time string in the format "hh:mm:ssAM" or "hh:mm:ssPM", where hours range from 01 to 12. The challenge tests your ability to manipulate strings, handle conditional logic for AM/PM, and format the output correctly.

Input and Output

  • Input:

    • A single string s in 12-hour format: "hh:mm:ssAM" or "hh:mm:ssPM", where:

      • hh is hours (01 to 12).

      • mm is minutes (00 to 59).

      • ss is seconds (00 to 59).

      • The suffix is either "AM" or "PM".

  • Output:

    • A string representing the time in 24-hour format: "hh:mm:ss", where hours range from 00 to 23.

  • Constraints:

    • All input times are valid.

    • Hours in the input are from "01" to "12".

    • Minutes and seconds are from "00" to "59".

    • The input string is exactly 10 characters long.

Initial Reasoning

To solve this, we need to:

  1. Extract the hours, minutes, seconds, and AM/PM suffix from the input string.

  2. Convert the hours based on AM/PM rules:

    • For AM: 12:xx:xxAM becomes 00:xx:xx; other AM times stay the same (e.g., 07:xx:xxAM is 07:xx:xx).

    • For PM: Add 12 to hours unless it’s 12:xx:xxPM (which stays 12:xx:xx).

  3. Format the output as a string in "hh:mm:ss" format, ensuring two-digit hours.

  4. Use string manipulation or parsing to handle the input and output formatting.
    This can be done efficiently with string operations and simple conditionals, requiring O(1) time since the input size is fixed.

Thought Process

Let’s break down the solution step-by-step:

  1. Parse the Input:

    • The input string is in the format "hh:mm:ssAM" or "hh:mm:ssPM".

    • Extract the hours (first two characters), minutes (characters 3–4), seconds (characters 6–7), and AM/PM suffix (last two characters).

    • Alternatively, split the string at ":" and extract the AM/PM from the last part.

  2. Handle AM/PM Conversion:

    • Check the AM/PM suffix:

      • If PM and hours ≠ 12, add 12 to the hours (e.g., 07PM → 19).

      • If PM and hours = 12, keep hours as 12.

      • If AM and hours = 12, set hours to 00.

      • If AM and hours ≠ 12, keep hours as is.

    • Convert the hours to an integer for calculations and back to a two-digit string for output.

  3. Format the Output:

    • Construct the output string as "hh:mm:ss", where hours is a two-digit number (e.g., "07" or "19").

    • Use string formatting to ensure leading zeros for hours (e.g., "00" for midnight).

  4. Edge Cases:

    • 12:00:00AM: Should output "00:00:00".

    • 12:00:00PM: Should output "12:00:00".

    • 01:00:00AM/PM: Ensure hours are formatted as "01" or "13".

    • The constraints guarantee valid inputs, so no need to validate format or ranges.

Pseudocode

// timeConversion method:
Extract hours, minutes, seconds, and AM/PM from input string
If time is AM and hour is not equal to 12
	Add 12 hours 
Else if time is AM and hours equals 12 
	Set hours to 0
Format hours as two-digit string
Construct output string
Return formatted time string

Solution Code

// Note: This is one of many possible solutions
// Note: Variable names have been updated from HackerRank's defaults (e.g., 's', 'hoursString') to more descriptive names
// Note: Variable names have been updated from the original template for clarity and to follow Java naming conventions (e.g., 's' to 'time12Hour')
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

   public static String timeConversion(String time12Hour) {
    
        // Extract hours, minutes, seconds, and period
        int hours = Integer.parseInt(time12Hour.substring(0, 2));
        String minutes = time12Hour.substring(3, 5);
        String seconds = time12Hour.substring(6, 8);
        String period = time12Hour.substring(8, 10);
    
        // Convert to 24-hour format
        if (period.equals("PM") && hours != 12) {
            hours += 12;
        } else if (period.equals("AM") && hours == 12) {
            hours = 0;
        }
    
        String formattedHours = String.format("%02d", hours);
    
        // Construct and return the result
        return formattedHours + ":" + minutes + ":" + seconds;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String time12Hour = bufferedReader.readLine();

        String result = Result.timeConversion(time12Hour);

        bufferedWriter.write(result);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Step-by-Step Explanation

Let’s break down the Java solution for beginners:

  1. Input Handling:

    • The main method reads a single string time12Hour using BufferedReader.

    • The timeConversion method takes this string as input and returns the converted time.

  2. Parsing the Input:

    • Extract components using substring:

      • hours = time12Hour.substring(0, 2) (e.g., "08") → convert to integer with Integer.parseInt.

      • minutes = time12Hour.substring(3, 5) (e.g., "10").

      • seconds = time12Hour.substring(6, 8) (e.g., "20").

      • period = time12Hour.substring(8, 10) (e.g., "PM").

  3. Converting to 24-Hour Format:

    • Check the period (AM/PM):

      • If period is "PM" and hours is not 12, add 12 to hours (e.g., 08PM → 20).

      • If period is "AM" and hours is 12, set hours to 0 (e.g., 12AM → 00).

      • Otherwise, hours remains unchanged (e.g., 08AM → 08, 12PM → 12).

  4. Formatting Hours:

    • Use String.format("%02d", hours) to ensure hours is a two-digit string (e.g., 8 becomes "08", 19 stays "19").

  5. Constructing the Output:

    • Concatenate hoursString, ":", minutes, ":", and seconds to form the result (e.g., "20:10:20").

    • Return the resulting string.

  6. Output Handling:

    • In the main method, write the result to the output file using BufferedWriter and add a newline.

    • Close both BufferedReader and BufferedWriter to prevent resource leaks.

Common Mistakes to Avoid

Here are common pitfalls for beginners:

  • Incorrect String Parsing: Using wrong substring indices (e.g., time12Hour.substring(0, 1) for hours) can lead to incorrect hour values or runtime errors. Always verify indices match the format "hh:mm:ssAM".

  • Ignoring AM/PM Edge Cases: Forgetting to handle 12:xx:xxAM (→ 00:xx:xx) or 12:xx:xxPM (→ 12:xx:xx) can cause incorrect outputs.

  • Missing Leading Zeros: Not formatting hours as two digits (e.g., outputting "8" instead of "08") fails the required format. Use String.format("%02d", hours).

Real-World Application

Time conversion logic is common in software applications dealing with scheduling, logging, or internationalization. For example, a global calendar app might convert local times (12-hour format) to a standardized 24-hour format for backend processing. This problem teaches string manipulation and conditional logic, skills used in parsing data formats in web development, APIs, and database systems.

FAQs

Q: Why use substring instead of splitting the string?
A: substring is simpler for a fixed-format input like "hh:mm:ssAM", as it avoids extra array creation from splitting. Splitting (e.g., s.split(":")) is viable but requires additional handling for the AM/PM suffix.

Q: Can I use SimpleDateFormat for this problem?
A: Yes, but it’s overkill for a simple conversion task and less beginner-friendly. SimpleDateFormat involves parsing and formatting dates, which adds complexity compared to direct string manipulation.

Q: Why ensure two-digit hours in the output?
A: The 24-hour format requires hours to be two digits (e.g., "08" instead of "8") to match the problem’s output format and ensure consistency.