|
| 1 | +package solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +// [Problem] https://leetcode.com/problems/meeting-scheduler |
| 8 | +class MeetingScheduler { |
| 9 | + // Two pointers with sorting |
| 10 | + // O(mlogm + nlogn) time, O(1) space |
| 11 | + // where m = slots1.length, n = slots2.length |
| 12 | + public List<Integer> minAvailableDuration(int[][] slots1, int[][] slots2, int duration) { |
| 13 | + Arrays.sort(slots1, (a, b) -> a[0] - b[0]); // O(mlogm) time |
| 14 | + Arrays.sort(slots2, (a, b) -> a[0] - b[0]); // O(nlogn) time |
| 15 | + int i = 0, j = 0; |
| 16 | + while (i < slots1.length && j < slots2.length) { |
| 17 | + int[] slot1 = slots1[i], slot2 = slots2[j]; |
| 18 | + int start = Math.max(slot1[0], slot2[0]); |
| 19 | + int end = Math.min(slot1[1], slot2[1]); |
| 20 | + if (end - start >= duration) { |
| 21 | + return List.of(start, start + duration); |
| 22 | + } |
| 23 | + if (slot1[1] < slot2[1]) { |
| 24 | + i++; |
| 25 | + } else { |
| 26 | + j++; |
| 27 | + } |
| 28 | + } |
| 29 | + return new ArrayList<>(); |
| 30 | + } |
| 31 | + |
| 32 | + // Test |
| 33 | + public static void main(String[] args) { |
| 34 | + MeetingScheduler solution = new MeetingScheduler(); |
| 35 | + |
| 36 | + int[][] slots1 = {{10, 50}, {60, 120}, {140, 210}}; |
| 37 | + int[][] slots2 = {{0, 15}, {60, 70}}; |
| 38 | + int duration = 8; |
| 39 | + List<Integer> expectedOutput = List.of(60, 68); |
| 40 | + List<Integer> actualOutput = solution.minAvailableDuration(slots1, slots2, duration); |
| 41 | + |
| 42 | + System.out.println("Test passed? " + expectedOutput.equals(actualOutput)); |
| 43 | + } |
| 44 | +} |
0 commit comments