Skip to content

Instantly share code, notes, and snippets.

@tawrahim
Created January 11, 2018 21:17
Show Gist options
  • Save tawrahim/ed2cd0970f255a07ecddf274c7bdbe04 to your computer and use it in GitHub Desktop.
Save tawrahim/ed2cd0970f255a07ecddf274c7bdbe04 to your computer and use it in GitHub Desktop.
Uber interview question
public class Interview {
class Interval {
int start;
int end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
}
public static void main(String[] args) {
Interval i1 = new Interval(1,2);
Interval i2 = new Interval(2,4);
Interval i3 = new Interval(3,8);
Interval i4 = new Interval(4,12);
List<Interval> intervals = new ArrayList<>();
intervals.add(i1);
intervals.add(i2);
intervals.add(i3);
intervals.add(i4);
intervals.add(i5);
merge(intervals);
}
public static List<Interval> merge(List<Interval> intervals) {
// Sort the intervals
Collections.sort(intervals,new IntervalComaparator());
List<Interval> result = new List<>();
Stack<Interval> stack = new Stack<>();
stack.push(intervals.get(0));
for (int i = 1; i < intervals.size(); i++) {
Interval currentTime = intervals.get(i);
Interval onStack = stack.pop();
if (isInInterval(onStack, currentTime)) {
result.add(new Interval(onStack.start, Math.max(onStack.end, currentTime.end)));
stack.push(intervals.get(i));
i++;
} else {
stack.push(currentTime);
result.add(onStack);
}
}
return result;
}
public static boolean isInInterval(Interval i, Interval j) {
if (i.end >= j.start) return true;
return false;
}
class IntervalComaparator implements Comparator<Interval>{
public int compare(Interval i1,Interval i2){
if (i1.start == s2.start) return 0;
if (i1.start > i2.start) return 1;
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment