Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

539. Minimum Time Difference

ArrayMathStringSorting

Explanation

To solve this problem, we can convert each time point to minutes from midnight, sort the minutes, and then find the minimum difference between consecutive times. Since the time wraps around (e.g., 23:59 is close to 00:00), we also need to consider the circular nature of time.

  • Convert each time to minutes from midnight.
  • Sort the minutes.
  • Find the minimum difference between consecutive times.
  • Also, consider the circular nature of time.

Time Complexity: O(n log n) - Sorting the time points \n Space Complexity: O(n) - Storing the minutes from midnight

import java.util.*;

class Solution {
    public int findMinDifference(List<String> timePoints) {
        List<Integer> minutes = new ArrayList<>();
        
        for (String time : timePoints) {
            String[] parts = time.split(":");
            int hour = Integer.parseInt(parts[0]);
            int minute = Integer.parseInt(parts[1]);
            minutes.add(hour * 60 + minute);
        }
        
        Collections.sort(minutes);
        
        int minDiff = Integer.MAX_VALUE;
        for (int i = 1; i < minutes.size(); i++) {
            minDiff = Math.min(minDiff, minutes.get(i) - minutes.get(i - 1));
        }
        
        minDiff = Math.min(minDiff, 24 * 60 + minutes.get(0) - minutes.get(minutes.size() - 1));
        
        return minDiff;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.