Intuitive and understandable Java solution (8 ms)

  • 0
     public class Solution {
        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
                Collections.sort(intervals,new custom());
                List<Interval> ans = new LinkedList();
                for(int i=0;i<intervals.size();i++){
                        int l = intervals.get(i).start;
                        int r = intervals.get(i).end;
                        while(i<intervals.size()-1 && intersect(l,r,intervals.get(i+1).start,intervals.get(i+1).end)){
                            l = Math.min(l,intervals.get(i+1).start);
                            r = Math.max(r,intervals.get(i+1).end);
                        ans.add(new Interval(l,r));
                return ans;
        private boolean intersect(int a, int b, int c, int d){
            return b-c<0 ^ a-d<0;
    class custom implements Comparator<Interval>{
        public int compare(Interval i1, Interval i2){
            return i1.start - i2.start;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.