Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 28, 2018 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/ef28dd969c23e9e641496ab1e0f08f78 to your computer and use it in GitHub Desktop.
Save jianminchen/ef28dd969c23e9e641496ab1e0f08f78 to your computer and use it in GitHub Desktop.
Meeting planner - being an interviewer - give some code review
import java.io.*;
import java.util.*;
https://www.linkedin.com/in/jianminchen
class Solution {
/**
1. find the overlapped intervals between the 2 persons.
2. if the overlapped interval is bigger than 'dur', then return it.
I would use 2 pointers.
ia - index of current slot of A
ib - index of current slot of B
how to check overlap?
!(A.end < B.start || A.start > B.end)
overlapped interval.
start : math.max(A.start, B.start);
end : math.min(A.end, B.end);
if (overlaps) {
if the overlapped interval is bigger than 'dur'
return the interval of 'dur'
else //whose end is smaller, then increase it.
} else if (slotsA[ia].start > slotsB[ib].end) {
ib++;
} else {
ia++;
}
------------------
-----------
corner case :
1. slotsA[ia].end < slotsB[ib].start A: [0,15] [25, 40] B: [20, 30]
*/
static int[] meetingPlanner(int[][] slotsA, int[][] slotsB, int dur) {
// your code goes here
int ia = 0; // indexA
int ib = 0; // indexB
while(ia < slotsA.length && ib < slotsB.length) {
if(overlap(slotsA[ia], slotsB[ib])) {
// get the overlapped interval
int[] joint = new int[2];
int[] intervalA = slotsA[ia];
int[] intervalB = slotsB[ib];
joint[0] = Math.max(slotsA[ia][0], slotsB[ib][0]);
joint[1] = Math.min(slotsA[ia][1], slotsB[ib][1]);
if(joint[1] - joint[0] >= dur) {
joint[1] = joint[0] + dur;
return joint;
}
}
if(slotsA[ia][1] >= slotsB[ib][1]) {
ib++;
} else {
ia++;
}
/*
else if(slotsA[ia][0] > slotsB[ib][1]) {
ib++;
} else {
ia++;
}
*/
}
return new int[0];
}
private static boolean overlap(int[] i1, int[] i2) {
return !(i1[1] < i2[0] || i1[0] > i2[1]);
}
public static void main(String[] args) {
int[][] slotsA = {{10, 50}, {60, 120}, {140, 210}};
int[][] slotsB = {{0,15}, {60,70}};
int[] sol = Solution.meetingPlanner(slotsA, slotsB, 12);
if(sol != null) {
for(int i : sol) {
System.out.println(i);
}
}
}
}
/*
Julia's feedback:
The art of readable code
pluralsight.com - clean code: write code for humans
Make code more readable, line 45 and line 46
simplify the code:
Make the logic more simplified;
remove the code from line 69 to 75
move line 64 and 68 out from if loop line 49: if(overlap(slotsA[ia], slotsB[ib]))
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment