O(n logn) C++ solution showing time limit exceeding


  • 0
    L

    Can someone please throw some light on which it is showing time limit exceeded even though the time complexity if O(N logN) i.e. sorting the intervals first and then merging in O(N).
    Any suggestion or other input is most welcome !

    class Solution {
    public:
        static bool my_sort_func(Interval a,Interval b)
        {
            return (a.start <= b.start);
        }
        
        vector<Interval> merge(vector<Interval>& intervals) {
            
            Interval temp_interval;
            int size=intervals.size(), last_idx=0, initial_start_val=0;
            vector<Interval> result_v;
            
            sort(intervals.begin(),intervals.end(),my_sort_func);
            
            for(int i=0;i<=size-1;i++)
            {
                last_idx = intervals[i].end;
                initial_start_val = intervals[i].start;
                
                for(int j=i+1;j<=size-1;j++)
                {
                    if(last_idx >= intervals[j].start)
                    {
                        if(intervals[j].end > last_idx)
                             last_idx = intervals[j].end;
                        i++;
                    }
                    else
                        break;
                }
                
                temp_interval.start = initial_start_val;
                temp_interval.end = last_idx;
                result_v.push_back(temp_interval);
            }
            
            return result_v;
        }
    };

Log in to reply
 

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