Open In App

Reconstructing Segment Tree

Last Updated : 09 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We are given 2*N – 1 integers. We need to check whether it is possible to construct a Range Minimum Query segment tree for an array of N distinct integers from these integers. If so, we must output the segment tree array. N is given to be a power of 2.
An RMQ segment tree is a binary tree where each node is equal to the minimum value of its children. This type of tree is used to efficiently find the minimum value of elements in a given range.
 

Input  : 1 1 1 1 2 2 3 3 3 4 4 5 6 7 8
Output : 1 1 3 1 2 3 4 1 5 2 6 3 7 4 8
The segment tree is shown below



Input  : -381 -460 -381 95 -460 855 -242
          405 -460 982 -381 -460 95 981 855
Output : -460 -460 -381 -460 95 -381 855
         -460 -242 95 405 -381 981 855 982 
By constructing a segment tree from the output,
we can see that it a valid tree for RMQ and the
leaves are all distinct integers.

 

What we first do is iterate through the given integers counting the number of occurrences of each number, then sorting them by value. In C++, we can use the data structure map, which stores elements in sorted order. 
Now we maintain a queue for each possible level of the segment tree. We put the initial root of the tree (array index 0) into the queue for the max level. We then insert the smallest element into the leftmost nodes. We then detach these nodes from the main tree. As we detach a node, we create a new tree of height h – 1, where h is the height of the current node. We can see this in figure 2. We insert the root node of this new tree into the appropriate queue based on its height.
We go through each element, getting a tree of the appropriate height based on the number of occurrences of that element. If at any point such a tree does not exist, then it is not possible to create a segment tree. 
 

CPP




// C++ Program to Create RMQ Segment Tree
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if it is possible to construct
// a range minimum segment tree from given array.
bool createTree(int arr[], int N)
{
    // Store the height of the final tree
    const int height = log2(N) + 1;
 
    // Container to sort and store occurrences of elements
    map<int, int> multi;
 
    // Insert elements into the container
    for (int i = 0; i < 2 * N - 1; ++i)
        ++multi[arr[i]];
 
    // Used to store new subtrees created
    set<int> Q[height];
 
    // Insert root into set
    Q[height - 1].emplace(0);
 
    // Iterate through each unique element in set
    for (map<int, int>::iterator it = multi.begin();
        it != multi.end(); ++it)
    {
        // Number of occurrences is greater than height
        // Or, no subtree exists that can accommodate it
        if (it->second > height || Q[it->second - 1].empty())
            return false;
 
        // Get the appropriate subtree
        int node = *Q[it->second - 1].begin();
 
        // Delete the subtree we grabbed
        Q[it->second - 1].erase(Q[it->second - 1].begin());
 
        int level = 1;
        for (int i = node; i < 2 * N - 1;
            i = 2 * i + 1, ++level)
        {
            // Insert new subtree created into root
            if (2 * i + 2 < 2 * N - 1)
                Q[it->second - level - 1].emplace(2 * i + 2);
 
            // Insert element into array at position
            arr[i] = it->first;
        }
    }
    return true;
}
 
// Driver program
int main()
{
    int N = 8;
    int arr[2 * N - 1] = {1, 1, 1, 1, 2, 2,
                 3, 3, 3, 4, 4, 5, 6, 7, 8};
    if (createTree(arr, N))
    {
        cout << "YES\n";
        for (int i = 0; i < 2 * N - 1; ++i)
            cout << arr[i] << " ";
    }
    else
        cout << "NO\n";
    return 0;
}


Java




import java.util.*;
 
public class RMQSegmentTree {
 
    // Returns true if it is possible to construct
    // a range minimum segment tree from given array.
    public static boolean createTree(int[] arr, int N)
    {
        // Store the height of the final tree
        final int height
            = (int)(Math.log(N) / Math.log(2)) + 1;
 
        // Container to sort and store occurrences of
        // elements
        Map<Integer, Integer> multi = new HashMap<>();
 
        // Insert elements into the container
        for (int i = 0; i < 2 * N - 1; ++i)
            multi.put(arr[i],
                      multi.getOrDefault(arr[i], 0) + 1);
 
        // Used to store new subtrees created
        Set<Integer>[] Q = new HashSet[height];
        for (int i = 0; i < height; i++) {
            Q[i] = new HashSet<Integer>();
        }
 
        // Insert root into set
        Q[height - 1].add(0);
 
        // Iterate through each unique element in set
        for (Map.Entry<Integer, Integer> entry :
             multi.entrySet()) {
            int key = entry.getKey();
            int value = entry.getValue();
 
            // Number of occurrences is greater than height
            // Or, no subtree exists that can accommodate it
            if (value > height || Q[value - 1].isEmpty())
                return false;
 
            // Get the appropriate subtree
            int node = Q[value - 1].iterator().next();
 
            // Delete the subtree we grabbed
            Q[value - 1].remove(node);
 
            int level = 1;
            for (int i = node; i < 2 * N - 1;
                 i = 2 * i + 1, ++level) {
                // Insert new subtree created into root
                if (2 * i + 2 < 2 * N - 1)
                    Q[value - level - 1].add(2 * i + 2);
 
                // Insert element into array at position
                arr[i] = key;
            }
        }
        return true;
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int N = 8;
        int[] arr = { 1, 1, 1, 1, 2, 2, 3, 3,
                      3, 4, 4, 5, 6, 7, 8 };
 
        if (createTree(arr, N)) {
            System.out.println("YES");
            for (int i = 0; i < 2 * N - 1; ++i)
                System.out.print(arr[i] + " ");
        }
        else {
            System.out.println("NO");
        }
    }
}


Python3




# Python Program to Create RMQ Segment Tree
from typing import List
from math import log2
 
# Returns true if it is possible to construct
# a range minimum segment tree from given array.
def createTree(arr: List[int], N: int) -> bool:
 
    # Store the height of the final tree
    height = int(log2(N)) + 1
 
    # Container to sort and store occurrences of elements
    multi = {}
 
    # Insert elements into the container
    for i in range(2 * N - 1):
        if arr[i] not in multi:
            multi[arr[i]] = 0
        multi[arr[i]] += 1
 
    # Used to store new subtrees created
    Q = [set() for _ in range(height)]
 
    # Insert root into set
    Q[height - 1].add(0)
 
    # Iterate through each unique element in set
    for k, v in multi.items():
 
        # Number of occurrences is greater than height
        # Or, no subtree exists that can accommodate it
        if (v > height or len(Q[v - 1]) == 0):
            return False
 
        # Get the appropriate subtree
        node = sorted(Q[v - 1])[0]
 
        # Delete the subtree we grabbed
        Q[v - 1].remove(sorted(Q[v - 1])[0])
        level = 1
         
        # for (int i = node; i < 2 * N - 1;
        #     i = 2 * i + 1, ++level)
        i = node
        while i < 2 * N - 1:
 
            # Insert new subtree created into root
            if (2 * i + 2 < 2 * N - 1):
                Q[v - level - 1].add(2 * i + 2)
 
            # Insert element into array at position
            arr[i] = k
            level += 1
            i = 2 * i + 1
    return True
 
 
# Driver program
if __name__ == "__main__":
 
    N = 8
    arr = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 6, 7, 8]
    if (createTree(arr, N)):
 
        print("YES")
        # for (int i = 0; i < 2 * N - 1; ++i)
        for i in range(2 * N - 1):
            print(arr[i], end=" ")
 
    else:
        print("No")
 
# This code is contributed by sanjeev2552


C#




// C# Program to Create RMQ Segment Tree
using System;
using System.Collections.Generic;
 
public class RMQSegmentTree {
     
    // Returns true if it is possible to construct
    // a range minimum segment tree from given array.
    static bool CreateTree(int[] arr, int N)
    {
        // Store the height of the final tree
        int height = (int)(Math.Log(N) / Math.Log(2)) + 1;
 
        // Container to sort and store occurrences of
        // elements
        Dictionary<int, int> multi
            = new Dictionary<int, int>();
 
        // Insert elements into the container
        for (int i = 0; i < 2 * N - 1; ++i)
            if (multi.ContainsKey(arr[i]))
                multi[arr[i]]++;
            else
                multi[arr[i]] = 1;
 
        // Used to store new subtrees created
        SortedSet<int>[] Q = new SortedSet<int>[ height ];
 
        // Initialize each set in the array
        for (int i = 0; i < height; i++)
            Q[i] = new SortedSet<int>();
 
        // Insert root into set
        Q[height - 1].Add(0);
 
        // Iterate through each unique element in set
        foreach(KeyValuePair<int, int> entry in multi)
        {
            int count = entry.Value;
            int key = entry.Key;
 
            // Number of occurrences is greater than height
            // Or, no subtree exists that can accommodate it
            if (count > height || Q[count - 1].Count == 0)
                return false;
 
            // Get the appropriate subtree
            int node = Q[count - 1].Min;
 
            // Delete the subtree we grabbed
            Q[count - 1].Remove(node);
 
            int level = 1;
            for (int i = node; i < 2 * N - 1;
                 i = 2 * i + 1, ++level) {
                      
                // Insert new subtree created into root
                if (2 * i + 2 < 2 * N - 1)
                    Q[count - level - 1].Add(2 * i + 2);
 
                // Insert element into array at position
                arr[i] = key;
            }
        }
        return true;
    }
 
    // Driver program
    static public void Main()
    {
        int N = 8;
        int[] arr = { 1, 1, 1, 1, 2, 2, 3, 3,
                      3, 4, 4, 5, 6, 7, 8 };
 
        if (CreateTree(arr, N)) {
            Console.WriteLine("YES");
            for (int i = 0; i < 2 * N - 1; ++i)
                Console.Write(arr[i] + " ");
        }
        else
            Console.WriteLine("NO");
 
        Console.ReadLine();
    }
}
// This code is contributed by prasad264


Javascript




// JavaScript Program to Create RMQ Segment Tree
 
// Returns true if it is possible to construct
// a range minimum segment tree from given array.
function createTree(arr, N) {
 
// Store the height of the final tree
const height = Math.floor(Math.log2(N)) + 1;
 
// Container to sort and store occurrences of elements
const multi = {};
 
// Insert elements into the container
for (let i = 0; i < 2 * N - 1; i++) {
if (multi[arr[i]] == undefined) {
multi[arr[i]] = 0;
}
multi[arr[i]] += 1;
}
 
// Used to store new subtrees created
const Q = new Array(height);
for (let i = 0; i < height; i++) {
Q[i] = new Set();
}
 
// Insert root into set
Q[height - 1].add(0);
 
// Iterate through each unique element in set
for (const [k, v] of Object.entries(multi)) {// Number of occurrences is greater than height
// Or, no subtree exists that can accommodate it
if (v > height || Q[v - 1].size == 0) {
  return false;
}
 
// Get the appropriate subtree
const node = Math.min(...Q[v - 1]);
 
// Delete the subtree we grabbed
Q[v - 1].delete(node);
let level = 1;
let i = node;
 
while (i < 2 * N - 1) {
 
  // Insert new subtree created into root
  if (2 * i + 2 < 2 * N - 1) {
    Q[v - level - 1].add(2 * i + 2);
  }
 
  // Insert element into array at position
  arr[i] = k;
  level += 1;
  i = 2 * i + 1;
}
}
return true;
}
 
// Driver program
const N = 8;
const arr = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 6, 7, 8];
if (createTree(arr, N)) {
console.log("YES");
let ans="";
for (let i = 0; i < 2 * N - 1; i++) {
ans = ans + arr[i] + " ";
}
console.log(ans);
} else {
console.log("No");
}


Output: 
 

YES
1 1 3 1 2 3 4 1 5 2 6 3 7 4 8 

Main time complexity is caused by sorting elements. 
Time Complexity: O(N log N) 
Space Complexity: O(N)

Related Topic: Segment Tree

 



Similar Reads

Reconstructing the Array with Maximum Possible Sum by Given Operations
Consider an array A[] of length N. Suppose, you can create obtain B[] from A[] using below steps: Iterate N/2 times on A and follow below the step below:Insert (Ai + Ai+(N/2)) and |Ai - Ai+(N/2)| into B[]After that rearrange B[] in any random order.You are given B[], the task is to reconstructing any A[] if exists such that B[] can be obtained usin
13 min read
Find middle point segment from given segment lengths
Given an array arr[] of size M. The array represents segment lengths of different sizes. These segments divide a line beginning with 0. The value of arr[0] represents a segment from 0 arr[0], value of arr[1] represents segment from arr[0] to arr[1], and so on. The task is to find the segment which contains the middle point, If the middle segment do
6 min read
Build a segment tree for N-ary rooted tree
Prerequisite: Segment tree and depth first search.In this article, an approach to convert an N-ary rooted tree( a tree with more than 2 children) into a segment tree is discussed which is used to perform a range update queries. Why do we need a segment tree when we already have an n-ary rooted tree? Many times, a situation occurs where the same ope
15+ min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
Comparison between Fenwick Tree vs Segment Tree - with Similarities and Differences
Fenwick Tree (Binary Indexed Tree) and Segment Tree are both data structures used for efficient range query and update operations on an array. Here's a tabular comparison of these two data structures. Similarities between the Fenwick tree and Segment treeHere are some of the areas where Fenwick Tree is similar to Segment Tree: Array type: Both Fenw
2 min read
Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Introduction:Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.Trie: A trie, also known as a prefix tree, is a tree-like data structure that stores a collection of strings. It is used for ef
10 min read
Segment Tree | (XOR of a given range )
Let us consider the following problem to understand Segment Trees.We have an array arr[0 . . . n-1]. We should be able to 1 Find the xor of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1.2 Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1.Similar to Sum of Given Range
15+ min read
Levelwise Alternating OR and XOR operations in Segment Tree
A Levelwise OR/XOR alternating segment tree is a segment tree, such that at every level the operations OR and XOR alternate. In other words at Level 1 the left and right sub-trees combine together by the OR operation i.e Parent node = Left Child OR Right Child and on Level 2 the left and right sub-trees combine together by the XOR operation i.e Par
15+ min read
Euler Tour | Subtree Sum using Segment Tree
Euler tour tree (ETT) is a method for representing a rooted tree as a number sequence. When traversing the tree using Depth for search(DFS), insert each node in a vector twice, once while entered it and next after visiting all its children. This method is very useful for solving subtree problems and one such problem is Subtree Sum. Prerequisite : S
15+ min read
Segment Tree | Set 2 (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1. Also, change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1 and then find the maximum element of given range with updated values.Example : Input : {1, 3, 5, 7, 9, 11}
15+ min read
Article Tags :
Practice Tags :