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

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →