The Wayback Machine - https://web.archive.org/web/20241129134638/https://www.geeksforgeeks.org/check-two-bsts-contain-set-elements/
Open In App

Check if two BSTs contain same set of elements

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two Binary Search Trees consisting of unique positive elements, the task is to check whether the two BSTs contain the same set of elements or not. The structure of the two given BSTs can be different. 

Example:

Input:

check-if-two-bsts-contain-same-set-of-elements


Output: True
Explanation: The above two BSTs contains same set of elements {5, 10, 12, 15, 20, 25}

The simple idea is to traverse the first tree. For each node, check if a node exists with the same value in the second tree. If it exists, then set the node value of the second tree to -1 (to mark the node as visited) and recursively check for the left and right subtree. Otherwise, return false. Finally, check if all the nodes of the second tree have a value of -1.

Time Complexity: O( n * n ), where n is the number of nodes in the BST. 
Auxiliary Space: O( h1 + h2 ), where h1 and h2 are the heights of the two trees.

[Expected Approach – 1] Using Recursion and hash set – O(n) Time and O(n) Space

The idea is to store the node values of the first BST in a hashSet. Then, traverse the second BST and check for every node if its value exists in the hashSet. If it exists, then remove the value from the hash set and recursively check for left and right subtree. Otherwise, return false. Finally check if the hash set is empty or not.

Below is the implementation of the above approach: 

C++
// C++ program to check if two 
// BSTs contain same set of elements
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to append nodes of BST1 into set.
void appendNodes(Node* root, unordered_set<int> &s) {
    if (root == nullptr) return;
    
    s.insert(root->data);
    appendNodes(root->left, s);
    appendNodes(root->right, s);
}

// Recursive function to check if each
// node of BST2 exists in BST1 or not.
bool checkNodes(Node* root, unordered_set<int> &s) {
    if (root == nullptr) return true;
    
    // If current node does not exist in 
    // set, then return false.
    if (s.find(root->data) == s.end()) 
        return false;
    
    // Remove the value from the set     
    s.erase(root->data);
    
    // Recursively check the left and 
    // right subtrees.
    return 
    checkNodes(root->left, s)
    &&
    checkNodes(root->right, s);
}

// Main function to compare two BST.
bool checkBSTs(Node* root1, Node* root2) {
    
    // append node values into set.
    unordered_set<int> s;
    appendNodes(root1, s);
    
    // Check nodes of BST2
    bool ans = checkNodes(root2, s);
    
    // If BST2 does not contain all values
    // of BST1
    if (ans == false) 
        return false;
    
    // If BST2 still contains any value, 
    // then return false. Otherwise return 
    // true.
    return s.empty() == true;
}

int main() {
    
    // Tree 1
    //         15
    //        /  \
    //      10    20
    //     /  \     \
    //    5   12     25
    Node* root1 = new Node(15);
    root1->left = new Node(10);
    root1->right = new Node(20);
    root1->left->left = new Node(5);
    root1->left->right = new Node(12);
    root1->right->right = new Node(25);
    
    // Tree 2
    //         15
    //        /  \
    //      12    20
    //     /       \
    //    5         25
    //     \
    //     10
    Node* root2 = new Node(15);
    root2->left = new Node(12);
    root2->right = new Node(20);
    root2->left->left = new Node(5);
    root2->left->left->right = new Node(10);
    root2->right->right = new Node(25);
    
    if (checkBSTs(root1, root2)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    
    return 0;
}
Java
// Java program to check if two 
// BSTs contain same set of elements
import java.util.HashSet;

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to append nodes of BST1 into set.
    static void appendNodes(Node root, HashSet<Integer> s) {
        if (root == null) return;

        s.add(root.data);
        appendNodes(root.left, s);
        appendNodes(root.right, s);
    }

    // Recursive function to check if each
    // node of BST2 exists in BST1 or not.
    static boolean checkNodes(Node root, HashSet<Integer> s) {
        if (root == null) return true;

        // If current node does not exist in 
        // set, then return false.
        if (!s.contains(root.data)) 
            return false;

        // Remove the value from the set
        s.remove(root.data);

        // Recursively check the left and 
        // right subtrees.
        return checkNodes(root.left, s) && checkNodes(root.right, s);
    }

    // Main function to compare two BST.
    static boolean checkBSTs(Node root1, Node root2) {
        
        // Append node values into set.
        HashSet<Integer> s = new HashSet<>();
        appendNodes(root1, s);

        // Check nodes of BST2
        boolean ans = checkNodes(root2, s);

        // If BST2 does not contain all values
        // of BST1
        if (!ans)
            return false;

        // If BST2 still contains any value, 
        // then return false. Otherwise return 
        // true.
        return s.isEmpty();
    }

    public static void main(String[] args) {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check if two 
# BSTs contain same set of elements

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to append nodes of BST1 into set.
def appendNodes(root, s):
    if root is None:
        return
    
    s.add(root.data)
    appendNodes(root.left, s)
    appendNodes(root.right, s)

# Recursive function to check if each
# node of BST2 exists in BST1 or not.
def checkNodes(root, s):
    if root is None:
        return True

    # If current node does not exist in 
    # set, then return false.
    if root.data not in s:
        return False
    
    # Remove the value from the set     
    s.remove(root.data)
    
    # Recursively check the left and 
    # right subtrees.
    return checkNodes(root.left, s) and \
      checkNodes(root.right, s)

def checkBSTs(root1, root2):
    
    # Append node values into set.
    s = set()
    appendNodes(root1, s)
    
    # Check nodes of BST2
    ans = checkNodes(root2, s)
    
    # If BST2 does not contain all values
    # of BST1
    if not ans:
        return False
    
    # If BST2 still contains any value, 
    # then return false. Otherwise return 
    # true.
    return len(s) == 0

if __name__ == "__main__":
    
    # Tree 1
    #         15
    #        /  \
    #      10    20
    #     /  \     \
    #    5   12     25
    root1 = Node(15)
    root1.left = Node(10)
    root1.right = Node(20)
    root1.left.left = Node(5)
    root1.left.right = Node(12)
    root1.right.right = Node(25)
    
    # Tree 2
    #         15
    #        /  \
    #      12    20
    #     /       \
    #    5         25
    #     \
    #     10
    root2 = Node(15)
    root2.left = Node(12)
    root2.right = Node(20)
    root2.left.left = Node(5)
    root2.left.left.right = Node(10)
    root2.right.right = Node(25)
    
    if checkBSTs(root1, root2):
        print("True")
    else:
        print("False")
C#
// C# program to check if two 
// BSTs contain same set of elements
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // Function to append nodes of BST1 into set.
    static void appendNodes(Node root, HashSet<int> s) {
        if (root == null) return;

        s.Add(root.data);
        appendNodes(root.left, s);
        appendNodes(root.right, s);
    }

    // Recursive function to check if each
    // node of BST2 exists in BST1 or not.
    static bool checkNodes(Node root, HashSet<int> s) {
        if (root == null) return true;

        // If current node does not exist in 
        // set, then return false.
        if (!s.Contains(root.data)) 
            return false;

        // Remove the value from the set
        s.Remove(root.data);

        // Recursively check the left and 
        // right subtrees.
        return checkNodes(root.left, s) 
                  && checkNodes(root.right, s);
    }

    // Main function to compare two BST.
    static bool checkBSTs(Node root1, Node root2) {
      
        // Append node values into set.
        HashSet<int> s = new HashSet<int>();
        appendNodes(root1, s);

        // Check nodes of BST2
        bool ans = checkNodes(root2, s);

        // If BST2 does not contain all values
        // of BST1
        if (!ans)
            return false;

        // If BST2 still contains any value, 
        // then return false. Otherwise return 
        // true.
        return s.Count == 0;
    }

    static void Main(string[] args) {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check if two 
// BSTs contain same set of elements

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to append nodes of BST1 into set.
function appendNodes(root, s) {
    if (root === null) return;

    s.add(root.data);
    appendNodes(root.left, s);
    appendNodes(root.right, s);
}

// Recursive function to check if each
// node of BST2 exists in BST1 or not.
function checkNodes(root, s) {
    if (root === null) return true;

    // If current node does not exist in 
    // set, then return false.
    if (!s.has(root.data)) 
        return false;

    // Remove the value from the set     
    s.delete(root.data);

    // Recursively check the left and 
    // right subtrees.
    return checkNodes(root.left, s) 
            && checkNodes(root.right, s);
}

// Main function to compare two BST.
function checkBSTs(root1, root2) {
    
    // Append node values into set.
    let s = new Set();
    appendNodes(root1, s);

    // Check nodes of BST2
    let ans = checkNodes(root2, s);

    // If BST2 does not contain all values
    // of BST1
    if (!ans)
        return false;

    // If BST2 still contains any value, 
    // then return false. Otherwise return 
    // true.
    return s.size === 0;
}

// Tree 1
//         15
//        /  \
//      10    20
//     /  \     \
//    5   12     25
let root1 = new Node(15);
root1.left = new Node(10);
root1.right = new Node(20);
root1.left.left = new Node(5);
root1.left.right = new Node(12);
root1.right.right = new Node(25);

// Tree 2
//         15
//        /  \
//      12    20
//     /       \
//    5         25
//     \
//     10
let root2 = new Node(15);
root2.left = new Node(12);
root2.right = new Node(20);
root2.left.left = new Node(5);
root2.left.left.right = new Node(10);
root2.right.right = new Node(25);

if (checkBSTs(root1, root2)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

Note: If BST’s does not contain distinct elements, then this approach can be implemented using hashmap instead of hash set.

[Expected Approach – 2] Using In-Order Traversal and Array – O(n) Time and O(n) Space

The idea is to use the property of BST that in-order traversal of a BST generates a sorted array. So, traverse the trees and generate two arrays. If the two arrays are same, then the BST’s have same set of elements, so return true. Otherwise return false.

Below is the implementation of the above approach: 

C++
// C++ program to check if two 
// BSTs contain same set of elements
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left, *right;
    Node (int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// In-order function to append 
// nodes of BST into array
void appendNodes(Node* root, vector<int> &arr) {
    if (root == nullptr) return;
    
    appendNodes(root->left, arr);
    arr.push_back(root->data);
    appendNodes(root->right, arr);
}

// Main function to compare two BST.
bool checkBSTs(Node* root1, Node* root2) {
    
    vector<int> arr1, arr2;
    appendNodes(root1, arr1);
    appendNodes(root2, arr2);
    
    // If size of two arrays is not 
    // same, return false.
    if (arr1.size() != arr2.size())
        return false;
        
    for (int i=0; i<arr1.size(); i++) {
        
        // If elements do not match,
        // return false.
        if (arr1[i] != arr2[i]) 
            return false;
    }
    
    return true;
}

int main() {
    
    // Tree 1
    //         15
    //        /  \
    //      10    20
    //     /  \     \
    //    5   12     25
    Node* root1 = new Node(15);
    root1->left = new Node(10);
    root1->right = new Node(20);
    root1->left->left = new Node(5);
    root1->left->right = new Node(12);
    root1->right->right = new Node(25);
    
    // Tree 2
    //         15
    //        /  \
    //      12    20
    //     /       \
    //    5         25
    //     \
    //     10
    Node* root2 = new Node(15);
    root2->left = new Node(12);
    root2->right = new Node(20);
    root2->left->left = new Node(5);
    root2->left->left->right = new Node(10);
    root2->right->right = new Node(25);
    
    if (checkBSTs(root1, root2)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    
    return 0;
}
Java
// Java program to check if two 
// BSTs contain same set of elements
import java.util.ArrayList;

class Node {
    int data;
    Node left, right;
    
    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // In-order function to append 
    // nodes of BST into array
    static void appendNodes(Node root, 
                            ArrayList<Integer> arr) {
        if (root == null) return;
        
        appendNodes(root.left, arr);
        arr.add(root.data);
        appendNodes(root.right, arr);
    }

    // Main function to compare two BST.
    static boolean checkBSTs(Node root1, Node root2) {
        ArrayList<Integer> arr1 = new ArrayList<>();
        ArrayList<Integer> arr2 = new ArrayList<>();
        appendNodes(root1, arr1);
        appendNodes(root2, arr2);

        // If size of two arrays is not 
        // same, return false.
        if (arr1.size() != arr2.size()) return false;
        
        for (int i = 0; i < arr1.size(); i++) {

            // If elements do not match,
            // return false.
            if (!arr1.get(i).equals(arr2.get(i))) 
                return false;
        }
        return true;
    }

    public static void main(String[] args) {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            System.out.println("True");
        } else {
            System.out.println("False");
        }
    }
}
Python
# Python program to check if two 
# BSTs contain same set of elements

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# In-order function to append 
# nodes of BST into array
def appendNodes(root, arr):
    if root is None:
        return
    
    appendNodes(root.left, arr)
    arr.append(root.data)
    appendNodes(root.right, arr)

# Main function to compare two BST.
def checkBSTs(root1, root2):
    arr1, arr2 = [], []
    appendNodes(root1, arr1)
    appendNodes(root2, arr2)
    
    # If size of two arrays is not 
    # same, return false.
    if len(arr1) != len(arr2):
        return False
    
    for i in range(len(arr1)):
      
        # If elements do not match,
        # return false.
        if arr1[i] != arr2[i]:
            return False
    
    return True

if __name__ == "__main__":
    
    # Tree 1
    #         15
    #        /  \
    #      10    20
    #     /  \     \
    #    5   12     25
    root1 = Node(15)
    root1.left = Node(10)
    root1.right = Node(20)
    root1.left.left = Node(5)
    root1.left.right = Node(12)
    root1.right.right = Node(25)
    
    # Tree 2
    #         15
    #        /  \
    #      12    20
    #     /       \
    #    5         25
    #     \
    #     10
    root2 = Node(15)
    root2.left = Node(12)
    root2.right = Node(20)
    root2.left.left = Node(5)
    root2.left.left.right = Node(10)
    root2.right.right = Node(25)
    
    if checkBSTs(root1, root2):
        print("True")
    else:
        print("False")
C#
// C# program to check if two 
// BSTs contain same set of elements
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {

    // In-order function to append 
    // nodes of BST into array
    static void appendNodes(Node root, List<int> arr) {
        if (root == null) return;
        
        appendNodes(root.left, arr);
        arr.Add(root.data);
        appendNodes(root.right, arr);
    }

    // Main function to compare two BST.
    static bool checkBSTs(Node root1, Node root2) {
        List<int> arr1 = new List<int>();
        List<int> arr2 = new List<int>();
        appendNodes(root1, arr1);
        appendNodes(root2, arr2);

        // If size of two arrays is not 
        // same, return false.
        if (arr1.Count != arr2.Count) return false;
        
        for (int i = 0; i < arr1.Count; i++) {
            
            // If elements do not match,
            // return false.
            if (arr1[i] != arr2[i]) 
                return false;
        }
        return true;
    }

    static void Main() {

        // Tree 1
        //         15
        //        /  \
        //      10    20
        //     /  \     \
        //    5   12     25
        Node root1 = new Node(15);
        root1.left = new Node(10);
        root1.right = new Node(20);
        root1.left.left = new Node(5);
        root1.left.right = new Node(12);
        root1.right.right = new Node(25);

        // Tree 2
        //         15
        //        /  \
        //      12    20
        //     /       \
        //    5         25
        //     \
        //     10
        Node root2 = new Node(15);
        root2.left = new Node(12);
        root2.right = new Node(20);
        root2.left.left = new Node(5);
        root2.left.left.right = new Node(10);
        root2.right.right = new Node(25);

        if (checkBSTs(root1, root2)) {
            Console.WriteLine("True");
        } else {
            Console.WriteLine("False");
        }
    }
}
JavaScript
// JavaScript program to check if two 
// BSTs contain same set of elements

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// In-order function to append 
// nodes of BST into array
function appendNodes(root, arr) {
    if (root === null) return;
    
    appendNodes(root.left, arr);
    arr.push(root.data);
    appendNodes(root.right, arr);
}

// Main function to compare two BST.
function checkBSTs(root1, root2) {
    let arr1 = [], arr2 = [];
    appendNodes(root1, arr1);
    appendNodes(root2, arr2);

    // If size of two arrays is not 
    // same, return false.
    if (arr1.length !== arr2.length) return false;
    
    for (let i = 0; i < arr1.length; i++) {
        
        // If elements do not match,
        // return false.
        if (arr1[i] !== arr2[i]) 
            return false;
    }
    return true;
}

// Tree 1
//         15
//        /  \
//      10    20
//     /  \     \
//    5   12     25
let root1 = new Node(15);
root1.left = new Node(10);
root1.right = new Node(20);
root1.left.left = new Node(5);
root1.left.right = new Node(12);
root1.right.right = new Node(25);

// Tree 2
//         15
//        /  \
//      12    20
//     /       \
//    5         25
//     \
//     10
let root2 = new Node(15);
root2.left = new Node(12);
root2.right = new Node(20);
root2.left.left = new Node(5);
root2.left.left.right = new Node(10);
root2.right.right = new Node(25);

if (checkBSTs(root1, root2)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True


Previous Article
Next Article

Similar Reads

Check if two given key sequences construct same BSTs
Given two arrays which represent two sequences of keys that are used to create BSTs. Imagine we make a Binary Search Tree (BST) from each array. We need to tell whether two BSTs will be identical or not without actually constructing the tree. Examples: Let the input arrays be a[] and b[] Example 1: a[] = {2, 4, 1, 3} will construct following tree.
6 min read
Check whether two strings contain same characters in same order
Given two strings s1 and s2, the task is to find whether the two strings contain the same characters that occur in the same order. For example string "Geeks" and string "Geks" contain the same characters in same order. Examples: Input: s1 = "Geeks", s2 = "Geks" Output: Yes Input: s1 = "Arnab", s2 = "Andrew" Output: No Approach: We have two strings
9 min read
Find a Symmetric matrix of order N that contain integers from 0 to N-1 and main diagonal should contain only 0's
Given an integer N. The task is to generate a symmetric matrix of order N*N having the following properties. Main diagonal should contain only 0'sThe matrix should contain elements from 0 to N-1 only. Examples: Input: N = 4 Output: 0 2 3 1 2 0 1 3 3 1 0 2 1 3 2 0Input: N = 5 Output: 0 2 3 4 1 2 0 4 1 3 3 4 0 2 1 4 1 2 0 3 1 3 1 3 0 Approach: Since
10 min read
Split a BST into two balanced BSTs based on a value K
Given a Binary Search tree and an integer K, we have to split the tree into two Balanced Binary Search Tree, where BST-1 consists of all the nodes which are less than K and BST-2 consists of all the nodes which are greater than or equal to K.Note: The arrangement of the nodes may be anything but both BST should be Balanced. Examples: Input: 40 / \
15+ min read
Generate two BSTs from the given array such that maximum height among them is minimum
Given an array of n integers where n is greater than 1, the task is to make two Binary Search Tree from the given array (in any order) such that the maximum height among the two trees is minimum possible and print the maximum height.Examples: Input: arr[] = {1, 2, 3, 4, 6} Output: 1 Input: arr[] = { 74, 25, 23, 1, 65, 2, 8, 99 } Output: 2 Approach:
4 min read
Nodes from given two BSTs with sum equal to X
Given two Binary search trees and an integer X, the task is to find a pair of nodes, one belonging to the first BST and the second belonging to other such that their sum is equal to X. If there exists such a pair, print Yes else print No. Examples: Input: X = 100 BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 11 \ 13 Output: No There is no such pair with
9 min read
Print all pairs from two BSTs whose sum is greater than the given value
Given two Binary Search Tree (BSTs) and a value X, the problem is to print all pairs from both the BSTs whose sum is greater than the given value X.\ Examples: Input: BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18X = 20Output: The pairs are: (3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)Naive Approach
15+ min read
Merge two BSTs with limited extra space
Given two Binary Search Trees(BST), print the inorder traversal of merged BSTs. Examples: Input: First BST 3 / \ 1 5Second BST 4 / \2 6Output: 1 2 3 4 5 6 Input:First BST 8 / \ 2 10 / 1Second BST 5 / 3 /0Output: 0 1 2 3 5 8 10 Recommended PracticeMerge two BST 'sTry It!Merge two BSTs using Iterative Inorder Traversal: The idea is to use iterative i
15+ min read
Count pairs from two BSTs whose sum is equal to a given value x
Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The task is to count all pairs from both the BSTs whose sum is equal to x. Examples: Input : Output: 3Explanation: The pairs are: (5, 11), (6, 10) and (8, 8) whose sum is equal to x. Table of Content [Naive Approach] Using Recursive Method - O(n1 * n2) Time and O(h1 +
15 min read
Check for Identical BSTs without building the trees
Given two arrays that represent a sequence of keys. Imagine we make a Binary Search Tree (BST) from each array. The task is to find whether two BSTs will be identical or not without actually constructing the tree. Examples: Input: arr1[] = {2, 4, 1, 3} , arr2[] = {2, 4, 3, 1} Output: TrueExplanation: As we can see the input arrays are {2, 4, 3, 1}
10 min read
Total number of BSTs using array elements
Prerequisite: Total number of possible Binary Search Trees with n keys Given an array arr[] of N integers. The task is to count the number of Binary Search Tree can be made using each node of element in arr[] as a root node.Examples: Input: arr[] = { 20, 10, 30 } Output: 1 2 2 Input: arr[] = { 1, 2, 3, 4, 5 } Output: 14 5 4 5 14 Approach: The total
7 min read
Find pairs with given sum such that pair elements lie in different BSTs
Given two Binary Search Trees (BST) and a given sum. The task is to find pairs with given sum such that each pair elements must lie in different BST. Examples: Input : sum = 10 8 5 / \ / \ 3 10 2 18 / \ \ / \ 1 6 14 1 3 / \ / \ 5 7 13 4 Output : (5,5), (6,4), (7,3), (8,2) In above pairs first element lies in first BST and second element lies in sec
14 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Count of sub-strings that do not contain all the characters from the set {'a', 'b', 'c'} at the same time
Given a string str consisting only of the characters 'a', 'b' and 'c', find the number of sub-strings that do not contain all the three characters at the same time.Examples: Input: str = "abc" Output: 5 The possible substrings are "a", "b", "c", "ab" and "bc"Input: str = "babac" Output: 12 Approach: The idea is to use three variables a_index, b_ind
8 min read
Check if set of first X elements of one Array is same as set of first Y elements of other
Given two arrays arr1[] and arr2[] of size N each and an array Q[][2] consisting of M queries of the form [x, y], the task for each query is to check if the set of values contained from first x elements of arr1[] is equal to set of values from in first y elements of arr2[]. Note: Two sets are equal when they have all their distinct elements equal.
15+ min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Count of BSTs with N nodes having height at least K
Given two positive integers N and K, the task is to find the number of binary search trees (BST) with N nodes of height greater than or equal to K. Note: Here height refers to the maximum depth of the BST. Examples: Input: N = 3, K = 3Output: 4Explanation:There are 4 possible binary search trees with height greater than or equal to K. 1 1 3 3 \ \ /
6 min read
Count of BSTs having N nodes and maximum depth equal to H
Given two integers N and H, the task is to find the count of distinct Binary Search Trees consisting of N nodes where the maximum depth or height of the tree is equal to H. Note: The height of BST with only the root node is 0. Examples: Input: N = 2, H = 1Output: 2Explanation: The two BST's are : Input: N = 3, H = 2Output: 4Explanation: The four BS
15+ min read
Construct all possible BSTs for keys 1 to N
Given an integer n, the task is to generate all possible Binary Search Trees (BSTs) that can be constructed using keys from 1 to n and print their preorder traversal. Examples: Input: n = 2Output:1 22 1 Input: n = 3Output: 1 2 31 3 22 1 33 1 23 2 1 How many structurally unique BSTs can be formed with keys from 1 to n? The key observation is that fo
8 min read
Count elements of same value placed at same indices of two given arrays
Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the two arrays). Examples: Input: A[] = { 5, 3, 7, 9, 8
8 min read
Construct a graph which does not contain any pair of adjacent nodes with same value
Given an array arr[] consisting of N characters, the task is to generate a graph of N nodes and (N - 1) Edges such that each node i is associated with character arr[i] and no two adjacent nodes have the same value. If it is possible to make such a graph, then print "Possible" with the pairs of edges. Otherwise, print "Not Possible". Examples: Input
10 min read
Minimum difference between adjacent elements of array which contain elements from each row of a matrix
Given a matrix of N rows and M columns, the task is to find the minimum absolute difference between any of the two adjacent elements of an array of size N, which is created by picking one element from each row of the matrix. Note the element picked from row 1 will become arr[0], element picked from row 2 will become arr[1] and so on. Examples: Inpu
10 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Loss when two items are sold at same price and same percentage profit/loss
Given the Selling price i.e 'SP' of the two items each. One item is sold at 'P%' Profit and other at 'P%' Loss. The task is to find out the overall Loss.Examples: Input: SP = 2400, P = 30% Output: Loss = 474.725 Input: SP = 5000, P = 10% Output: Loss = 101.01 Approach: How does the above formula work? For profit making item : With selling price (10
4 min read
Check if two elements of a matrix are on the same diagonal or not
Given a matrix mat[][], and two integers X and Y, the task is to check if X and Y are on the same diagonal of the given matrix or not. Examples: Input: mat[][]= {{1, 2}. {3, 4}}, X = 1, Y = 4 Output: YesExplanation:Both X and Y lie on the same diagonal. Input: mat[][]= {{1, 2}. {3, 4}}, X = 2, Y = 4Output: No Approach: The key observation to solve
7 min read
Check if two unsorted arrays (with duplicates allowed) have same elements
Given two unsorted arrays, check whether both arrays have the same set of elements or not. Examples: Input : A = {2, 5, 6, 8, 10, 2, 2} B = {2, 5, 5, 6, 8, 5, 6} Output : No Input : A = {2, 5, 6, 8, 2, 10, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Input : A = {2, 5, 8, 6, 10, 2, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Method 1 (Simple):A simple
13 min read
Check if the relative ordering of elements in given two Arrays is same or not
Given two arrays A[] and B[] each of size N, the task is to check if the sequencing of both the arrays is the same or not. If the sequencing of both the arrays is same, the print Yes otherwise print No. Examples: Input: A[] = { 10, 12, 9, 11 }, B[] = { 2, 7, -3, 5 };Output: YesExplanation: In both the arrays, the relative ordering of elements are s
7 min read
Find whether only two parallel lines contain all coordinates points or not
Given an array that represents the y coordinates of a set of points on a coordinate plane, where (i, arr[i]) represent a single point. Find whether it is possible to draw a pair of parallel lines that includes all the coordinate points given and also both lines must contain a point. Print 1 for possible and 0 if not possible. Examples: Input: arr[]
7 min read
Find two numbers whose sum is N and does not contain any digit as K
Given an integer N, the task is to find two numbers a and b such that a + b = N, where a and b doesn't contain any of the digits as K. Print -1 if not possible. Examples: Input: N = 100, K = 0Output: 1 99Explanation:1 + 99 = 100 and none of the numbers has 0 in it. Input: N = 123456789, K = 2Output: 3456790 119999999 Explanation:3456790 + 119999999
6 min read
three90RightbarBannerImg