LeetCode Solutions

539. Minimum Time Difference

Time: $O(n)$

Space: $O(24 \cdot 60)$

			

class Solution {
 public:
  int findMinDifference(vector<string>& timePoints) {
    int ans = 24 * 60;
    int first = 24 * 60;
    vector<bool> bucket(24 * 60);

    for (const string& time : timePoints) {
      const int num = stoi(time.substr(0, 2)) * 60 + stoi(time.substr(3));
      first = min(first, num);
      if (bucket[num])
        return 0;
      bucket[num] = true;
    }

    int prev = first;

    for (int i = first + 1; i < bucket.size(); ++i)
      if (bucket[i]) {
        ans = min(ans, i - prev);
        prev = i;
      }

    return min(ans, 24 * 60 - prev + first);
  }
};
			

class Solution {
  public int findMinDifference(List<String> timePoints) {
    int ans = 24 * 60;
    int first = 24 * 60;
    boolean[] bucket = new boolean[24 * 60];

    for (final String timePoint : timePoints) {
      final int num =
          Integer.valueOf(timePoint.substring(0, 2)) * 60 + Integer.valueOf(timePoint.substring(3));
      first = Math.min(first, num);
      if (bucket[num])
        return 0;
      bucket[num] = true;
    }

    int prev = first;

    for (int i = first + 1; i < bucket.length; ++i)
      if (bucket[i]) {
        ans = Math.min(ans, i - prev);
        prev = i;
      }

    return Math.min(ans, 24 * 60 - prev + first);
  }
}
			

class Solution:
  def findMinDifference(self, timePoints: List[str]) -> int:
    ans = 24 * 60
    nums = sorted([int(timePoint[:2]) * 60 + int(timePoint[3:])
                   for timePoint in timePoints])

    for a, b in zip(nums, nums[1:]):
      ans = min(ans, b - a)

    return min(ans, 24 * 60 - nums[-1] + nums[0])