The Wayback Machine - https://web.archive.org/web/20240921060229/https://www.geeksforgeeks.org/insertion-and-deletion-in-heaps/
Open In App

Insertion and Deletion in Heaps

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

Deletion in Heap:

Given a Binary Heap and an element present in the given Heap. The task is to delete an element from this Heap. 

The standard deletion operation on Heap is to delete the element present at the root node of the Heap. That is if it is a Max Heap, the standard deletion operation will delete the maximum element and if it is a Min heap, it will delete the minimum element.

Process of Deletion: 
Since deleting an element at any intermediary position in the heap can be costly, so we can simply replace the element to be deleted by the last element and delete the last element of the Heap. 

  • Replace the root or element to be deleted by the last element.
  • Delete the last element from the Heap.
  • Since, the last element is now placed at the position of the root node. So, it may not follow the heap property. Therefore, heapify the last node placed at the position of root.

Illustration:  

Suppose the Heap is a Max-Heap as:
10
/ \
5 3
/ \
2 4
The element to be deleted is root, i.e. 10.
Process:
The last element is 4.
Step 1: Replace the last element with root, and delete it.
4
/ \
5 3
/
2
Step 2: Heapify root.
Final Heap:
5
/ \
4 3
/
2

Implementation:  

C++




// C++ program for implement deletion in Heaps
 
#include <iostream>
 
using namespace std;
 
// To heapify a subtree rooted with node i which is
// an index of arr[] and n is the size of heap
void heapify(int arr[], int n, int i)
{
    int largest = i; // Initialize largest as root
    int l = 2 * i + 1; // left = 2*i + 1
    int r = 2 * i + 2; // right = 2*i + 2
 
    // If left child is larger than root
    if (l < n && arr[l] > arr[largest])
        largest = l;
 
    // If right child is larger than largest so far
    if (r < n && arr[r] > arr[largest])
        largest = r;
 
    // If largest is not root
    if (largest != i) {
        swap(arr[i], arr[largest]);
 
        // Recursively heapify the affected sub-tree
        heapify(arr, n, largest);
    }
}
 
// Function to delete the root from Heap
void deleteRoot(int arr[], int& n)
{
    // Get the last element
    int lastElement = arr[n - 1];
 
    // Replace root with last element
    arr[0] = lastElement;
 
    // Decrease size of heap by 1
    n = n - 1;
 
    // heapify the root node
    heapify(arr, n, 0);
}
 
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Array representation of Max-Heap
    //     10
    //    /  \
    //   5    3
    //  / \
    // 2   4
    int arr[] = { 10, 5, 3, 2, 4 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    deleteRoot(arr, n);
 
    printArray(arr, n);
 
    return 0;
}


Java




// Java program for implement deletion in Heaps
public class deletionHeap {
 
    // To heapify a subtree rooted with node i which is
    // an index in arr[].Nn is size of heap
    static void heapify(int arr[], int n, int i)
    {
        int largest = i; // Initialize largest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2
 
        // If left child is larger than root
        if (l < n && arr[l] > arr[largest])
            largest = l;
 
        // If right child is larger than largest so far
        if (r < n && arr[r] > arr[largest])
            largest = r;
 
        // If largest is not root
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
 
            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }
 
    // Function to delete the root from Heap
    static int deleteRoot(int arr[], int n)
    {
        // Get the last element
        int lastElement = arr[n - 1];
 
        // Replace root with first element
        arr[0] = lastElement;
 
        // Decrease size of heap by 1
        n = n - 1;
 
        // heapify the root node
        heapify(arr, n, 0);
 
        // return new size of Heap
        return n;
    }
 
    /* A utility function to print array of size N */
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
 
        System.out.println();
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Array representation of Max-Heap
        // 10
        //    /  \
        // 5    3
        //  / \
        // 2   4
        int arr[] = { 10, 5, 3, 2, 4 };
 
        int n = arr.length;
 
        n = deleteRoot(arr, n);
 
        printArray(arr, n);
    }
}


Python3




# Python 3 program for implement deletion in Heaps
 
# To heapify a subtree rooted with node i which is
# an index of arr[] and n is the size of heap
def heapify(arr, n, i):
 
    largest = i #Initialize largest as root
    l = 2 * i + 1 # left = 2*i + 1
    r = 2 * i + 2 # right = 2*i + 2
 
    #If left child is larger than root
    if (l < n and arr[l] > arr[largest]):
        largest = l
 
    #If right child is larger than largest so far
    if (r < n and arr[r] > arr[largest]):
        largest = r
 
    # If largest is not root
    if (largest != i):
        arr[i],arr[largest]=arr[largest],arr[i]
 
        #Recursively heapify the affected sub-tree
        heapify(arr, n, largest)
 
#Function to delete the root from Heap
def deleteRoot(arr):
    global n
 
    # Get the last element
    lastElement = arr[n - 1]
 
    # Replace root with last element
    arr[0] = lastElement
 
    # Decrease size of heap by 1
    n = n - 1
 
    # heapify the root node
    heapify(arr, n, 0)
 
# A utility function to print array of size n
def printArray(arr, n):
 
    for i in range(n):
        print(arr[i],end=" ")
    print()
 
# Driver Code
if __name__ == '__main__':
 
    # Array representation of Max-Heap
    #      10
    #     /  \
    #    5    3
    #   / \
    #  2   4
    arr = [ 10, 5, 3, 2, 4 ]
 
    n = len(arr)
 
    deleteRoot(arr)
 
    printArray(arr, n)
     
    # This code is contributed by Rajat Kumar.


C#




// C# program for implement deletion in Heaps
using System;
 
public class deletionHeap
{
 
    // To heapify a subtree rooted with node i which is
    // an index in arr[].Nn is size of heap
    static void heapify(int []arr, int n, int i)
    {
        int largest = i; // Initialize largest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2
 
        // If left child is larger than root
        if (l < n && arr[l] > arr[largest])
            largest = l;
 
        // If right child is larger than largest so far
        if (r < n && arr[r] > arr[largest])
            largest = r;
 
        // If largest is not root
        if (largest != i)
        {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
 
            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }
 
    // Function to delete the root from Heap
    static int deleteRoot(int []arr, int n)
    {
        // Get the last element
        int lastElement = arr[n - 1];
 
        // Replace root with first element
        arr[0] = lastElement;
 
        // Decrease size of heap by 1
        n = n - 1;
 
        // heapify the root node
        heapify(arr, n, 0);
 
        // return new size of Heap
        return n;
    }
 
    /* A utility function to print array of size N */
    static void printArray(int []arr, int n)
    {
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");
 
        Console.WriteLine();
    }
 
    // Driver Code
    public static void Main()
    {
        // Array representation of Max-Heap
        // 10
        // / \
        // 5 3
        // / \
        // 2 4
        int []arr = { 10, 5, 3, 2, 4 };
        int n = arr.Length;
        n = deleteRoot(arr, n);
        printArray(arr, n);
    }
}
 
// This code is contributed by Ryuga


Javascript




<script>
    // Javascript program for implement deletion in Heaps
     
    // To heapify a subtree rooted with node i which is
    // an index in arr[].Nn is size of heap
    function heapify(arr, n, i)
    {
        let largest = i; // Initialize largest as root
        let l = 2 * i + 1; // left = 2*i + 1
        let r = 2 * i + 2; // right = 2*i + 2
   
        // If left child is larger than root
        if (l < n && arr[l] > arr[largest])
            largest = l;
   
        // If right child is larger than largest so far
        if (r < n && arr[r] > arr[largest])
            largest = r;
   
        // If largest is not root
        if (largest != i)
        {
            let swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;
   
            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }
   
    // Function to delete the root from Heap
    function deleteRoot(arr, n)
    {
        // Get the last element
        let lastElement = arr[n - 1];
   
        // Replace root with first element
        arr[0] = lastElement;
   
        // Decrease size of heap by 1
        n = n - 1;
   
        // heapify the root node
        heapify(arr, n, 0);
   
        // return new size of Heap
        return n;
    }
   
    /* A utility function to print array of size N */
    function printArray(arr, n)
    {
        for (let i = 0; i < n; ++i)
            document.write(arr[i] + " ");
   
        document.write("</br>");
    }
     
    let arr = [ 10, 5, 3, 2, 4 ];
    let n = arr.length;
    n = deleteRoot(arr, n);
    printArray(arr, n);
 
// This code is contributed by divyeshrabdiya07.
</script>


Output

5 4 3 2

Time complexity: O(logn) where n is no of elements in the heap
Auxiliary Space: O(n)

Insertion in Heaps:

The insertion operation is also similar to that of the deletion process. 

Given a Binary Heap and a new element to be added to this Heap. The task is to insert the new element to the Heap maintaining the properties of Heap. 

Process of Insertion: Elements can be inserted to the heap following a similar approach as discussed above for deletion. The idea is to: 

  • First increase the heap size by 1, so that it can store the new element.
  • Insert the new element at the end of the Heap.
  • This newly inserted element may distort the properties of Heap for its parents. So, in order to keep the properties of Heap, heapify this newly inserted element following a bottom-up approach.

Illustration:  

Suppose the Heap is a Max-Heap as:
10
/ \
5 3
/ \
2 4
The new element to be inserted is 15.
Process:
Step 1: Insert the new element at the end.
10
/ \
5 3
/ \ /
2 4 15
Step 2: Heapify the new element following bottom-up
approach.
-> 15 is more than its parent 3, swap them.
10
/ \
5 15
/ \ /
2 4 3
-> 15 is again more than its parent 10, swap them.
15
/ \
5 10
/ \ /
2 4 3
Therefore, the final heap after insertion is:
15
/ \
5 10
/ \ /
2 4 3

Implementation: 

C++




// C++ program to insert new element to Heap
 
#include <iostream>
using namespace std;
 
#define MAX 1000 // Max size of Heap
 
// Function to heapify ith node in a Heap
// of size n following a Bottom-up approach
void heapify(int arr[], int n, int i) {
    // Find parent
    int parent = (i - 1) / 2;
    if (parent >= 0) {
        // For Max-Heap
        // If current node is greater than its parent
        // Swap both of them and call heapify again
        // for the parent
        if (arr[i] > arr[parent]) {
            swap(arr[i], arr[parent]);
            // Recursively heapify the parent node
            heapify(arr, n, parent);
        }
    }
}
 
// Function to insert a new node to the Heap
void insertNode(int arr[], int& n, int Key)
{
    // Increase the size of Heap by 1
    n = n + 1;
 
    // Insert the element at end of Heap
    arr[n - 1] = Key;
 
    // Heapify the new node following a
    // Bottom-up approach
    heapify(arr, n, n - 1);
}
 
// A utility function to print array of size n
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
 
    cout << "\n";
}
 
// Driver Code
int main()
{
    // Array representation of Max-Heap
    // 10
    //    /  \
    // 5    3
    //  / \
    // 2   4
    int arr[MAX] = { 10, 5, 3, 2, 4 };
 
    int n = 5;
 
    int key = 15;
 
    insertNode(arr, n, key);
 
    printArray(arr, n);
    // Final Heap will be:
    // 15
    //    /   \
    // 5     10
    //  / \   /
    // 2   4 3
    return 0;
}


Java




// Java program for implementing insertion in Heaps
public class insertionHeap {
 
    // Function to heapify ith node in a Heap
    // of size n following a Bottom-up approach
    static void heapify(int[] arr, int n, int i)
    {
        // Find parent
        int parent = (i - 1) / 2;
     
        if (parent >= 0) {
            // For Max-Heap
            // If current node is greater than its parent
            // Swap both of them and call heapify again
            // for the parent
            if (arr[i] > arr[parent]) {
                 
                  // swap arr[i] and arr[parent]
                int temp = arr[i];
                arr[i] = arr[parent];
                arr[parent] = temp;
               
                // Recursively heapify the parent node
                heapify(arr, n, parent);
            }
        }
    }
 
    // Function to insert a new node to the heap.
    static int insertNode(int[] arr, int n, int Key)
    {
        // Increase the size of Heap by 1
        n = n + 1;
     
        // Insert the element at end of Heap
        arr[n - 1] = Key;
     
        // Heapify the new node following a
        // Bottom-up approach
        heapify(arr, n, n - 1);
         
        // return new size of Heap
        return n;
    }
 
    /* A utility function to print array of size n */
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; ++i)
            System.out.println(arr[i] + " ");
 
        System.out.println();
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Array representation of Max-Heap
        // 10
        //    /  \
        // 5    3
        //  / \
        // 2   4
         
        // maximum size of the array
        int MAX = 1000;
        int[] arr = new int[MAX];
         
        // initializing some values
        arr[0] = 10;
        arr[1] = 5;
        arr[2] = 3;
        arr[3] = 2;
        arr[4] = 4;
         
        // Current size of the array
        int n = 5;
 
        // the element to be inserted
        int Key = 15;
         
        // The function inserts the new element to the heap and
        // returns the new size of the array
        n = insertNode(arr, n, Key);
 
        printArray(arr, n);
        // Final Heap will be:
        // 15
        //    /   \
        // 5     10
        //  / \   /
        // 2   4 3
    }
}
 
// The code is contributed by Gautam goel


Python3




# program to insert new element to Heap
 
# Function to heapify ith node in a Heap
# of size n following a Bottom-up approach
 
 
def heapify(arr, n, i):
    parent = int(((i-1)/2))
    # For Max-Heap
    # If current node is greater than its parent
    # Swap both of them and call heapify again
    # for the parent
    if parent >= 0:
        if arr[i] > arr[parent]:
            arr[i], arr[parent] = arr[parent], arr[i]
            # Recursively heapify the parent node
            heapify(arr, n, parent)
# Function to insert a new node to the Heap
 
 
def insertNode(arr, key):
    global n
    # Increase the size of Heap by 1
    n += 1
    # Insert the element at end of Heap
    arr.append(key)
    # Heapify the new node following a
    # Bottom-up approach
    heapify(arr, n, n-1)
# A utility function to print array of size n
 
 
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end=" ")
 
 
# Driver Code
# Array representation of Max-Heap
'''
        10
       /  \
      5    3
     / \
    2   4
'''
arr = [10, 5, 3, 2, 4, 1, 7]
n = 7
key = 15
insertNode(arr, key)
printArr(arr, n)
# Final Heap will be:
'''
      15
    /   \
   5     10
 /  \    /
2    4   3
 
Code is written by Rajat Kumar....
'''


C#




// C# program for implementing insertion in Heaps
 
using System;
 
public class insertionHeap {
 
    // Function to heapify ith node in a Heap of size n following a Bottom-up approach
    static void heapify(int[] arr, int n, int i) {
        // Find parent
        int parent = (i - 1) / 2;
 
        if (parent >= 0) {
            // For Max-Heap
            // If current node is greater than its parent
            // Swap both of them and call heapify again
            // for the parent
            if (arr[i] > arr[parent]) {
 
                // swap arr[i] and arr[parent]
                int temp = arr[i];
                arr[i] = arr[parent];
                arr[parent] = temp;
 
                // Recursively heapify the parent node
                heapify(arr, n, parent);
            }
        }
    }
 
    // Function to insert a new node to the heap.
    static int insertNode(int[] arr, int n, int Key) {
        // Increase the size of Heap by 1
        n = n + 1;
 
        // Insert the element at end of Heap
        arr[n - 1] = Key;
 
        // Heapify the new node following a
        // Bottom-up approach
        heapify(arr, n, n - 1);
 
        // return new size of Heap
        return n;
    }
 
    /* A utility function to print array of size n */
    static void printArray(int[] arr, int n) {
        for (int i = 0; i < n; ++i)
            Console.WriteLine(arr[i] + " ");
 
        Console.WriteLine("");
    }
 
    public static void Main(string[] args) {
        // Array representation of Max-Heap
        //     10
        //    /  \
        //   5    3
        //  / \
        // 2   4
 
        // maximum size of the array
        int MAX = 1000;
        int[] arr = new int[MAX];
 
        // initializing some values
        arr[0] = 10;
        arr[1] = 5;
        arr[2] = 3;
        arr[3] = 2;
        arr[4] = 4;
 
        // Current size of the array
        int n = 5;
 
        // the element to be inserted
        int Key = 15;
 
        // The function inserts the new element to the heap and
        // returns the new size of the array
        n = insertNode(arr, n, Key);
 
        printArray(arr, n);
        // Final Heap will be:
        //      15
        //    /   \
        //   5     10
        //  / \   /
        // 2   4 3
    }
}
 
// This code is contributed by ajaymakvana.


Javascript




// Javascript program for implement insertion in Heaps
 
// To heapify a subtree rooted with node i which is
// an index in arr[].Nn is size of heap
 
let MAX = 1000;
 
// Function to heapify ith node in a Heap of size n following a Bottom-up approach
function heapify(arr, n, i)
{
    // Find parent
    let parent = Math.floor((i-1)/2);
 
    if (parent >= 0) {
        // For Max-Heap
        // If current node is greater than its parent
        // Swap both of them and call heapify again
        // for the parent
        if (arr[i] > arr[parent]) {
            let temp = arr[i];
            arr[i] = arr[parent];
            arr[parent] = temp;
 
            // Recursively heapify the parent node
            heapify(arr, n, parent);
        }
    }
}
 
// Function to insert a new node to the Heap
function insertNode(arr, n, Key)
{
    // Increase the size of Heap by 1
    n = n + 1;
 
    // Insert the element at end of Heap
    arr[n - 1] = Key;
 
    // Heapify the new node following a
    // Bottom-up approach
    heapify(arr, n, n - 1);
     
    return n;
}
 
/* A utility function to print array of size N */
function printArray(arr, n)
{
    for (let i = 0; i < n; ++i)
        console.log(arr[i] + " ");
 
    console.log("</br>");
}
 
let arr = [ 10, 5, 3, 2, 4 ];
 
let n = arr.length;
 
let key = 15;
 
n = insertNode(arr, n, key);
 
printArray(arr, n);
 
// This code is contributed by ajaymakvana


Output

15 5 10 2 4 3

Time Complexity:  O(log(n)) (where n is no of elements in the heap)
Auxiliary Space: O(n)



Similar Reads

m-Way Search Tree | Set-2 | Insertion and Deletion
Insertion in an m-Way search tree: The insertion in an m-Way search tree is similar to binary trees but there should be no more than m-1 elements in a node. If the node is full then a child node will be created to insert the further elements. Let us see the example given below to insert an element in an m-Way search tree.Example: To insert a new el
15+ min read
Insertion, Searching and Deletion in AVL trees containing a parent node pointer
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. The insertion and deletion in AVL trees have been discussed in the previous article. In this article, insert, search, and delete operations are discussed on AVL trees that also have a parent po
15+ min read
Count of array elements whose order of deletion precedes order of insertion
Given an initial array, A[] and a final array B[] both of size N containing integers from the range [1, N], where A[] represent the order in which elements were inserted and B[] represents the order in which they were removed, the task is to find the number of elements in B[] lying at an index earlier than its respective position in A[]. Examples:
7 min read
Difference between Heaps and Sorted Array
1. Heap:A heap is a tree based data structure in which tree should be almost complete. It is of two types i.e. max and min heap. Max heap: In max heap, if p is the parent and c is its child, then for every parent p the value of it is greater than or equal to the value of cMin heap In min heap, if p is the parent and c is its child, then for every p
4 min read
Merge Two Binary Max Heaps
Given two binary max heaps, the task is to merge the given heaps to form a new max heap. Examples :  Input: a[] = {10, 5, 6, 2}, b[] = {12, 7, 9}Output: {12, 10, 9, 2, 5, 7, 6} Input: a[] = {2, 5, 1, 9, 12}, b[] = {3, 7, 4, 10}Output: {12, 10, 7, 9, 5, 3, 1, 4, 2} Table of Content [Naive Approach] Using Max Heap - O((N + M)*log(N + M)) Time and O(N
12 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
2-3 Trees | (Search, Insert and Deletion)
In binary search trees we have seen the average-case time for operations like search/insert/delete is O(log N) and the worst-case time is O(N) where N is the number of nodes in the tree. Like other Trees include AVL trees, Red Black Tree, B tree, 2-3 Tree is also a height balanced tree. The time complexity of search/insert/delete is O(log N) . A 2-
4 min read
Fibonacci Heap - Deletion, Extract min and Decrease key
In the last post, we discussed the Insertion and Union of Fibonacci Heaps. In this post, we will discuss Extract_min(), Decrease_key() and Deletion() operations on Fibonacci heap. Prerequisites: Fibonacci Heap (Introduction) Fibonacci Heap - Insertion and Union Extract_min(): We create a function for deleting the minimum node and setting the min po
12 min read
Make a string from another by deletion and rearrangement of characters
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH, s2 = gfhfBHkooIHnfndSHEKsiAnGOutput : Possible Input : s1 = Hello, s2 = dnaKfhelddfOutput : Not Possible Input : s1 = GeeksforGeeks, s2 = rteksfoGrdsskGeggehesOutput : Po
5 min read
Skip List | Set 3 (Searching and Deletion)
In previous article Skip List | Set 2 (Insertion) we discussed the structure of skip nodes and how to insert an element in the skip list. In this article we will discuss how to search and delete an element from skip list. Searching an element in Skip list Searching an element is very similar to approach for searching a spot for inserting an element
15+ min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Deletion at different positions in a Circular Linked List
tGiven a Circular Linked List. The task is to write programs to delete nodes from this list present at: First position.Last Position.At any given position [Tex]i [/Tex].Deleting first node from Singly Circular Linked List Examples: Input : 99-&gt;11-&gt;22-&gt;33-&gt;44-&gt;55-&gt;66 Output : 11-&gt;22-&gt;33-&gt;44-&gt;55-&gt;66 Input : 11-&gt;22-
15+ min read
Proto Van Emde Boas Trees | Set 4 | Deletion
Please check previous sets of Proto Van Emde Boas Tree article first. It is highly recommended.Procedure for delete: Base Case: If we reach at Proto VEB with size 2 then we will check for whether the key is present or not if yes then we assign the pointer to nullptr which will set false to it presence.Recursion: We recursively call delete function
14 min read
Count of elements in array A left after performing deletion/rotation operation based on given conditions
Given two binary arrays, A[] and B[] of size N respectively, the task is to find the number of elements in array A[] that will be left after performing the following operation until no elements can be deleted: If the starting elements of array A[] and B[] are equal, then delete both the elements.Otherwise, append the starting character of array A[]
9 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Set 2
Given two equal-size strings s[] and t[] of size N. In one step, choose any character of t[] and replace it with another character. Return the minimum number of steps to make t[] an anagram of s[]. Note: An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. Examples: Input: s = "baa", t = "aba
6 min read
Minimize deletions to reduce String to size 1 wherein ith deletion, N/2^i occurrences of (X+i-1)th character can be deleted
Given string str of length N and a character X, where N is always of the form 2k, the task is to find the minimum replacement operations required to reduce the size of the string to 1 wherein ith deletion, N/2i occurrences of (X + i - 1)th character can be deleted either from the front or the back of the string. Example: Input: str = "CDAAAABB", X
7 min read
Minimize deletion of edges to convert Tree into a forest of size at most N/2
Given a tree with N nodes, numbered from 0 to N - 1, the task is to find the minimum number of deletion of edges, such that, the tree is converted into a forest where each tree in the forest can have size less than equal to ⌊N/2⌋. Examples: Input: N = 3, edges = [[0, 1], [0, 2]] 0 / \ 1 2Output: 2Explanation: The maximum size of each tree after rem
14 min read
Minimize deletion or insertions of Array elements such that arr[i] have frequency as its value
Given an array arr[] of length N, the task is to find the minimum number of operations to change the array such that each arr[i] occurs arr[i] times where in each operation either one element can be deleted from the array or one element can be inserted in the array. Examples: Input: N = 4, arr[ ] = {1, 1, 3, 3}Output: 2Explanation: Delete one occur
7 min read
Minimum deletion such that Xor of adjacent digits is atmost 1
Given a string S consisting of N digits, the task is to find the minimum number of deletions such that the bitwise Xor of any two adjacent digits of the remaining string is at most 1. Examples: Input: S = "24244"Output: 2?Explanation: We can delete both the 2's to make the string "444", which satisfies the condition. Input: S = "9999"Output: 0 Appr
5 min read
Minimize deletion or append to make consecutive occurrence of all elements equal
Given an array arr[] of size N having positive elements, the task is to find the minimum number of deletion or append operations to make consecutive occurrences of all elements equal. Examples: Input: N = 4, arr[] = {1, 1, 2, 2}Output: 0Explanation: All the consecutive elements have the same value and same frequency already. Therefore, no operation
15 min read
Check if L sized Subarray of first N numbers can have sum S with one deletion allowed
Consider an integer sequence A = {1, 2, 3, ...., N} i.e. the first N natural numbers in order and two integers, L and S. Check whether there exists a subarray of length L and sum S after removing at most one element from A. Examples: Input: N = 5, L = 3, S = 11Output: YESExplanation: We can remove 3 from A to obtain A = {1, 2, 4, 5} where {2, 4, 5}
6 min read
Van Emde Boas Tree | Set 4 | Deletion
It is highly recommended to read the previous articles on Van Emde Boas Tree first. Procedure for Delete: Here we are assuming that the key is already present in the tree. First we check if only one key is present, then assign the maximum and minimum of the tree to null value to delete the key.Base Case: If the universe size of the tree is two then
15+ min read
Minimum steps to delete a string after repeated deletion of palindrome substrings
Given a string containing characters as integers only. We need to delete all characters of this string in a minimum number of steps wherein in one step we can delete the substring which is a palindrome. After deleting a substring remaining parts are concatenated. Examples: Input : s = “2553432” Output : 2 We can delete all character of above string
15+ min read
Deletion in Red-Black Tree
Deletion in a red-black tree is a bit more complicated than insertion. When a node is to be deleted, it can either have no children, one child or two children. Here are the steps involved in deleting a node in a red-black tree:If the node to be deleted has no children, simply remove it and update the parent node.If the node to be deleted has only o
15+ min read
Deletion in K Dimensional Tree
We strongly recommend to refer below posts as a prerequisite of this.K Dimensional Tree | Set 1 (Search and Insert) K Dimensional Tree | Set 2 (Find Minimum)In this post delete is discussed. The operation is to delete a given point from K D Tree. Like Binary Search Tree Delete, we recursively traverse down and search for the point to be deleted. Be
15+ min read
Size of array after repeated deletion of LIS
Given an array arr[0..n-1] of the positive element. The task is to print the remaining elements of arr[] after repeated deletion of LIS (of size greater than 1). If there are multiple LIS with the same length, we need to choose the LIS that ends first.Examples: Input : arr[] = {1, 2, 5, 3, 6, 4, 1} Output : 1 Explanation : {1, 2, 5, 3, 6, 4, 1} - {
11 min read
Deletion in Doubly Circular Linked List
We have discussed the doubly circular linked list introduction and its insertion.Let us formulate the problem statement to understand the deletion process. Given a ‘key’, delete the first occurrence of this key in the circular doubly linked list. Algorithm: Case 1: Empty List(start = NULL) If the list is empty, simply return it. Case 2: The List in
15+ min read
Threaded Binary Search Tree | Deletion
A threaded binary tree node looks like following. C/C++ Code struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread; }; Java Code static class Node { Node left, right; int info; // Tru
15+ min read
Ternary Search Tree (Deletion)
In the SET 1 post on TST we have described how to insert and search a node in TST. In this article, we will discuss algorithm on how to delete a node from TST. During delete operation we delete the key in bottom-up manner using recursion. The following are possible cases when deleting a key from trie. Key may not be there in TST. Solution: Delete o
14 min read
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
Given two strings s1 and s2, we need to find the minimum number of manipulations required to make two strings anagram without deleting any character. Note:- The anagram strings have same set of characters, sequence of characters can be different. If deletion of character is allowed and cost is given, refer to Minimum Cost To Make Two Strings Identi
10 min read
Article Tags :
Practice Tags :