Convert Seconds to Hours, Minutes and Seconds

Solve this Problem
Easy10 min
Topics
Companies
Given a number of seconds total, return it as [hours, minutes, seconds], where minutes and seconds are each below 60. An algorithmAlgorithmA finite, precise sequence of steps that turns an input into the correct output. is just a clear recipe that always finishes with the right answer. This problem has two perfectly valid recipes: repeatedly take away an hour or a minute, or divide once. Both are correct, but they need very different amounts of work as the input grows — the idea behind everything else in this section.

Test Case 1:

Input:total = 3725
Output:[1, 2, 5]
Explanation:3600 seconds make one hour, 120 of the remaining 125 make two minutes, and 5 seconds are left.

Test Case 2:

Input:total = 59
Output:[0, 0, 59]
Explanation:Less than a minute: only seconds.

Constraints

  • ◆0 ≤ total ≤ 1000000

Try the Dry Run

Approach & Solutions

Repeated SubtractionBrute

An algorithm is a precise list of steps. Here is one a person might follow by hand: while at least 3600 seconds remain, take away an hour; then, while at least 60 remain, take away a minute; whatever is left is the seconds. It always finishes and is always right, but the number of steps grows with the input.

TimeO(total / 60)
SpaceO(1)
class Solution { public int[] splitSeconds(int total) { int hours = 0; int minutes = 0; int seconds = total; while (seconds >= 3600) { seconds -= 3600; hours++; } while (seconds >= 60) { seconds -= 60; minutes++; } return new int[] {hours, minutes, seconds}; } }
Division and RemainderOptimal

Replace each loop by the operation it was imitating. Integer division by 3600 gives the hours at once and % 3600 what is left; then / 60 and % 60 split that remainder into minutes and seconds. Four arithmetic operations, whatever the input.

TimeO(1)
SpaceO(1)
class Solution { public int[] splitSeconds(int total) { int hours = total / 3600; int rest = total % 3600; int minutes = rest / 60; int seconds = rest % 60; return new int[] {hours, minutes, seconds}; } }

Related Problems