EASY STACK JAVA Solution

interview-questions
Tags: #<Tag:0x00007f2428383eb8>

#1

/**

  • Definition for an interval.

  • public class Interval {

  • int start;
    
  • int end;
    
  • Interval() { start = 0; end = 0; }
    
  • Interval(int s, int e) { start = s; end = e; }
    
  • }
    */
    public class Solution {
    public ArrayList merge(ArrayList a) {
    Collections.sort(a,new Comparator(){
    public int compare(Interval i,Interval d)
    {
    if(i.start==d.start)
    {
    if(i.end>d.end)
    return 1;
    return -1;
    }
    if(i.start>d.start)
    return 1;
    return -1;
    }

     });
     Stack<Interval>s=new Stack<>();
     s.push(new Interval(a.get(0).start,a.get(0).end));
     for(int i=1;i<a.size();i++)
     {
         if(s.peek().end>=a.get(i).start)
         {
             int st=s.peek().start;
             int m=Math.max(s.peek().end,a.get(i).end);
             s.pop();
             s.push(new Interval(st,m));
         }
         else
         {
             s.push(new Interval(a.get(i).start,a.get(i).end));
         }
     }
     ArrayList<Interval>ans=new ArrayList<>();
     while(!s.isEmpty())
     {
         Interval rem=s.peek();
         s.pop();
         ans.add(0,rem);
     }
     return ans;
    

    }
    }