Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

A Close Look At Merging Intervals (Main Thread)

General • Asked over 4 years ago by Anonymous

Jake from AlgoDaily Commented on Apr 26, 2020:

This is the main discussion thread generated for A Close Look At Merging Intervals.

Anonymous Commented on Apr 26, 2020:

If no periods can be merged, doesn't this algo drop all but the last one? I think you are missing a second append...

Sandeep Commented on Jun 28, 2021:

> This part is a little hacky. Now the top of the stack can again be overlapping with new_item.

As we are are sorting the intervals before merging, how is it possible that the top of the stack will again be overlapping with the new_item(newly merged item)?

cpp
vector> merge(vector>& intervals) {
        sort(intervals.begin(), end(intervals));

        vector> ret = {intervals[0]};
        for (int i = 1; i < intervals.size(); i++) {
            vector &last = ret[ret.size() - 1];
            const vector &next = intervals[i];
            if (next[0] > last[1]) {
                ret.push_back(next);
                continue;
            }

            last[1] = max(last[1], next[1]);
        }

        return ret;
    }

Something like this seems sufficient with out needing to iterate over a while loop to nestedly compare against the top of the stack.
Please let me know if i am missing something here.