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 :
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
Tree: Huffman Decoding
Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t
View Solution →Binary Search Tree : Lowest Common Ancestor
You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b
View Solution →Swap Nodes [Algo]
A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from
View Solution →Kitty's Calculations on a Tree
Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a
View Solution →Is This a Binary Search Tree?
For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a
View Solution →Square-Ten Tree
The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the
View Solution →