Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Result {
- /**
- * Converts a HH:MM string to total minutes from the start of the day.
- */
- public static int timetoMin(String time) {
- String[] parts = time.split(":");
- return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]);
- }
- /**
- * Finds the earliest meeting time given busy events and duration k.
- * Uses a difference array to achieve O(n + 1440) complexity.
- */
- public static String getEarliestMeetTime(List<String> events, int k) {
- // Difference array for 1440 minutes (plus safety buffer for end+1)
- int[] diff = new int[1442];
- // 1. Parse events and mark busy periods
- for (String event : events) {
- String[] parts = event.split(" ");
- // The start and end times are the last two words in the string
- int start = timetoMin(parts[parts.length - 2]);
- int end = timetoMin(parts[parts.length - 1]);
- diff[start]++;
- diff[end + 1]--;
- }
- int busyCount = 0;
- int currentGap = 0;
- // 2. Iterate through every minute of the day
- for (int i = 0; i < 1440; i++) {
- busyCount += diff[i];
- if (busyCount == 0) {
- // Minute is free
- currentGap++;
- if (currentGap == k) {
- // We found a gap of size k ending at minute i
- int startMin = i - k + 1;
- return String.format("%02d:%02d", startMin / 60, startMin % 60);
- }
- } else {
- // Someone is busy, reset gap counter
- currentGap = 0;
- }
- } // End of loop
- // 3. Return -1 if no suitable time exists
- return "-1";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment