Weighted Merge Interval - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional list of integers intervals. 

Each element contains [start, end, weight], meaning that during the inclusive integer interval [start, end] its weight is weight. 

Weight is additive so if we have [[1, 5, 6], [2, 7, 3]], then during [2, 5] we have weight of 9. 

The input intervals may or may not be overlapping.

Return the list of intervals that have the highest weight, sorted in ascending order. 

The returned intervals should be merged, so [[1, 2], [3, 4]] should be merged to [1, 4].

Constraints

0 ≤ n ≤ 100,000 where n is the length of intervals

-2 ** 31 < start ≤ end < 2 ** 31

Example 1

Input

intervals = [

    [1, 3, 1],

    [2, 6, 1],

    [5, 7, 1]

]

Output

[

    [2, 3],

    [5, 6]
]

Explanation

During [[2, 3], [5, 6]] weight is 2 which is the max possible.


Example 2

Input

intervals = [

    [1, 2, 1],

    [3, 4, 1],

    [5, 6, 1]

]

Output

[

    [1, 6]

]

Explanation

All intervals have weight of 1



Solution :



title-img




                        Solution in C++ :

vector<vector<int>> solve(vector<vector<int>>& intervals) {
    map<int, int> mp;
    for (auto& i : intervals) {
        mp[i[0]] += i[2];
        mp[i[1] + 1] -= i[2];
    }
    int sum = 0;
    int mx = 0;
    for (auto& [k, v] : mp) {
        sum += v;
        mx = max(sum, mx);
    }
    sum = 0;
    vector<vector<int>> ans;
    for (auto it = mp.begin(); it != prev(mp.end()); it++) {
        sum += it->second;
        int me = it->first;
        int him = next(it)->first;
        if (sum == mx) {
            ans.push_back({me, him - 1});
        }
    }
    vector<vector<int>> res;
    for (auto& i : ans) {
        if (!res.empty() && res.back()[1] == i[0] - 1) {
            res.back()[1] = i[1];
        } else {
            res.push_back(i);
        }
    }
    return res;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int[][] solve(int[][] n) {
        int N = n.length;
        E[] events = new E[2 * N];
        for (int i = 0; i < N; i++) {
            events[i] = new E(n[i][0], 0, n[i][2]);
            events[i + N] = new E(n[i][1], 1, n[i][2]);
        }
        Arrays.sort(events);

        // find the maximum weight
        int maxw = 0;
        int curw = 0;
        for (E e : events) {
            if (e.type == 0)
                curw += e.w;
            else
                curw -= e.w;
            maxw = Math.max(maxw, curw);
        }

        ArrayList<int[]> ans = new ArrayList<int[]>();
        int w = 0;
        int last = Integer.MIN_VALUE;
        for (E e : events) {
            if (e.type == 0) {
                w += e.w;
            } else {
                if (w == maxw)
                    ans.add(new int[] {last, e.t});
                w -= e.w;
            }
            last = e.t;
        }

        ArrayList<int[]> merged = new ArrayList<int[]>();
        int s = ans.get(0)[0];
        int e = ans.get(0)[1];
        for (int i = 1; i < ans.size(); i++) {
            if (ans.get(i)[0] == e + 1) {
                e = ans.get(i)[1];
            } else {
                merged.add(new int[] {s, e});
                s = ans.get(i)[0];
                e = ans.get(i)[1];
            }
        }
        merged.add(new int[] {s, e});

        return convert(merged);
    }

    public int[][] convert(ArrayList<int[]> arr) {
        int[][] ret = new int[arr.size()][2];
        for (int i = 0; i < arr.size(); i++) ret[i] = arr.get(i);
        return ret;
    }

    static class E implements Comparable<E> {
        int t;
        int type;
        int w;
        public E(int t, int type, int w) {
            this.t = t;
            this.type = type;
            this.w = w;
        }

        public int compareTo(E e) {
            if (t != e.t)
                return t - e.t;
            else
                return type - e.type;
        }
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def merge(self, intervals):
        intervals.sort(key=lambda x: x[0])

        merged = []
        for interval in intervals:
            if not merged or merged[-1][1] < interval[0] - 1:
                merged.append(interval)
            else:
                merged[-1][1] = max(merged[-1][1], interval[1])

        return merged

    def solve(self, intervals):
        events = []
        for start, end, weight in intervals:
            events.append([start, weight, 0])
            events.append([end + 1, -weight, 1])

        events = sorted(events, key=lambda e: (e[0], -e[2]))

        highest = float("-inf")
        total = 0
        for time, weight, event in events:
            total += weight
            highest = max(highest, total)

        res, total = [], 0
        during, left = False, -1

        for time, weight, event in events:
            total += weight
            if total == highest:
                during, left = True, time
            elif during:
                res.append([left, time - 1])
                during = False
        if during:
            res.append([left, events[-1][0] - 1])
        return self.merge(res)
                    


View More Similar Problems

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →