Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Tile Stacking Problem
Next article icon

Vertex Cover Problem (Dynamic Programming Solution for Tree)

Last Updated : 30 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. 
The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for trees. In this post a solution for Binary Tree is discussed. The same solution can be extended for n-ary trees.

For example, consider the following binary tree. The smallest vertex cover is {20, 50, 30} and size of the vertex cover is 3. 

LargestIndependentSet1

The idea is to consider following two possibilities for root and recursively for all nodes down the root. 
1) Root is part of vertex cover: In this case root covers all children edges. We recursively calculate size of vertex covers for left and right subtrees and add 1 to the result (for root).

2) Root is not part of vertex cover: In this case, both children of root must be included in vertex cover to cover all root to children edges. We recursively calculate size of vertex covers of all grandchildren and number of children to the result (for two children of root).

Below are implementation of above idea. 

C




// A naive recursive C implementation for vertex cover problem for a tree
#include <stdio.h>
#include <stdlib.h>
 
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
 
/* A binary tree node has data, pointer to left child and a pointer to
   right child */
struct node
{
    int data;
    struct node *left, *right;
};
 
// The function returns size of the minimum vertex cover
int vCover(struct node *root)
{
    // The size of minimum vertex cover is zero if tree is empty or there
    // is only one node
    if (root == NULL)
        return 0;
    if (root->left == NULL && root->right == NULL)
        return 0;
 
    // Calculate size of vertex cover when root is part of it
    int size_incl = 1 + vCover(root->left) + vCover(root->right);
 
    // Calculate size of vertex cover when root is not part of it
    int size_excl = 0;
    if (root->left)
      size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
    if (root->right)
      size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
 
    // Return the minimum of two sizes
    return min(size_incl, size_excl);
}
 
// A utility function to create a node
struct node* newNode( int data )
{
    struct node* temp = (struct node *) malloc( sizeof(struct node) );
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us construct the tree given in the above diagram
    struct node *root         = newNode(20);
    root->left                = newNode(8);
    root->left->left          = newNode(4);
    root->left->right         = newNode(12);
    root->left->right->left   = newNode(10);
    root->left->right->right  = newNode(14);
    root->right               = newNode(22);
    root->right->right        = newNode(25);
 
    printf ("Size of the smallest vertex cover is %d ", vCover(root));
 
    return 0;
}
 
 

C++




#include <iostream>
#include <cstdlib>
 
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
 
/* A binary tree node has data, pointer to left child and a pointer to
   right child */
struct node
{
    int data;
    node *left, *right;
};
 
// The function returns size of the minimum vertex cover
int vCover(node *root)
{
    // The size of minimum vertex cover is zero if tree is empty or there
    // is only one node
    if (root == nullptr)
        return 0;
    if (root->left == nullptr && root->right == nullptr)
        return 0;
 
    // Calculate size of vertex cover when root is part of it
    int size_incl = 1 + vCover(root->left) + vCover(root->right);
 
    // Calculate size of vertex cover when root is not part of it
    int size_excl = 0;
    if (root->left)
      size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
    if (root->right)
      size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
 
    // Return the minimum of two sizes
    return min(size_incl, size_excl);
}
 
// A utility function to create a node
node* newNode( int data )
{
    node* temp = new node;
    temp->data = data;
    temp->left = temp->right = nullptr;
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us construct the tree given in the above diagram
    node *root         = newNode(20);
    root->left                = newNode(8);
    root->left->left          = newNode(4);
    root->left->right         = newNode(12);
    root->left->right->left   = newNode(10);
    root->left->right->right  = newNode(14);
    root->right               = newNode(22);
    root->right->right        = newNode(25);
 
    std::cout << "Size of the smallest vertex cover is " << vCover(root) << std::endl;
 
    return 0;
}
 
 

Java




// A naive recursive Java implementation
// for vertex cover problem for a tree
 
class GFG
{
    // A utility function to find min of two integers
    static int min(int x, int y)
    {
        return (x < y) ? x : y;
    }
 
    /*
    * A binary tree node has data, pointer
    to left child and a pointer to right
    * child
    */
    static class node
    {
        int data;
        node left, right;
    };
 
    // The function returns size
    // of the minimum vertex cover
    static int vCover(node root)
    {
        // The size of minimum vertex cover
        // is zero if tree is empty or there
        // is only one node
        if (root == null)
            return 0;
        if (root.left == null && root.right == null)
            return 0;
 
        // Calculate size of vertex cover
        // when root is part of it
        int size_incl = 1 + vCover(root.left) +
                               vCover(root.right);
 
        // Calculate size of vertex cover
        // when root is not part of it
        int size_excl = 0;
        if (root.left != null)
            size_excl += 1 + vCover(root.left.left) +
                              vCover(root.left.right);
        if (root.right != null)
            size_excl += 1 + vCover(root.right.left) +
                                vCover(root.right.right);
 
        // Return the minimum of two sizes
        return Math.min(size_incl, size_excl);
    }
 
    // A utility function to create a node
    static node newNode(int data)
    {
        node temp = new node();
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Let us construct tree given in the above diagram
        node root = newNode(20);
        root.left = newNode(8);
        root.left.left = newNode(4);
        root.left.right = newNode(12);
        root.left.right.left = newNode(10);
        root.left.right.right = newNode(14);
        root.right = newNode(22);
        root.right.right = newNode(25);
 
        System.out.printf("Size of the smallest vertex" +
                            "cover is %d ", vCover(root));
 
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# A naive recursive Python3 implementation
# for vertex cover problem for a tree
 
# A utility function to find min of two integers
 
# A binary tree node has data, pointer to
# left child and a pointer to right child
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.left = None
        self.right = None
 
# The function returns size of
# the minimum vertex cover
def vCover(root):
     
    # The size of minimum vertex cover
    # is zero if tree is empty or there
    # is only one node
    if (root == None):
        return 0
         
    if (root.left == None and
       root.right == None):
        return 0
 
    # Calculate size of vertex cover when
    # root is part of it
    size_incl = (1 + vCover(root.left) +
                     vCover(root.right))
 
    # Calculate size of vertex cover
    # when root is not part of it
    size_excl = 0
    if (root.left):
      size_excl += (1 + vCover(root.left.left) +
                        vCover(root.left.right))
    if (root.right):
      size_excl += (1 + vCover(root.right.left) +
                        vCover(root.right.right))
 
    # Return the minimum of two sizes
    return min(size_incl, size_excl)
 
# Driver Code
if __name__ == '__main__':
     
    # Let us construct the tree
    # given in the above diagram
    root  = Node(20)
    root.left = Node(8)
    root.left.left = Node(4)
    root.left.right = Node(12)
    root.left.right.left = Node(10)
    root.left.right.right = Node(14)
    root.right  = Node(22)
    root.right.right = Node(25)
 
    print("Size of the smallest vertex cover is", vCover(root))
 
# This code is contributed by mohit kumar 29
 
 

C#




// A naive recursive C# implementation
// for vertex cover problem for a tree
using System;
 
class GFG
{
    // A utility function to find
    // min of two integers
    static int min(int x, int y)
    {
        return (x < y) ? x : y;
    }
 
    /*
    * A binary tree node has data, pointer
    to left child and a pointer to right
    * child
    */
    public class node
    {
        public int data;
        public node left, right;
    };
 
    // The function returns size
    // of the minimum vertex cover
    static int vCover(node root)
    {
        // The size of minimum vertex cover
        // is zero if tree is empty or there
        // is only one node
        if (root == null)
            return 0;
        if (root.left == null &&
            root.right == null)
            return 0;
 
        // Calculate size of vertex cover
        // when root is part of it
        int size_incl = 1 + vCover(root.left) +
                            vCover(root.right);
 
        // Calculate size of vertex cover
        // when root is not part of it
        int size_excl = 0;
        if (root.left != null)
            size_excl += 1 + vCover(root.left.left) +
                             vCover(root.left.right);
        if (root.right != null)
            size_excl += 1 + vCover(root.right.left) +
                             vCover(root.right.right);
 
        // Return the minimum of two sizes
        return Math.Min(size_incl, size_excl);
    }
 
    // A utility function to create a node
    static node newNode(int data)
    {
        node temp = new node();
        temp.data = data;
        temp.left = temp.right = null;
        return temp;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // Let us construct tree given
        // in the above diagram
        node root = newNode(20);
        root.left = newNode(8);
        root.left.left = newNode(4);
        root.left.right = newNode(12);
        root.left.right.left = newNode(10);
        root.left.right.right = newNode(14);
        root.right = newNode(22);
        root.right.right = newNode(25);
 
        Console.Write("Size of the smallest vertex" +
                      "cover is {0} ", vCover(root));
    }
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// A naive recursive Javascript implementation
// for vertex cover problem for a tree
     
    // A utility function to find min of two integers
    function min(x,y)
    {
         return (x < y) ? x : y;
    }
     
    /*
    * A binary tree node has data, pointer
    to left child and a pointer to right
    * child
    */
    class Node
    {
        constructor(d)
        {
            this.data=d;
            this.left=null;
            this.right=null;
        }
    }
     
    // The function returns size
    // of the minimum vertex cover
    function vCover(root)
    {
        // The size of minimum vertex cover
        // is zero if tree is empty or there
        // is only one node
        if (root == null)
            return 0;
        if (root.left == null && root.right == null)
            return 0;
  
        // Calculate size of vertex cover
        // when root is part of it
        let size_incl = 1 + vCover(root.left) +
                               vCover(root.right);
  
        // Calculate size of vertex cover
        // when root is not part of it
        let size_excl = 0;
        if (root.left != null)
            size_excl += 1 + vCover(root.left.left) +
                              vCover(root.left.right);
        if (root.right != null)
            size_excl += 1 + vCover(root.right.left) +
                                vCover(root.right.right);
  
        // Return the minimum of two sizes
        return Math.min(size_incl, size_excl);
    }
     
    // Driver code
    // Let us construct tree given in the above diagram
    root = new Node(20);
    root.left = new Node(8);
    root.left.left = new Node(4);
    root.left.right = new Node(12);
    root.left.right.left = new Node(10);
    root.left.right.right = new Node(14);
    root.right = new Node(22);
    root.right.right = new Node(25);
     
    document.write("Size of the smallest vertex" +
                            "cover is ", vCover(root));   
     
    // This code is contributed by unknown2108
</script>
 
 
Output
Size of the smallest vertex cover is 3 

Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. For example, vCover of node with value 50 is evaluated twice as 50 is grandchild of 10 and child of 20.

Since same subproblems are called again, this problem has Overlapping Subproblems property. So Vertex Cover problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner.

Following is the implementation of Dynamic Programming based solution. In the following solution, an additional field ‘vc’ is added to tree nodes. The initial value of ‘vc’ is set as 0 for all nodes. The recursive function vCover() calculates ‘vc’ for a node only if it is not already set.

C




/* Dynamic programming based program for Vertex Cover problem for
   a Binary Tree */
#include <stdio.h>
#include <stdlib.h>
 
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
 
/* A binary tree node has data, pointer to left child and a pointer to
   right child */
struct node
{
    int data;
    int vc;
    struct node *left, *right;
};
 
// A memoization based function that returns size of the minimum vertex cover.
int vCover(struct node *root)
{
    // The size of minimum vertex cover is zero if tree is empty or there
    // is only one node
    if (root == NULL)
        return 0;
    if (root->left == NULL && root->right == NULL)
        return 0;
 
    // If vertex cover for this node is already evaluated, then return it
    // to save recomputation of same subproblem again.
    if (root->vc != 0)
        return root->vc;
 
    // Calculate size of vertex cover when root is part of it
    int size_incl = 1 + vCover(root->left) + vCover(root->right);
 
    // Calculate size of vertex cover when root is not part of it
    int size_excl = 0;
    if (root->left)
      size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
    if (root->right)
      size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
 
    // Minimum of two values is vertex cover, store it before returning
    root->vc =  min(size_incl, size_excl);
 
    return root->vc;
}
 
// A utility function to create a node
struct node* newNode( int data )
{
    struct node* temp = (struct node *) malloc( sizeof(struct node) );
    temp->data = data;
    temp->left = temp->right = NULL;
    temp->vc = 0; // Set the vertex cover as 0
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us construct the tree given in the above diagram
    struct node *root         = newNode(20);
    root->left                = newNode(8);
    root->left->left          = newNode(4);
    root->left->right         = newNode(12);
    root->left->right->left   = newNode(10);
    root->left->right->right  = newNode(14);
    root->right               = newNode(22);
    root->right->right        = newNode(25);
 
    printf ("Size of the smallest vertex cover is %d ", vCover(root));
 
    return 0;
}
 
 

C++




#include <iostream>
#include <stdlib.h>
 
// A utility function to find min of two integers
int min(int x, int y) { return (x < y)? x: y; }
 
/* A binary tree node has data, pointer to left child and a pointer to
   right child */
struct node
{
    int data;
    int vc;
    struct node *left, *right;
};
 
// A memoization based function that returns size of the minimum vertex cover.
int vCover(struct node *root)
{
    // The size of minimum vertex cover is zero if tree is empty or there
    // is only one node
    if (root == NULL)
        return 0;
    if (root->left == NULL && root->right == NULL)
        return 0;
 
    // If vertex cover for this node is already evaluated, then return it
    // to save recomputation of same subproblem again.
    if (root->vc != 0)
        return root->vc;
 
    // Calculate size of vertex cover when root is part of it
    int size_incl = 1 + vCover(root->left) + vCover(root->right);
 
    // Calculate size of vertex cover when root is not part of it
    int size_excl = 0;
    if (root->left)
      size_excl += 1 + vCover(root->left->left) + vCover(root->left->right);
    if (root->right)
      size_excl += 1 + vCover(root->right->left) + vCover(root->right->right);
 
    // Minimum of two values is vertex cover, store it before returning
    root->vc =  min(size_incl, size_excl);
 
    return root->vc;
}
 
// A utility function to create a node
struct node* newNode( int data )
{
    struct node* temp = (struct node *) malloc( sizeof(struct node) );
    temp->data = data;
    temp->left = temp->right = NULL;
    temp->vc = 0; // Set the vertex cover as 0
    return temp;
}
 
// Driver program to test above functions
int main()
{
    // Let us construct the tree given in the above diagram
    struct node *root         = newNode(20);
    root->left                = newNode(8);
    root->left->left          = newNode(4);
    root->left->right         = newNode(12);
    root->left->right->left   = newNode(10);
    root->left->right->right  = newNode(14);
    root->right               = newNode(22);
    root->right->right        = newNode(25);
 
    std::cout << "Size of the smallest vertex cover is " << vCover(root) << std::endl;
 
    return 0;
}
 
 

Java




/* Dynamic programming based program for
Vertex Cover problem for a Binary Tree */
 
class GFG
{
    // A utility function to find min of two integers
    static int min(int x, int y)
    {
        return (x < y) ? x : y;
    }
 
    /*
    * A binary tree node has data, pointer
    to left child and a pointer to right
    * child
    */
    static class node
    {
        int data;
        int vc;
        node left, right;
    };
 
    // A memoization based function that returns
    // size of the minimum vertex cover.
    static int vCover(node root)
    {
        // The size of minimum vertex cover is zero
        //  if tree is empty or there is only one node
        if (root == null)
            return 0;
        if (root.left == null && root.right == null)
            return 0;
 
        // If vertex cover for this node is
        // already evaluated, then return it
        // to save recomputation of same subproblem again.
        if (root.vc != 0)
            return root.vc;
 
        // Calculate size of vertex cover
        // when root is part of it
        int size_incl = 1 + vCover(root.left) +
                            vCover(root.right);
 
        // Calculate size of vertex cover
        // when root is not part of it
        int size_excl = 0;
        if (root.left != null)
            size_excl += 1 + vCover(root.left.left) +
                                vCover(root.left.right);
        if (root.right != null)
            size_excl += 1 + vCover(root.right.left) +
                                vCover(root.right.right);
 
        // Minimum of two values is vertex cover,
        // store it before returning
        root.vc = Math.min(size_incl, size_excl);
 
        return root.vc;
    }
 
    // A utility function to create a node
    static node newNode(int data)
    {
        node temp = new node();
        temp.data = data;
        temp.left = temp.right = null;
        temp.vc = 0; // Set the vertex cover as 0
        return temp;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Let us construct tree given in the above diagram
        node root = newNode(20);
        root.left = newNode(8);
        root.left.left = newNode(4);
        root.left.right = newNode(12);
        root.left.right.left = newNode(10);
        root.left.right.right = newNode(14);
        root.right = newNode(22);
        root.right.right = newNode(25);
 
        System.out.printf("Size of the smallest vertex" +
                            "cover is %d ", vCover(root));
    }
}
 
// This code is contributed by PrinciRaj1992
 
 

C#




/* Dynamic programming based program for
Vertex Cover problem for a Binary Tree */
using System;
 
class GFG
{
    // A utility function to find
    // min of two integers
    static int min(int x, int y)
    {
        return (x < y) ? x : y;
    }
 
    /*
    * A binary tree node has data, pointer
    to left child and a pointer to right
    * child
    */
    class node
    {
        public int data;
        public int vc;
        public node left, right;
    };
 
    // A memoization based function that returns
    // size of the minimum vertex cover.
    static int vCover(node root)
    {
        // The size of minimum vertex cover is zero
        // if tree is empty or there is only one node
        if (root == null)
            return 0;
        if (root.left == null &&
            root.right == null)
            return 0;
 
        // If vertex cover for this node is
        // already evaluated, then return it
        // to save recomputation of same subproblem again.
        if (root.vc != 0)
            return root.vc;
 
        // Calculate size of vertex cover
        // when root is part of it
        int size_incl = 1 + vCover(root.left) +
                            vCover(root.right);
 
        // Calculate size of vertex cover
        // when root is not part of it
        int size_excl = 0;
        if (root.left != null)
            size_excl += 1 + vCover(root.left.left) +
                             vCover(root.left.right);
        if (root.right != null)
            size_excl += 1 + vCover(root.right.left) +
                             vCover(root.right.right);
 
        // Minimum of two values is vertex cover,
        // store it before returning
        root.vc = Math.Min(size_incl, size_excl);
 
        return root.vc;
    }
 
    // A utility function to create a node
    static node newNode(int data)
    {
        node temp = new node();
        temp.data = data;
        temp.left = temp.right = null;
        temp.vc = 0; // Set the vertex cover as 0
        return temp;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // Let us construct tree given in the above diagram
        node root = newNode(20);
        root.left = newNode(8);
        root.left.left = newNode(4);
        root.left.right = newNode(12);
        root.left.right.left = newNode(10);
        root.left.right.right = newNode(14);
        root.right = newNode(22);
        root.right.right = newNode(25);
 
        Console.Write("Size of the smallest vertex" +
                      "cover is {0} ", vCover(root));
    }
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
/* Dynamic programming based program for
Vertex Cover problem for a Binary Tree */
 
// A utility function to find min of two integers
function min(x,y)
{
    return (x < y) ? x : y;
}
 
/*
    * A binary tree node has data, pointer
    to left child and a pointer to right
    * child
    */
class Node
{
    constructor(data)
    {
        this.vc=0;
        this.data=data;
        this.left=this.right=null;
    }
}
 
// A memoization based function that returns
// size of the minimum vertex cover.
function vCover(root)
{
    // The size of minimum vertex cover is zero
        //  if tree is empty or there is only one node
        if (root == null)
            return 0;
        if (root.left == null && root.right == null)
            return 0;
  
        // If vertex cover for this node is
        // already evaluated, then return it
        // to save recomputation of same subproblem again.
        if (root.vc != 0)
            return root.vc;
  
        // Calculate size of vertex cover
        // when root is part of it
        let size_incl = 1 + vCover(root.left) +
                            vCover(root.right);
  
        // Calculate size of vertex cover
        // when root is not part of it
        let size_excl = 0;
        if (root.left != null)
            size_excl += 1 + vCover(root.left.left) +
                                vCover(root.left.right);
        if (root.right != null)
            size_excl += 1 + vCover(root.right.left) +
                                vCover(root.right.right);
  
        // Minimum of two values is vertex cover,
        // store it before returning
        root.vc = Math.min(size_incl, size_excl);
  
        return root.vc;
}
 
// Driver code
// Let us construct tree given in the above diagram
        let root = new Node(20);
        root.left = new Node(8);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);
        root.right = new Node(22);
        root.right.right = new Node(25);
  
        document.write("Size of the smallest vertex " +
                            "cover is ", vCover(root));
 
 
 
// This code is contributed by rag2127
 
</script>
 
 

Python3




# A binary tree node has data, pointer to left child and a pointer to
#   right child
 
 
class node:
 
    def __init__(self):
        # instance fields found by C++ to Python Converter:
        self.data = 0
        self.vc = 0
        self.left = None
        self.right = None
 
 
# Driver program to test above functions
def main():
    # Let us construct the tree given in the above diagram
    root = Globals.newNode(20)
    root.left = Globals.newNode(8)
    root.left.left = Globals.newNode(4)
    root.left.right = Globals.newNode(12)
    root.left.right.left = Globals.newNode(10)
    root.left.right.right = Globals.newNode(14)
    root.right = Globals.newNode(22)
    root.right.right = Globals.newNode(25)
 
    print("Size of the smallest vertex cover is ", end='')
    print(Globals.vCover(root), end='')
    print("\n", end='')
 
 
class Globals:
    # A utility function to find min of two integers
    @staticmethod
    def min(x, y):
        if(x < y):
            return x
        else:
            return y
 
    # A memoization based function that returns size of the minimum vertex cover.
 
    @staticmethod
    def vCover(root):
        # The size of minimum vertex cover is zero if tree is empty or there
        # is only one node
        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 0
 
        # If vertex cover for this node is already evaluated, then return it
        # to save recomputation of same subproblem again.
        if root.vc != 0:
            return root.vc
 
        # Calculate size of vertex cover when root is part of it
        size_incl = 1 + Globals.vCover(root.left) + Globals.vCover(root.right)
 
        # Calculate size of vertex cover when root is not part of it
        size_excl = 0
        if root.left:
            size_excl += 1 + \
                Globals.vCover(root.left.left) + \
                Globals.vCover(root.left.right)
        if root.right:
            size_excl += 1 + \
                Globals.vCover(root.right.left) + \
                Globals.vCover(root.right.right)
 
        # Minimum of two values is vertex cover, store it before returning
        root.vc = Globals.min(size_incl, size_excl)
 
        return root.vc
 
    # A utility function to create a node
    @staticmethod
    def newNode(data):
        temp = node()
        temp.data = data
        temp.left = temp.right = None
        temp.vc = 0  # Set the vertex cover as 0
        return temp
 
 
if __name__ == "__main__":
    main()
 
 
Output
Size of the smallest vertex cover is 3 

Time Complexity:
The time complexity of the vCover function is O(n), where n is the number of nodes in the binary tree. This is because each node is visited only once and its vertex cover size is calculated in constant time.

Space Complexity:
The space complexity of the program is O(n), where n is the number of nodes in the binary tree. This is because the space required for the binary tree is proportional to the number of nodes in the tree. Additionally, the memoization technique used in the vCover function requires additional space to store the vertex cover sizes of already evaluated nodes. However, since the depth of the recursion tree is limited by the height of the binary tree, the space complexity of the program is also O(h), where h is the height of the binary tree. In the worst case scenario where the binary tree is skewed, the height of the tree can be as large as n, which would result in a space complexity of O(n).

References: 
http://courses.csail.mit.edu/6.006/spring11/lectures/lec21.pdf
Exercise: 
Extend the above solution for n-ary trees. 

 

Approach for any general tree :

1. Approach will be same dynamic programming approach as discussed.

2. For every node, if we exclude this node from vertex cover than we have to include its neighbouring nodes,

   and if we include this node in the vertex cover than we will take the minimum of the two possibilities of taking its neighbouring

   nodes in the vertex cover to get minimum vertex cover. 

3. We will store the above information in the dp array.

C++




// C++ implementation for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// An utility function to add an edge in the tree
void addEdge(vector<int> adj[], int x, int y)
{
    adj[x].push_back(y);
    adj[y].push_back(x);
}
 
void dfs(vector<int> adj[], vector<int> dp[], int src,
         int par)
{
    for (auto child : adj[src]) {
        if (child != par)
            dfs(adj, dp, child, src);
    }
 
    for (auto child : adj[src]) {
        if (child != par) {
            // not including source in the vertex cover
            dp[src][0] += dp[child][1];
 
            // including source in the vertex cover
            dp[src][1] += min(dp[child][1], dp[child][0]);
        }
    }
}
 
// function to find minimum size of vertex cover
void minSizeVertexCover(vector<int> adj[], int N)
{
    vector<int> dp[N + 1];
 
    for (int i = 1; i <= N; i++) {
        // 0 denotes not included in vertex cover
        dp[i].push_back(0);
 
        // 1 denotes included in vertex cover
        dp[i].push_back(1);
    }
 
    dfs(adj, dp, 1, -1);
 
    // printing minimum size vertex cover
    cout << min(dp[1][0], dp[1][1]) << endl;
}
 
// Driver Code
int main()
{  
    /*                          1
   
                        /            \
  
                     2                7
  
               /             \
  
             3                6
  
    /        |        \
  
  4          8          5
    
 */
     
    // number of nodes in the tree
    int N = 8;
 
    // adjacency list representation of the tree
    vector<int> adj[N + 1];
 
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 7);
    addEdge(adj, 2, 3);
    addEdge(adj, 2, 6);
    addEdge(adj, 3, 4);
    addEdge(adj, 3, 8);
    addEdge(adj, 3, 5);
 
    minSizeVertexCover(adj, N);
 
    return 0;
}
 
 

Java




// Java implementation for the above approach
import java.util.*;
 
class GFG {
    // An utility function to add an edge in the tree
    static void addEdge(List<List<Integer> > adj, int x,
                        int y)
    {
        adj.get(x).add(y);
        adj.get(y).add(x);
    }
 
    static void dfs(List<List<Integer> > adj,
                    List<List<Integer> > dp, int src,
                    int par)
    {
        for (Integer child : adj.get(src)) {
            if (child != par)
                dfs(adj, dp, child, src);
        }
 
        for (Integer child : adj.get(src)) {
            if (child != par) {
                // not including source in the vertex cover
                dp.get(src).set(0,
                                dp.get(child).get(1)
                                    + dp.get(src).get(0));
 
                // including source in the vertex cover
                dp.get(src).set(
                    1,
                    dp.get(src).get(1)
                        + Math.min(dp.get(child).get(1),
                                   dp.get(child).get(0)));
            }
        }
    }
 
    // function to find minimum size of vertex cover
    static void minSizeVertexCover(List<List<Integer> > adj,
                                   int N)
    {
        List<List<Integer> > dp = new ArrayList<>();
        for (int i = 0; i <= N; i++) {
            dp.add(new ArrayList<>());
        }
        for (int i = 1; i <= N; i++) {
            // 0 denotes not included in vertex cover
            dp.get(i).add(0);
 
            // 1 denotes included in vertex cover
            dp.get(i).add(1);
        }
 
        dfs(adj, dp, 1, -1);
 
        // printing minimum size vertex cover
        System.out.println(
            Math.min(dp.get(1).get(0), dp.get(1).get(1)));
    }
 
    public static void main(String[] args)
    {
        /*                          1
 
                            /            \
 
                        2                7
 
                /             \
 
                3                6
 
        /        |        \
 
    4          8          5
 
    */
 
        // number of nodes in the tree
        int N = 8;
 
        // adjacency list representation of the tree
        List<List<Integer> > adj = new ArrayList<>();
        for (int i = 0; i <= N; i++) {
            adj.add(new ArrayList<>());
        }
        addEdge(adj, 1, 2);
        addEdge(adj, 1, 7);
        addEdge(adj, 2, 3);
        addEdge(adj, 2, 6);
        addEdge(adj, 3, 4);
        addEdge(adj, 3, 8);
        addEdge(adj, 3, 5);
 
        minSizeVertexCover(adj, N);
    }
}
 
 

Python3




# Python3 implementation for the above approach
 
 
def addEdge(adj, x, y):
    adj[x].append(y)
    adj[y].append(x)
 
 
def dfs(adj, dp, src, par):
    for child in adj[src]:
        if child != par:
            dfs(adj, dp, child, src)
 
    for child in adj[src]:
        if child != par:
            # not including source in the vertex cover
            dp[src][0] = dp[child][1] + dp[src][0]
 
            # including source in the vertex cover
            dp[src][1] = dp[src][1] + min(dp[child][1], dp[child][0])
 
 
def minSizeVertexCover(adj, N):
    dp = [[0 for j in range(2)] for i in range(N+1)]
    for i in range(1, N+1):
        # 0 denotes not included in vertex cover
        dp[i][0] = 0
 
        # 1 denotes included in vertex cover
        dp[i][1] = 1
 
    dfs(adj, dp, 1, -1)
 
    # printing minimum size vertex cover
    print(min(dp[1][0], dp[1][1]))
 
 
# Driver Code
"""
          1
        /   \
      2       7
     / \
    3   6
   /|\ 
  4 8 5
"""
# number of nodes in the tree
N = 8
 
# adjacency list representation of the tree
adj = [[] for i in range(N+1)]
addEdge(adj, 1, 2)
addEdge(adj, 1, 7)
addEdge(adj, 2, 3)
addEdge(adj, 2, 6)
addEdge(adj, 3, 4)
addEdge(adj, 3, 8)
addEdge(adj, 3, 5)
 
minSizeVertexCover(adj, N)
 
 

C#




using System;
using System.Collections.Generic;
 
class GFG
{
    // An utility function to add an edge in the tree
    static void addEdge(List<List<int>> adj, int x, int y)
    {
        adj[x].Add(y);
        adj[y].Add(x);
    }
 
    static void dfs(List<List<int>> adj, List<List<int>> dp, int src, int par)
    {
        foreach (int child in adj[src])
        {
            if (child != par)
                dfs(adj, dp, child, src);
        }
 
        foreach (int child in adj[src])
        {
            if (child != par)
            {
                // not including source in the vertex cover
                dp[src][0] = dp[child][1] + dp[src][0];
 
                // including source in the vertex cover
                dp[src][1] = dp[src][1] + Math.Min(dp[child][1], dp[child][0]);
            }
        }
    }
 
    // function to find minimum size of vertex cover
    static void minSizeVertexCover(List<List<int>> adj, int N)
    {
        List<List<int>> dp = new List<List<int>>();
        for (int i = 0; i <= N; i++)
        {
            dp.Add(new List<int>());
        }
        for (int i = 1; i <= N; i++)
        {
            // 0 denotes not included in vertex cover
            dp[i].Add(0);
 
            // 1 denotes included in vertex cover
            dp[i].Add(1);
        }
 
        dfs(adj, dp, 1, -1);
 
        // printing minimum size vertex cover
        Console.WriteLine(Math.Min(dp[1][0], dp[1][1]));
    }
 
    public static void Main(string[] args)
    {
        /*
                            1
 
                            /            \
 
                        2                7
 
                /             \
 
                3                6
 
        /        |        \
 
    4          8          5
 
    */
 
        // number of nodes in the tree
        int N = 8;
 
        // adjacency list representation of the tree
        List<List<int>> adj = new List<List<int>>();
        for (int i = 0; i <= N; i++)
        {
            adj.Add(new List<int>());
        }
        addEdge(adj, 1, 2);
        addEdge(adj, 1, 7);
        addEdge(adj, 2, 3);
        addEdge(adj, 2, 6);
        addEdge(adj, 3, 4);
        addEdge(adj, 3, 8);
        addEdge(adj, 3, 5);
 
        minSizeVertexCover(adj, N);
    }
}
 
 

Javascript




// Javascript implementation for the above approach
 
      // An utility function to add an edge in the tree
      function addEdge(adj, x, y) {
        adj[x].push(y);
        adj[y].push(x);
      }
 
      function dfs(adj, dp, src, par) {
        for (let child of adj[src]) {
          if (child != par) dfs(adj, dp, child, src);
        }
 
        for (let child of adj[src]) {
          if (child != par) {
            // not including source in the vertex cover
            dp[src][0] += dp[child][1];
 
            // including source in the vertex cover
            dp[src][1] += Math.min(dp[child][1], dp[child][0]);
          }
        }
      }
 
      // function to find minimum size of vertex cover
      function minSizeVertexCover(adj, N) {
        let dp = Array.from(Array(N + 1), () => new Array());
 
        for (var i = 1; i <= N; i++) {
          // 0 denotes not included in vertex cover
          dp[i].push(0);
 
          // 1 denotes included in vertex cover
          dp[i].push(1);
        }
 
        dfs(adj, dp, 1, -1);
 
        // printing minimum size vertex cover
        console.log(Math.min(dp[1][0], dp[1][1]));
      }
 
      // Driver Code
 
      /*                          1
 
                                /            \
 
                             2                7
 
                       /             \
 
                     3                6
 
            /        |        \
 
          4          8          5
 
         */
 
      // number of nodes in the tree
      var N = 8;
 
      // adjacency list representation of the tree
      let adj = Array.from(Array(N + 1), () => new Array());
 
      addEdge(adj, 1, 2);
      addEdge(adj, 1, 7);
      addEdge(adj, 2, 3);
      addEdge(adj, 2, 6);
      addEdge(adj, 3, 4);
      addEdge(adj, 3, 8);
      addEdge(adj, 3, 5);
 
      minSizeVertexCover(adj, N);
 
 
Output
3

Time Complexity : O(N)
Auxiliary space : O(N)



Next Article
Tile Stacking Problem

U

Udit Gupta
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • NPHard
Practice Tags :
  • Dynamic Programming

Similar Reads

  • Dynamic Programming or DP
    Dynamic Programming is an algorithmic technique with the following properties. It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
    3 min read
  • What is Memoization? A Complete Tutorial
    In this tutorial, we will dive into memoization, a powerful optimization technique that can drastically improve the performance of certain algorithms. Memoization helps by storing the results of expensive function calls and reusing them when the same inputs occur again. This avoids redundant calcula
    6 min read
  • Dynamic Programming (DP) Introduction
    Dynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again. The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way
    15+ min read
  • Tabulation vs Memoization
    Tabulation and memoization are two techniques used to implement dynamic programming. Both techniques are used when there are overlapping subproblems (the same subproblem is executed multiple times). Below is an overview of two approaches. Memoization:Top-down approachStores the results of function c
    9 min read
  • Optimal Substructure Property in Dynamic Programming | DP-2
    The following are the two main properties of a problem that suggest that the given problem can be solved using Dynamic programming: 1) Overlapping Subproblems 2) Optimal Substructure We have already discussed the Overlapping Subproblem property. Let us discuss the Optimal Substructure property here.
    4 min read
  • Overlapping Subproblems Property in Dynamic Programming | DP-1
    Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems using recursion and storing the results of subproblems to avoid computing the same results again. Following are the two main properties of a problem that suggests that the given problem
    10 min read
  • Steps to solve a Dynamic Programming Problem
    Steps to solve a Dynamic programming problem:Identify if it is a Dynamic programming problem.Decide a state expression with the Least parameters.Formulate state and transition relationship.Apply tabulation or memorization.Step 1: How to classify a problem as a Dynamic Programming Problem? Typically,
    14 min read
  • Advanced Topics

    • Count Ways To Assign Unique Cap To Every Person
      Given n people and 100 types of caps labelled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps. Example: Input: caps = [[3, 4], [4, 5], [5]] Outpu
      15+ min read

    • Digit DP | Introduction
      Prerequisite : How to solve a Dynamic Programming Problem ?There are many types of problems that ask to count the number of integers 'x' between two integers say 'a' and 'b' such that x satisfies a specific property that can be related to its digits.So, if we say G(x) tells the number of such intege
      14 min read

    • Sum over Subsets | Dynamic Programming
      Prerequisite: Basic Dynamic Programming, Bitmasks Consider the following problem where we will use Sum over subset Dynamic Programming to solve it. Given an array of 2n integers, we need to calculate function F(x) = ?Ai such that x&i==i for all x. i.e, i is a bitwise subset of x. i will be a bit
      10 min read

    Easy problems in Dynamic programming

    • Coin Change - Count Ways to Make Sum
      Given an integer array of coins[] of size n representing different types of denominations and an integer sum, the task is to count all combinations of coins to make a given value sum. Note: Assume that you have an infinite supply of each type of coin. Examples: Input: sum = 4, coins[] = [1, 2, 3]Out
      15+ min read

    • Subset Sum Problem
      Given an array arr[] of non-negative integers and a value sum, the task is to check if there is a subset of the given array whose sum is equal to the given sum. Examples: Input: arr[] = [3, 34, 4, 12, 5, 2], sum = 9Output: TrueExplanation: There is a subset (4, 5) with sum 9. Input: arr[] = [3, 34,
      15+ min read

    • Introduction and Dynamic Programming solution to compute nCr%p
      Given three numbers n, r and p, compute value of nCr mod p. Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6.We strongly recommend that you click here and practice it, before moving on to the solution.METHOD 1: (Using Dynamic Programming) A Simple Solution is
      15+ min read

    • Rod Cutting
      Given a rod of length n inches and an array price[]. price[i] denotes the value of a piece of length i. The task is to determine the maximum value obtainable by cutting up the rod and selling the pieces. Note: price[] is 1-indexed array. Input: price[] = [1, 5, 8, 9, 10, 17, 17, 20]Output: 22Explana
      15+ min read

    • Painting Fence Algorithm
      Given a fence with n posts and k colors, the task is to find out the number of ways of painting the fence so that not more than two consecutive posts have the same color. Examples: Input: n = 2, k = 4Output: 16Explanation: We have 4 colors and 2 posts.Ways when both posts have same color: 4 Ways whe
      15 min read

    • Longest Common Subsequence (LCS)
      Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
      15+ min read

    • Longest Increasing Subsequence (LIS)
      Given an array arr[] of size n, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e., the longest possible subsequence in which the elements of the subsequence are sorted in increasing order. Examples: Input: arr[] = [3, 10, 2, 1, 20]Output: 3Explanation: The longest incre
      14 min read

    • Longest subsequence such that difference between adjacents is one
      Given an array arr[] of size n, the task is to find the longest subsequence such that the absolute difference between adjacent elements is 1. Examples: Input: arr[] = [10, 9, 4, 5, 4, 8, 6]Output: 3Explanation: The three possible subsequences of length 3 are [10, 9, 8], [4, 5, 4], and [4, 5, 6], whe
      15+ min read

    • Maximum size square sub-matrix with all 1s
      Given a binary matrix mat of size n * m, the task is to find out the maximum length of a side of a square sub-matrix with all 1s. Example: Input: mat = [ [0, 1, 1, 0, 1], [1, 1, 0, 1, 0], [0, 1, 1, 1, 0], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0] ] Output: 3Explanation: The maximum length of
      15+ min read

    • Min Cost Path
      You are given a 2D matrix cost[][] of dimensions m × n, where each cell represents the cost of traversing through that position. Your goal is to determine the minimum cost required to reach the bottom-right cell (m-1, n-1) starting from the top-left cell (0,0).The total cost of a path is the sum of
      15+ min read

    • Longest Common Substring (Space optimized DP solution)
      Given two strings ‘s1‘ and ‘s2‘, find the length of the longest common substring. Example: Input: s1 = “GeeksforGeeks”, s2 = “GeeksQuiz” Output : 5 Explanation:The longest common substring is “Geeks” and is of length 5. Input: s1 = “abcdxyz”, s2 = “xyzabcd” Output : 4Explanation:The longest common s
      7 min read

    • Count ways to reach the nth stair using step 1, 2 or 3
      A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. The task is to implement a method to count how many possible ways the child can run up the stairs. Examples: Input: 4Output: 7Explanation: There are seven ways: {1, 1, 1, 1}, {1, 2, 1}, {2, 1, 1}
      15+ min read

    • Grid Unique Paths - Count Paths in matrix
      Given an matrix of size m x n, the task is to find the count of all unique possible paths from top left to the bottom right with the constraints that from each cell we can either move only to the right or down. Examples: Input: m = 2, n = 2Output: 2Explanation: There are two paths(0, 0) -> (0, 1)
      15+ min read

    • Unique paths in a Grid with Obstacles
      Given a grid[][] of size m * n, let us assume we are starting at (1, 1) and our goal is to reach (m, n). At any instance, if we are on (x, y), we can either go to (x, y + 1) or (x + 1, y). The task is to find the number of unique paths if some obstacles are added to the grid.Note: An obstacle and sp
      15+ min read

    Medium problems on Dynamic programming

    • 0/1 Knapsack Problem
      Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
      15+ min read

    • Printing Items in 0/1 Knapsack
      Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays, val[0..n-1] and wt[0..n-1] represent values and weights associated with n items respectively. Also given an integer W which repre
      12 min read

    • Unbounded Knapsack (Repetition of items allowed)
      Given a knapsack weight, say capacity and a set of n items with certain value vali and weight wti, The task is to fill the knapsack in such a way that we can get the maximum profit. This is different from the classical Knapsack problem, here we are allowed to use an unlimited number of instances of
      15+ min read

    • Egg Dropping Puzzle | DP-11
      You are given n identical eggs and you have access to a k-floored building from 1 to k. There exists a floor f where 0 <= f <= k such that any egg dropped from a floor higher than f will break, and any egg dropped from or below floor f will not break. There are a few rules given below: An egg
      15+ min read

    • Word Break
      Given a string s and y a dictionary of n words dictionary, check if s can be segmented into a sequence of valid words from the dictionary, separated by spaces. Examples: Input: s = "ilike", dictionary[] = ["i", "like", "gfg"]Output: trueExplanation: The string can be segmented as "i like". Input: s
      12 min read

    • Vertex Cover Problem (Dynamic Programming Solution for Tree)
      A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complet
      15+ min read

    • Tile Stacking Problem
      Given integers n (the height of the tower), m (the maximum size of tiles available), and k (the maximum number of times each tile size can be used), the task is to calculate the number of distinct stable towers of height n that can be built. Note: A stable tower consists of exactly n tiles, each sta
      15+ min read

    • Box Stacking Problem
      Given three arrays height[], width[], and length[] of size n, where height[i], width[i], and length[i] represent the dimensions of a box. The task is to create a stack of boxes that is as tall as possible, but we can only stack a box on top of another box if the dimensions of the 2-D base of the low
      15+ min read

    • Partition a Set into Two Subsets of Equal Sum
      Given an array arr[], the task is to check if it can be partitioned into two parts such that the sum of elements in both parts is the same.Note: Each element is present in either the first subset or the second subset, but not in both. Examples: Input: arr[] = [1, 5, 11, 5]Output: true Explanation: T
      15+ min read

    • Travelling Salesman Problem using Dynamic Programming
      Given a 2d matrix cost[][] of size n where cost[i][j] denotes the cost of moving from city i to city j. The task is to complete a tour from city 0 (0-based index) to all other cities such that we visit each city exactly once and then at the end come back to city 0 at minimum cost. Note the differenc
      15 min read

    • Longest Palindromic Subsequence (LPS)
      Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Examples: Input: s = "bbabcbcab"Output: 7Explanation: Subsequence "babcbab" is the longest su
      15+ min read

    • Longest Common Increasing Subsequence (LCS + LIS)
      Given two arrays, a[] and b[], find the length of the longest common increasing subsequence(LCIS). LCIS refers to a subsequence that is present in both arrays and strictly increases.Prerequisites: LCS, LIS. Examples: Input: a[] = [3, 4, 9, 1], b[] = [5, 3, 8, 9, 10, 2, 1]Output: 2Explanation: The lo
      15+ min read

    • Find all distinct subset (or subsequence) sums of an array
      Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small. Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
      15+ min read

    • Weighted Job Scheduling
      Given a 2D array jobs[][] of order n*3, where each element jobs[i] defines start time, end time, and the profit associated with the job. The task is to find the maximum profit you can take such that there are no two jobs with overlapping time ranges. Note: If the job ends at time X, it is allowed to
      15+ min read

    • Count Derangements (Permutation such that no element appears in its original position)
      A Derangement is a permutation of n elements, such that no element appears in its original position. For example, a derangement of [0, 1, 2, 3] is [2, 3, 1, 0].Given a number n, find the total number of Derangements of a set of n elements. Examples : Input: n = 2Output: 1Explanation: For two balls [
      12 min read

    • Minimum insertions to form a palindrome
      Given a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Examples: Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions. Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic str
      15+ min read

    • Ways to arrange Balls such that adjacent balls are of different types
      There are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of the same type are adjacent.Examples : Input: p = 1, q = 1, r = 0Output: 2Explanation: There are only two arrangements PQ and QP Input: p = 1, q = 1,
      15+ min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences