Iam_Sandeep

Untitled

Feb 3rd, 2026
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Result {
  4.  
  5.     /**
  6.      * Converts a HH:MM string to total minutes from the start of the day.
  7.      */
  8.     public static int timetoMin(String time) {
  9.         String[] parts = time.split(":");
  10.         return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]);
  11.     }
  12.  
  13.     /**
  14.      * Finds the earliest meeting time given busy events and duration k.
  15.      * Uses a difference array to achieve O(n + 1440) complexity.
  16.      */
  17.     public static String getEarliestMeetTime(List<String> events, int k) {
  18.         // Difference array for 1440 minutes (plus safety buffer for end+1)
  19.         int[] diff = new int[1442];
  20.  
  21.         // 1. Parse events and mark busy periods
  22.         for (String event : events) {
  23.             String[] parts = event.split(" ");
  24.             // The start and end times are the last two words in the string
  25.             int start = timetoMin(parts[parts.length - 2]);
  26.             int end = timetoMin(parts[parts.length - 1]);
  27.            
  28.             diff[start]++;
  29.             diff[end + 1]--;
  30.         }
  31.  
  32.         int busyCount = 0;
  33.         int currentGap = 0;
  34.  
  35.         // 2. Iterate through every minute of the day
  36.         for (int i = 0; i < 1440; i++) {
  37.             busyCount += diff[i];
  38.            
  39.             if (busyCount == 0) {
  40.                 // Minute is free
  41.                 currentGap++;
  42.                 if (currentGap == k) {
  43.                     // We found a gap of size k ending at minute i
  44.                     int startMin = i - k + 1;
  45.                     return String.format("%02d:%02d", startMin / 60, startMin % 60);
  46.                 }
  47.             } else {
  48.                 // Someone is busy, reset gap counter
  49.                 currentGap = 0;
  50.             }
  51.         } // End of loop
  52.  
  53.         // 3. Return -1 if no suitable time exists
  54.         return "-1";
  55.     }
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment