Skip to main content

Command Palette

Search for a command to run...

Time Conversion Algorithm🕑🕝

This algorithm is a part of HackerRank's algo warmup challenges.

Updated
4 min read
Time Conversion Algorithm🕑🕝
U

Writing about things I learn helps me understand better, and I hope reading them will help you too! 🙂

In this article, I'll be describing how I solved the Time Conversion Challenge on HackerRank using Python 3.

This challenge is part of the Warmup challenges for the Algorithm section on HackerRank.

Problem 🎲

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note:

  • 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
  • 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

- s = '12:01:00PM': 
   Return '12:01:00'.

- s = '12:01:00AM': 
   Return '00:01:00'.

Function Description

Complete the timeConversion function in the editor. It should return a new string representing the input time in 24-hour format.

timeConversion has the following parameter(s):

  • string s: a time in 12-hour format

Returns

  • string: the time in 24-hour format

Input Format

A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM)

Constraints

  • All input times are valid

Samle Input:

'07:05:45PM'

Samle Ouput:

'19:05:45'

Solution 🔎

As always, we will start by breaking the problem into smaller bits and solving each bit synchronously.

Let's assume s = '12:01:00AM' to test our solution.

def timeConversion(s):
    # Write your code here

Step 1️⃣ : Slicing and splitting the input string into two parts. 🔪

  • Since we are given the time format in a string of constant length, we can split all characters minus the last two (i.e. PM or AM).
  • This means splitting the string s by the delimiter : and slicing the first 8 characters.
  • Let's store the sliced array showing only digits in a variable, a.
  • and store the time format part of the array in a variable,tf.
    a = s[:8].split(":") 
    >> ['12', '01', '00']
    tf = s[-2:]
    >> AM
    

Step 2️⃣: String array to int array ⚙️

  • We need to convert this string array (containing digits) into an integer array, so we can easily manipulate them in our time conversion logic 🤓.
  • To achieve this, we use python's map function.

    map(function, iterable, ...) returns an iterator that applies a function to every item of iterable, yielding the result.

a = list(map(int, a))
>> [12, 1, 0]
  • Here, we called the int function on every item in the array and converted the result to a list.

Step 3️⃣: Time conversion logic time!⏱️

  • We use conditional statements to implement our logic.
  • Here, we'll do the following:
    • Return hh + 12, if the time is PM and not 12 (all digits from 0 - 11),

      example: return 17 if its 5PM.

    • Return hh - 12, if the time is AM and 12,

      example: return 0 if its 12AM.

    • Return the same value in all other cases (example in mm digits).
      if tf == 'PM' and a[0] != 12: a[0]+=12 
      elif tf == 'AM' and a[0]==12: a[0]-=12
      >>
      

Step 4️⃣: Convert our manipulated int array back to a string array.

  • Here, we'll convert our int array (after applying our time conversion logic) back to a string array (temporarily store its items in a variable b, while also maintaining leading zeroes using python's .zfill() function
  • Then, store our new strings in a new string array called a_new.
    b = list(map(str, a))
      for num in b: 
          a_new.append(num.zfill(2))
    >> ['00', '01', '00']
    

Step 5️⃣: Return our string array in the desired string format. 🥅

  • Let's convert our string array back to the desired HH:SS:MM format using python's join() function
  • Finally, we return the string in a variable, ouput.
    output = ':'.join(a_new)
      return output
    >> 00:01:00
    

Full code:

def timeConversion(s):
    # Write your code here
    a = s[:8].split(":")
    a = list(map(int, a))

    tf = s[-2:]

    if tf == 'PM' and a[0] != 12: a[0]+=12
    elif tf == 'AM' and a[0]==12: a[0]-=12

    b = list(map(str, a))
    a_new = []
    for num in b:
        a_new.append(num.zfill(2))

    output = ':'.join(a_new)

    return output



timeConversion('12:01:00AM')

Hope this helps with understanding this challenge. Happy Coding!👨🏽‍💻

Buy me a coffee.png

Algos in Plain English

Part 1 of 24

In this series, I'll code solutions to the HackerRank challenges with succinct explanation. Hope this helps anyone looking to improve their skills on data structures and algorithms!

Up next

Grading Students Algorithm

This algorithm is a part of HackerRank's algorithm implementation challenges.