How I solved the Hacker Rank Challenge, ‘Time Conversion’

Danielle Torres
2 min readJul 7, 2024

--

I enjoyed solving the Time Conversion challenge. I chose to use Python for this task because it’s a new language I’m learning, and it simplifies the process of solving algorithms.

Here are the challenge instructions:

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'

Below is the code I used to solve the problem. There are some great resources online on how to best convert time from 12 to 24 hours.

def timeConversion(s):
# Write your code here
if s[-2:] == 'AM' and s[:2] == '12':
return '00' + s[2:-2]
elif s[-2:] == 'AM':
return s[:-2]
elif s[-2:] == 'PM' and s[:2] == '12':
return s[:-2]
else:
return str(int(s[:2]) + 12) + s[2:8]

First, we check if the last two characters are AM or PM and if the first two are 12 then we return ‘00’ plus the string minus the first two characters and the last two.

Else if the last two characters are AM and the first two don’t equal 12 then we return everything except for the last two characters.

If the last two characters are PM and the first two are 12 then the string except for the last two characters is returned else convert the hour to 24-hour format by adding 12 to the hour and append the remaining part.

Since all operations within the function (string slicing, indexing, conditional checks, string concatenation, and integer conversion) are O(1)O(1)O(1), the overall time complexity of the timeConversion function is O(1)O(1)O(1). This means that the execution time of the function is constant and does not depend on the size of the input string, as it always processes a fixed number of characters.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Danielle Torres
Danielle Torres

Written by Danielle Torres

Highly organized & motivated Software Engineer with an application analyst/data analyst background.

No responses yet

Write a response