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

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →