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

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →