Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Get minimum time difference challenge

Sharing is caring!

Problem statement
Given an array of times in HH:MM format, find the minimum difference in minutes. The time is circular in nature. For example 23:52 and 00:08 have a difference of 16. Also 00:00 should be handled the same as 24:00.

Solution
The first key is to convert the string representation of each time into an int representing minutes:

int[] timeInMinutes = new int[times.length];

for (int i = 0; i < times.length; i++) {
    timeInMinutes[i] = Integer.valueOf(times[i].split(":")[0]) * 60 + Integer.valueOf(times[i].split(":")[1]);
}

Next, we iterate over the times and subtract each time from the following one checking for a new minimum each time:

int diff = Integer.MAX_VALUE;
for (int i=0; i < timeInMinutes.length-1; i++) {
    diff = Math.min(diff, timeInMinutes[i+1] - timeInMinutes[i]);
}

The last step is to complete the circle and make the first time the follower of the last time in the array by adding 1440\ (24\ hours) and subtracting the last time from it:

diff = Math.min(diff, (timeInMinutes[0] + 1440) - timeInMinutes[timeInMinutes.length-1]);

Full code

public class SmallestTimeDifference {
    private static int solve(String[] times) {
        int[] timeInMinutes = new int[times.length];

        // Convert each time to minutes
        for (int i = 0; i < times.length; i++) {
            timeInMinutes[i] = Integer.valueOf(times[i].split(":")[0]) * 60 + Integer.valueOf(times[i].split(":")[1]);
        }

        // Sort
        Arrays.sort(timeInMinutes);

        // Iterate over times and subtract each time from the following one
        int diff = Integer.MAX_VALUE;
        for (int i=0; i < timeInMinutes.length-1; i++) {
            diff = Math.min(diff, timeInMinutes[i+1] - timeInMinutes[i]);
        }

        // Circle : add 1440 (24 hour) to the first and subtract the last from it. That is make the first
        // time the following time of the last to complete the circle.
        diff = Math.min(diff, (timeInMinutes[0] + 1440) - timeInMinutes[timeInMinutes.length-1]);

        return diff;
    }

    public static void main(String args[]) {
        String times[] = {"23:20","23:30","23:36","23:55","01:00"};
        System.out.println(solve(times));
    }
}