text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Types of Linked List | Structure of the list | struct link { int info ; struct link * next ; } ; |
Remove all even parity nodes from a Doubly and Circular Singly Linked List | C ++ implementation to remove all the Even Parity Nodes from a doubly linked list ; Node of the doubly linked list ; Function to insert a node at the beginning of the Doubly Linked List ; Allocate the node ; Insert the data ; Since we are adding at the beginning , prev is always NULL ; Link the old list off the new node ; Change the prev of head node to new node ; Move the head to point to the new node ; Function that returns true if count of set bits in x is even ; parity will store the count of set bits ; Function to delete a node in a Doubly Linked List . head_ref -- > pointer to head node pointer . del -- > pointer to node to be deleted ; Base case ; If the node to be deleted is head node ; Change next only if node to be deleted is not the last node ; Change prev only if node to be deleted is not the first node ; Finally , free the memory occupied by del ; Function to to remove all the Even Parity Nodes from a doubly linked list ; Iterating through the linked list ; If node ' s β data ' s parity is even ; Function to print nodes in a given doubly linked list ; Driver Code ; Create the doubly linked list 18 < -> 15 < -> 8 < -> 9 < -> 14 ; Uncomment to view the list cout << " Original β List : β " ; printList ( head ) ; ; Modified List | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * prev , * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = ( Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> prev = NULL ; new_node -> next = ( * head_ref ) ; if ( ( * head_ref ) != NULL ) ( * head_ref ) -> prev = new_node ; ( * head_ref ) = new_node ; } bool isEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { if ( x & 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return true ; else return false ; } void deleteNode ( Node * * head_ref , Node * del ) { if ( * head_ref == NULL del == NULL ) return ; if ( * head_ref == del ) * head_ref = del -> next ; if ( del -> next != NULL ) del -> next -> prev = del -> prev ; if ( del -> prev != NULL ) del -> prev -> next = del -> next ; free ( del ) ; return ; } void deleteEvenParityNodes ( Node * * head_ref ) { Node * ptr = * head_ref ; Node * next ; while ( ptr != NULL ) { next = ptr -> next ; if ( isEvenParity ( ptr -> data ) ) deleteNode ( head_ref , ptr ) ; ptr = next ; } } void printList ( Node * head ) { if ( head == NULL ) { cout << " Empty β list STRNEWLINE " ; return ; } while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { Node * head = NULL ; push ( & head , 14 ) ; push ( & head , 9 ) ; push ( & head , 8 ) ; push ( & head , 15 ) ; push ( & head , 18 ) ; deleteEvenParityNodes ( & head ) ; printList ( head ) ; } |
Remove all even parity nodes from a Doubly and Circular Singly Linked List | C ++ program to remove all the Even Parity Nodes from a circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; Create a new node and make head as next of it . ; If linked list is not NULL then set the next of last node ; Find the node before head and update next of it . ; Point for the first node ; Function to delete the node from a Circular Linked list ; If node to be deleted is head node ; Traverse list till not found delete node ; Copy the address of the node ; Finally , free the memory occupied by del ; Function that returns true if count of set bits in x is even ; parity will store the count of set bits ; Function to delete all the Even Parity Nodes from the singly circular linked list ; Traverse the list till the end ; If the node ' s β data β has β even β parity , β β delete β node β ' ptr ' ; Point to the next node ; Function to print nodes in a given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 11 -> 9 -> 34 -> 6 -> 13 -> 21 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } void deleteNode ( Node * & head_ref , Node * del ) { if ( head_ref == del ) head_ref = del -> next ; struct Node * temp = head_ref ; while ( temp -> next != del ) { temp = temp -> next ; } temp -> next = del -> next ; free ( del ) ; return ; } bool isEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { if ( x & 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return true ; else return false ; } void deleteEvenParityNodes ( Node * & head ) { if ( head == NULL ) return ; if ( head == head -> next ) { if ( isEvenParity ( head -> data ) ) head = NULL ; return ; } struct Node * ptr = head ; struct Node * next ; do { next = ptr -> next ; if ( isEvenParity ( ptr -> data ) ) deleteNode ( head , ptr ) ; ptr = next ; } while ( ptr != head ) ; if ( head == head -> next ) { if ( isEvenParity ( head -> data ) ) head = NULL ; return ; } } void printList ( struct Node * head ) { if ( head == NULL ) { cout << " Empty β List STRNEWLINE " ; return ; } struct Node * temp = head ; if ( head != NULL ) { do { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } while ( temp != head ) ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 21 ) ; push ( & head , 13 ) ; push ( & head , 6 ) ; push ( & head , 34 ) ; push ( & head , 9 ) ; push ( & head , 11 ) ; deleteEvenParityNodes ( head ) ; printList ( head ) ; return 0 ; } |
Remove all the Even Digit Sum Nodes from a Circular Singly Linked List | C ++ program to remove all the Even Digit Sum Nodes from a circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; Create a new node and make head as next of it . ; If linked list is not NULL then set the next of last node ; Find the node before head and update next of it . ; Point for the first node ; Function to delete the node from a Circular Linked list ; If node to be deleted is head node ; Traverse list till not found delete node ; Copy the address of the node ; Finally , free the memory occupied by del ; Function to find the digit sum for a number ; Function to delete all the Even Digit Sum Nodes from the singly circular linked list ; Traverse the list till the end ; If the node ' s β data β is β Fibonacci , β β delete β node β ' ptr ' ; Point to the next node ; Function to print nodes in a given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 9 -> 11 -> 34 -> 6 -> 13 -> 21 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } void deleteNode ( Node * head_ref , Node * del ) { struct Node * temp = head_ref ; if ( head_ref == del ) head_ref = del -> next ; while ( temp -> next != del ) { temp = temp -> next ; } temp -> next = del -> next ; free ( del ) ; return ; } int digitSum ( int num ) { int sum = 0 ; while ( num ) { sum += ( num % 10 ) ; num /= 10 ; } return sum ; } void deleteEvenDigitSumNodes ( Node * head ) { struct Node * ptr = head ; struct Node * next ; do { if ( ! ( digitSum ( ptr -> data ) & 1 ) ) deleteNode ( head , ptr ) ; next = ptr -> next ; ptr = next ; } while ( ptr != head ) ; } void printList ( struct Node * head ) { struct Node * temp = head ; if ( head != NULL ) { do { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } while ( temp != head ) ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 21 ) ; push ( & head , 13 ) ; push ( & head , 6 ) ; push ( & head , 34 ) ; push ( & head , 11 ) ; push ( & head , 9 ) ; deleteEvenDigitSumNodes ( head ) ; printList ( head ) ; return 0 ; } |
Remove all Fibonacci Nodes from a Circular Singly Linked List | C ++ program to delete all the Fibonacci nodes from the circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; Create a new node and make head as next of it . ; If linked list is not NULL then set the next of last node ; Find the node before head and update next of it . ; Point for the first node ; Delete the node from a Circular Linked list ; If node to be deleted is head node ; Traverse list till not found delete node ; Copy the address of the node ; Finally , free the memory occupied by del ; Function to find the maximum node of the circular linked list ; Pointer for traversing ; Initialize head to the current pointer ; Initialize min int value to max ; While the last node is not reached ; If current node data is greater for max then replace it ; Function to create hash table to check Fibonacci numbers ; Adding the first two elements to the hash ; Inserting the Fibonacci numbers into the hash ; Function to delete all the Fibonacci nodes from the singly circular linked list ; Find the largest node value in Circular Linked List ; Creating a hash containing all the Fibonacci numbers upto the maximum data value in the circular linked list ; Traverse the list till the end ; If the node ' s β data β is β Fibonacci , β β delete β node β ' ptr ' ; Point to the next node ; Function to print nodes in a given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 9 -> 11 -> 34 -> 6 -> 13 -> 20 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } void deleteNode ( Node * head_ref , Node * del ) { struct Node * temp = head_ref ; if ( head_ref == del ) head_ref = del -> next ; while ( temp -> next != del ) { temp = temp -> next ; } temp -> next = del -> next ; free ( del ) ; return ; } int largestElement ( struct Node * head_ref ) { struct Node * current ; current = head_ref ; int maxEle = INT_MIN ; do { if ( current -> data > maxEle ) { maxEle = current -> data ; } current = current -> next ; } while ( current != head_ref ) ; return maxEle ; } void createHash ( set < int > & hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . insert ( prev ) ; hash . insert ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . insert ( temp ) ; prev = curr ; curr = temp ; } } void deleteFibonacciNodes ( Node * head ) { int maxEle = largestElement ( head ) ; set < int > hash ; createHash ( hash , maxEle ) ; struct Node * ptr = head ; struct Node * next ; do { if ( hash . find ( ptr -> data ) != hash . end ( ) ) deleteNode ( head , ptr ) ; next = ptr -> next ; ptr = next ; } while ( ptr != head ) ; } void printList ( struct Node * head ) { struct Node * temp = head ; if ( head != NULL ) { do { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } while ( temp != head ) ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 13 ) ; push ( & head , 6 ) ; push ( & head , 34 ) ; push ( & head , 11 ) ; push ( & head , 9 ) ; deleteFibonacciNodes ( head ) ; printList ( head ) ; return 0 ; } |
Delete all odd nodes of a Circular Linked List | C ++ program to delete all odd node from a Circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not NULL then set the next of last node ; For the first node ; Delete the node if it is odd ; If node to be deleted is head node ; Traverse list till not found delete node ; Copy address of node ; Finally , free the memory occupied by del ; Function to delete all odd nodes from the singly circular linked list ; Traverse list till the end if the node is odd then delete it ; if node is odd ; point to next node ; Function to print nodes ; Driver code ; Initialize lists as empty ; Created linked list will be 56 -> 61 -> 57 -> 11 -> 12 -> 2 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } void deleteNode ( Node * head_ref , Node * del ) { struct Node * temp = head_ref ; if ( head_ref == del ) head_ref = del -> next ; while ( temp -> next != del ) { temp = temp -> next ; } temp -> next = del -> next ; free ( del ) ; return ; } void deleteoddNodes ( Node * head ) { struct Node * ptr = head ; struct Node * next ; do { if ( ( ptr -> data % 2 ) == 1 ) deleteNode ( head , ptr ) ; next = ptr -> next ; ptr = next ; } while ( ptr != head ) ; } void printList ( struct Node * head ) { struct Node * temp = head ; if ( head != NULL ) { do { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } while ( temp != head ) ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 2 ) ; push ( & head , 12 ) ; push ( & head , 11 ) ; push ( & head , 57 ) ; push ( & head , 61 ) ; push ( & head , 56 ) ; cout << " List after deletion : " ; deleteoddNodes ( head ) ; printList ( head ) ; return 0 ; } |
Insertion in a sorted circular linked list when a random pointer is given | C ++ implementation of the approach ; Node structure ; Function to create a node ; Function to find and return the head ; If the list is empty ; Finding the last node of the linked list the last node must have the highest value if no such element is present then all the nodes of the linked list must be same ; Return the head ; Function to insert a new_node in the list in sorted fashion Note that this function expects a pointer to head node as this can modify the head of the input linked list ; If the list is empty ; If the node to be inserted is the smallest then it has to be the new head ; Find the last node of the list as it will be pointing to the head ; Locate the node before the point of insertion ; Return the new head ; Function to print the nodes of the linked list ; Driver code ; Start with an empty linked list ; Create linked list from the given array ; Move to a random node if it exists ; Print the contents of the created list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * next ; int data ; } ; Node * create ( ) { Node * new_node = ( Node * ) malloc ( sizeof ( Node ) ) ; new_node -> next = NULL ; return new_node ; } Node * find_head ( Node * random ) { if ( random == NULL ) return NULL ; Node * head , * var = random ; while ( ! ( var -> data > var -> next -> data var -> next == random ) ) { var = var -> next ; } return var -> next ; } Node * sortedInsert ( Node * head_ref , Node * new_node ) { Node * current = head_ref ; if ( current == NULL ) { new_node -> next = new_node ; head_ref = new_node ; } else if ( current -> data >= new_node -> data ) { while ( current -> next != head_ref ) current = current -> next ; current -> next = new_node ; new_node -> next = head_ref ; head_ref = new_node ; } else { while ( current -> next != head_ref && current -> next -> data < new_node -> data ) { current = current -> next ; } new_node -> next = current -> next ; current -> next = new_node ; } return head_ref ; } void printList ( Node * start ) { Node * temp ; if ( start != NULL ) { temp = start ; do { cout << temp -> data << " β " ; temp = temp -> next ; } while ( temp != start ) ; } } int main ( ) { int arr [ ] = { 12 , 56 , 2 , 11 , 1 , 90 } ; int list_size , i ; Node * start = NULL ; Node * temp ; for ( i = 0 ; i < 6 ; i ++ ) { if ( start != NULL ) for ( int j = 0 ; j < ( rand ( ) % 10 ) ; j ++ ) start = start -> next ; temp = create ( ) ; temp -> data = arr [ i ] ; start = sortedInsert ( find_head ( start ) , temp ) ; } printList ( find_head ( start ) ) ; return 0 ; } |
Splitting starting N nodes into new Circular Linked List while preserving the old nodes | C ++ implementation of the approach ; Function to add a node to the empty list ; If not empty ; Creating a node dynamically ; Assigning the data ; Creating the link ; Function to add a node to the beginning of the list ; If list is empty ; Create node ; Assign data ; Function to traverse and print the list ; If list is empty ; Pointing to the first Node of the list ; Traversing the list ; Function to find the length of the CircularLinkedList ; Stores the length ; List is empty ; Iterator Node to traverse the List ; Return the length of the list ; Function to split the first k nodes into a new CircularLinkedList and the remaining nodes stay in the original CircularLinkedList ; Empty Node for reference ; Check if the list is empty If yes , then return NULL ; NewLast will contain the last node of the new split list itr to iterate the node till the required node ; Update NewLast to the required node and link the last to the start of rest of the list ; Return the last node of the required list ; Driver code ; Create a new list for the starting k nodes ; Append the new last node into the new list ; Print the new lists | #include <bits/stdc++.h> NEW_LINE using namespace std ; class CircularLinkedList { public : struct Node { int data ; Node * next ; } ; Node * last ; Node * addToEmpty ( int data ) { if ( last != NULL ) return last ; Node * temp = new Node ( ) ; temp -> data = data ; last = temp ; last -> next = last ; return last ; } Node * addBegin ( int data ) { if ( last == NULL ) return addToEmpty ( data ) ; Node * temp = new Node ( ) ; temp -> data = data ; temp -> next = last -> next ; last -> next = temp ; return last ; } void traverse ( ) { Node * p ; if ( last == NULL ) { cout << ( " List β is β empty . " ) ; return ; } p = last -> next ; do { cout << p -> data << " β " ; p = p -> next ; } while ( p != last -> next ) ; cout << endl ; } int length ( ) { int x = 0 ; if ( last == NULL ) return x ; Node * itr = last -> next ; while ( itr -> next != last -> next ) { x ++ ; itr = itr -> next ; } return ( x + 1 ) ; } Node * split ( int k ) { Node * pass = new Node ( ) ; if ( last == NULL ) return last ; Node * newLast , * itr = last ; for ( int i = 0 ; i < k ; i ++ ) { itr = itr -> next ; } newLast = itr ; pass -> next = itr -> next ; newLast -> next = last -> next ; last -> next = pass -> next ; return newLast ; } } ; int main ( ) { CircularLinkedList * clist = new CircularLinkedList ( ) ; clist -> last = NULL ; clist -> addToEmpty ( 12 ) ; clist -> addBegin ( 10 ) ; clist -> addBegin ( 8 ) ; clist -> addBegin ( 6 ) ; clist -> addBegin ( 4 ) ; clist -> addBegin ( 2 ) ; cout << ( " Original β list : " ) ; clist -> traverse ( ) ; int k = 4 ; CircularLinkedList * clist2 = new CircularLinkedList ( ) ; clist2 -> last = clist -> split ( k ) ; cout << ( " The β new β lists β are : " ) ; clist2 -> traverse ( ) ; clist -> traverse ( ) ; } |
Convert a given Binary Tree to Circular Doubly Linked List | Set 2 | A C ++ program for conversion of Binary Tree to CDLL ; A binary tree node has data , and left and right pointers ; Function to perform In - Order traversal of the tree and store the nodes in a vector ; first recur on left child ; append the data of node in vector ; now recur on right child ; Function to convert Binary Tree to Circular Doubly Linked list using the vector which stores In - Order traversal of the Binary Tree ; Base cases ; Vector to be used for storing the nodes of tree in In - order form ; Calling the In - Order traversal function ; Create the head of the linked list pointing to the root of the tree ; Create a current pointer to be used in traversal ; Traversing the nodes of the tree starting from the second elements ; Create a temporary pointer pointing to current ; Current 's right points to the current node in traversal ; Current points to its right ; Current 's left points to temp ; Current 's right points to head of the list ; Head 's left points to current ; Return head of the list ; Display Circular Link List ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; Node ( int x ) { data = x ; left = right = NULL ; } } ; void inorder ( Node * root , vector < int > & v ) { if ( ! root ) return ; inorder ( root -> left , v ) ; v . push_back ( root -> data ) ; inorder ( root -> right , v ) ; } Node * bTreeToCList ( Node * root ) { if ( root == NULL ) return NULL ; vector < int > v ; inorder ( root , v ) ; Node * head_ref = new Node ( v [ 0 ] ) ; Node * curr = head_ref ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) { Node * temp = curr ; curr -> right = new Node ( v [ i ] ) ; curr = curr -> right ; curr -> left = temp ; } curr -> right = head_ref ; head_ref -> left = curr ; return head_ref ; } void displayCList ( Node * head ) { cout << " Circular β Doubly β Linked β List β is β : STRNEWLINE " ; Node * itr = head ; do { cout << itr -> data << " β " ; itr = itr -> right ; } while ( head != itr ) ; cout << " STRNEWLINE " ; } int main ( ) { Node * root = new Node ( 10 ) ; root -> left = new Node ( 12 ) ; root -> right = new Node ( 15 ) ; root -> left -> left = new Node ( 25 ) ; root -> left -> right = new Node ( 30 ) ; root -> right -> left = new Node ( 36 ) ; Node * head = bTreeToCList ( root ) ; displayCList ( head ) ; return 0 ; } |
Delete all odd or even positioned nodes from Circular Linked List | Function to delete that all node whose index position is odd ; check list have any node if not then return ; if list have single node means odd position then delete it ; traverse first to last if list have more than one node ; delete first position node which is odd position ; Function to delete first node ; check position is odd or not if yes then delete node | void DeleteAllOddNode ( struct Node * * head ) { int len = Length ( * head ) ; int count = 0 ; struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " Delete Last List is empty " return ; } if ( len == 1 ) { DeleteFirst ( head ) ; return ; } while ( len > 0 ) { if ( count == 0 ) { DeleteFirst ( head ) ; } if ( count % 2 == 0 && count != 0 ) { deleteNode ( * head , previous ) ; } previous = previous -> next ; next = previous -> next ; len -- ; count ++ ; } return ; } |
Delete all odd or even positioned nodes from Circular Linked List | Function to delete all even position nodes ; Take size of list ; Check list is empty if empty simply return ; if list have single node then return ; make first node is previous ; make second node is current ; check node number is even if node is even then delete that node | void DeleteAllEvenNode ( struct Node * * head ) { int len = Length ( * head ) ; int count = 1 ; struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( len < 2 ) { return ; } previous = * head ; next = previous -> next ; while ( len > 0 ) { if ( count % 2 == 0 ) { previous -> next = next -> next ; free ( next ) ; previous = next -> next ; next = previous -> next ; } len -- ; count ++ ; } return ; } |
Delete all odd or even positioned nodes from Circular Linked List | C ++ program to delete all even and odd position nodes from Singly Circular Linked list ; structure for a node ; Function return number of nodes present in list ; if list is empty simply return length zero ; traverse forst to last node ; Function print data of list ; if list is empty simply show message ; traverse forst to last node ; Function to insert a node at the end of a Circular linked list ; Create a new node ; check node is created or not ; insert data into newly created node ; check list is empty if not have any node then make first node it ; if list have already some node ; move firt node to last node ; put first or head node address in new node link ; put new node address into last node link ( next ) ; Utitlity function to delete a Node ; If node to be deleted is head node ; traverse list till not found delete node ; copy address of node ; Finally , free the memory occupied by del ; Function to delete First node of Circular Linked List ; check list have any node if not then return ; check list have single node if yes then delete it and return ; traverse second to first ; now previous is last node and next is first node of list first node ( next ) link address put in last node ( previous ) link ; make second node as head node ; Function to delete odd position nodes ; check list have any node if not then return ; if list have single node means odd position then delete it ; traverse first to last if list have more than one node ; delete first position node which is odd position ; Function to delete first node ; check position is odd or not if yes then delete node Note : Considered 1 based indexing ; Function to delete all even position nodes ; Take size of list ; Check list is empty if empty simply return ; if list have single node then return ; make first node is previous ; make second node is current ; check node number is even if node is even then delete that node ; Driver Code ; Deleting Odd positioned nodes ; Deleting Even positioned nodes | #include <bits/stdc++.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; int Length ( struct Node * head ) { struct Node * current = head ; int count = 0 ; if ( head == NULL ) { return 0 ; } else { do { current = current -> next ; count ++ ; } while ( current != head ) ; } return count ; } void Display ( struct Node * head ) { struct Node * current = head ; if ( head == NULL ) { printf ( " Display List is empty " return ; } else { do { printf ( " % d β " , current -> data ) ; current = current -> next ; } while ( current != head ) ; } } void Insert ( struct Node * * head , int data ) { struct Node * current = * head ; struct Node * newNode = new Node ; if ( ! newNode ) { printf ( " Memory Error " return ; } newNode -> data = data ; if ( * head == NULL ) { newNode -> next = newNode ; * head = newNode ; return ; } else { while ( current -> next != * head ) { current = current -> next ; } newNode -> next = * head ; current -> next = newNode ; } } void deleteNode ( struct Node * head_ref , struct Node * del ) { struct Node * temp = head_ref ; if ( head_ref == del ) { head_ref = del -> next ; } while ( temp -> next != del ) { temp = temp -> next ; } temp -> next = del -> next ; free ( del ) ; return ; } void DeleteFirst ( struct Node * * head ) { struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( previous -> next == previous ) { * head = NULL ; return ; } while ( previous -> next != * head ) { previous = previous -> next ; next = previous -> next ; } previous -> next = next -> next ; * head = previous -> next ; free ( next ) ; return ; } void DeleteAllOddNode ( struct Node * * head ) { int len = Length ( * head ) ; int count = 0 ; struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " Delete Last List is empty " return ; } if ( len == 1 ) { DeleteFirst ( head ) ; return ; } while ( len > 0 ) { if ( count == 0 ) { DeleteFirst ( head ) ; } if ( count % 2 == 0 && count != 0 ) { deleteNode ( * head , previous ) ; } previous = previous -> next ; next = previous -> next ; len -- ; count ++ ; } return ; } void DeleteAllEvenNode ( struct Node * * head ) { int len = Length ( * head ) ; int count = 1 ; struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( len < 2 ) { return ; } previous = * head ; next = previous -> next ; while ( len > 0 ) { if ( count % 2 == 0 ) { previous -> next = next -> next ; free ( next ) ; previous = next -> next ; next = previous -> next ; } len -- ; count ++ ; } return ; } int main ( ) { struct Node * head = NULL ; Insert ( & head , 99 ) ; Insert ( & head , 11 ) ; Insert ( & head , 22 ) ; Insert ( & head , 33 ) ; Insert ( & head , 44 ) ; Insert ( & head , 55 ) ; Insert ( & head , 66 ) ; printf ( " Initial β List : β " ) ; Display ( head ) ; printf ( " After deleting Odd position nodes : " DeleteAllOddNode ( & head ) ; Display ( head ) ; printf ( " Initial List : " Display ( head ) ; printf ( " After deleting even position nodes : " DeleteAllEvenNode ( & head ) ; Display ( head ) ; return 0 ; } |
Deletion at different positions in a Circular Linked List | C ++ program to delete node at different poisitions from a circular linked list ; structure for a node ; Function to insert a node at the end of a Circular linked list ; Create a new node ; check node is created or not ; insert data into newly created node ; check list is empty if not have any node then make first node it ; if list have already some node ; move first node to last node ; put first or head node address in new node link ; put new node address into last node link ( next ) ; Function print data of list ; if list is empty , simply show message ; traverse first to last node ; Function return number of nodes present in list ; if list is empty simply return length zero ; traverse forst to last node ; Function delete First node of Circular Linked List ; check list have any node if not then return ; check list have single node if yes then delete it and return ; traverse second to first ; now previous is last node and next is first node of list first node ( next ) link address put in last node ( previous ) link ; make second node as head node ; Function to delete last node of Circular Linked List ; check if list doesn 't have any node if not then return ; check if list have single node if yes then delete it and return ; move first node to last previous ; Function delete node at a given poisition of Circular Linked List ; Find length of list ; check list have any node if not then return ; given index is in list or not ; delete first node ; traverse first to last node ; if index found delete that node ; Driver Code ; Deleting Node at position ; Deleting first Node ; Deleting last Node | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void Insert ( struct Node * * head , int data ) { struct Node * current = * head ; struct Node * newNode = new Node ; if ( ! newNode ) { printf ( " Memory Error " return ; } newNode -> data = data ; if ( * head == NULL ) { newNode -> next = newNode ; * head = newNode ; return ; } else { while ( current -> next != * head ) { current = current -> next ; } newNode -> next = * head ; current -> next = newNode ; } } void Display ( struct Node * head ) { struct Node * current = head ; if ( head == NULL ) { printf ( " Display List is empty " return ; } else { do { printf ( " % d β " , current -> data ) ; current = current -> next ; } while ( current != head ) ; } } int Length ( struct Node * head ) { struct Node * current = head ; int count = 0 ; if ( head == NULL ) { return 0 ; } else { do { current = current -> next ; count ++ ; } while ( current != head ) ; } return count ; } void DeleteFirst ( struct Node * * head ) { struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( previous -> next == previous ) { * head = NULL ; return ; } while ( previous -> next != * head ) { previous = previous -> next ; next = previous -> next ; } previous -> next = next -> next ; * head = previous -> next ; free ( next ) ; return ; } void DeleteLast ( struct Node * * head ) { struct Node * current = * head , * temp = * head , * previous ; if ( * head == NULL ) { printf ( " List is empty " return ; } if ( current -> next == current ) { * head = NULL ; return ; } while ( current -> next != * head ) { previous = current ; current = current -> next ; } previous -> next = current -> next ; * head = previous -> next ; free ( current ) ; return ; } void DeleteAtPosition ( struct Node * * head , int index ) { int len = Length ( * head ) ; int count = 1 ; struct Node * previous = * head , * next = * head ; if ( * head == NULL ) { printf ( " Delete Last List is empty " return ; } if ( index >= len index < 0 ) { printf ( " Index is not Found " return ; } if ( index == 0 ) { DeleteFirst ( head ) ; return ; } while ( len > 0 ) { if ( index == count ) { previous -> next = next -> next ; free ( next ) ; return ; } previous = previous -> next ; next = previous -> next ; len -- ; count ++ ; } return ; } int main ( ) { struct Node * head = NULL ; Insert ( & head , 99 ) ; Insert ( & head , 11 ) ; Insert ( & head , 22 ) ; Insert ( & head , 33 ) ; Insert ( & head , 44 ) ; Insert ( & head , 55 ) ; Insert ( & head , 66 ) ; printf ( " Initial β List : β " ) ; Display ( head ) ; printf ( " After Deleting node at index 4 : " DeleteAtPosition ( & head , 4 ) ; Display ( head ) ; printf ( " Initial List : " Display ( head ) ; printf ( " After Deleting first node : " DeleteFirst ( & head ) ; Display ( head ) ; printf ( " Initial List : " Display ( head ) ; printf ( " After Deleting last node : " DeleteLast ( & head ) ; Display ( head ) ; return 0 ; } |
Find minimum and maximum elements in singly Circular Linked List | C ++ program to find minimum and maximum value from singly circular linked list ; structure for a node ; Function to print minimum and maximum nodes of the circular linked list ; check list is empty ; pointer for traversing ; initialize head to current pointer ; initialize max int value to min initialize min int value to max ; While last node is not reached ; If current node data is lesser for min then replace it ; If current node data is greater for max then replace it ; Function to insert a node at the end of a Circular linked list ; Create a new node ; check node is created or not ; insert data into newly created node ; check list is empty if not have any node then make first node it ; if list have already some node ; move firt node to last node ; put first or head node address in new node link ; put new node address into last node link ( next ) ; Function to print the Circular linked list ; if list is empty simply show message ; traverse first to last node ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void printMinMax ( struct Node * * head ) { if ( * head == NULL ) { return ; } struct Node * current ; current = * head ; int min = INT_MAX , max = INT_MIN ; do { if ( current -> data < min ) { min = current -> data ; } if ( current -> data > max ) { max = current -> data ; } current = current -> next ; } while ( current != head ) ; cout << " Minimum = " β < < β min β < < β " , Maximum = " } void insertNode ( struct Node * * head , int data ) { struct Node * current = * head ; struct Node * newNode = new Node ; if ( ! newNode ) { printf ( " Memory Error " return ; } newNode -> data = data ; if ( * head == NULL ) { newNode -> next = newNode ; * head = newNode ; return ; } else { while ( current -> next != * head ) { current = current -> next ; } newNode -> next = * head ; current -> next = newNode ; } } void displayList ( struct Node * head ) { struct Node * current = head ; if ( head == NULL ) { printf ( " Display List is empty " return ; } else { do { printf ( " % d β " , current -> data ) ; current = current -> next ; } while ( current != head ) ; } } int main ( ) { struct Node * Head = NULL ; insertNode ( & Head , 99 ) ; insertNode ( & Head , 11 ) ; insertNode ( & Head , 22 ) ; insertNode ( & Head , 33 ) ; insertNode ( & Head , 44 ) ; insertNode ( & Head , 55 ) ; insertNode ( & Head , 66 ) ; cout << " Initial β List : β " ; displayList ( Head ) ; printMinMax ( & Head ) ; return 0 ; } |
Delete all the even nodes of a Circular Linked List | CPP program to delete all even node from a Circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not NULL then set the next of last node ; For the first node ; Delete the node if it is even ; If node to be deleted is head node ; traverse list till not found delete node ; copy address of node ; Finally , free the memory occupied by del ; Function to delete all even nodes from the singly circular linked list ; traverse list till the end if the node is even then delete it ; if node is even ; point to next node ; Function to print nodes ; Driver code ; Initialize lists as empty ; Created linked list will be 57 -> 11 -> 2 -> 56 -> 12 -> 61 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } void deleteNode ( Node * head_ref , Node * del ) { struct Node * temp = head_ref ; if ( head_ref == del ) head_ref = del -> next ; while ( temp -> next != del ) { temp = temp -> next ; } temp -> next = del -> next ; free ( del ) ; return ; } void deleteEvenNodes ( Node * head ) { struct Node * ptr = head ; struct Node * next ; do { if ( ptr -> data % 2 == 0 ) deleteNode ( head , ptr ) ; next = ptr -> next ; ptr = next ; } while ( ptr != head ) ; } void printList ( struct Node * head ) { struct Node * temp = head ; if ( head != NULL ) { do { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } while ( temp != head ) ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 61 ) ; push ( & head , 12 ) ; push ( & head , 56 ) ; push ( & head , 2 ) ; push ( & head , 11 ) ; push ( & head , 57 ) ; cout << " List after deletion : " ; deleteEvenNodes ( head ) ; printList ( head ) ; return 0 ; } |
Sum of the nodes of a Circular Linked List | CPP program to find the sum of all nodes of a Circular linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not NULL then set the next of last node ; For the first node ; Function to find sum of the given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 11 -> 2 -> 56 -> 12 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } int sumOfList ( struct Node * head ) { struct Node * temp = head ; int sum = 0 ; if ( head != NULL ) { do { temp = temp -> next ; sum += temp -> data ; } while ( temp != head ) ; } return sum ; } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 56 ) ; push ( & head , 2 ) ; push ( & head , 11 ) ; cout << " Sum β of β Circular β linked β list β is β = β " << sumOfList ( head ) ; return 0 ; } |
Delete every Kth node from circular linked list | C ++ program to delete every kth Node from circular linked list . ; structure for a Node ; Utility function to print the circular linked list ; Function to delete every kth Node ; If list is empty , simply return . ; take two pointers - current and previous ; Check if Node is the only Node \ If yes , we reached the goal , therefore return . ; Print intermediate list . ; If more than one Node present in the list , Make previous pointer point to current Iterate current pointer k times , i . e . current Node is to be deleted . ; If Node to be deleted is head ; If Node to be deleted is last Node . ; Function to insert a Node at the end of a Circular linked list ; Create a new Node ; if the list is empty , make the new Node head Also , it will point to itself . ; traverse the list to reach the last Node and insert the Node ; Driver program to test above functions ; insert Nodes in the circular linked list ; Delete every kth Node from the circular linked list . | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; Node ( int x ) { data = x ; next = NULL ; } } ; void printList ( Node * head ) { if ( head == NULL ) return ; Node * temp = head ; do { cout << temp -> data << " - > " ; temp = temp -> next ; } while ( temp != head ) ; cout << head -> data << endl ; } void deleteK ( Node * * head_ref , int k ) { Node * head = * head_ref ; if ( head == NULL ) return ; Node * curr = head , * prev ; while ( true ) { if ( curr -> next == head && curr == head ) break ; printList ( head ) ; for ( int i = 0 ; i < k ; i ++ ) { prev = curr ; curr = curr -> next ; } if ( curr == head ) { prev = head ; while ( prev -> next != head ) prev = prev -> next ; head = curr -> next ; prev -> next = head ; * head_ref = head ; free ( curr ) ; } else if ( curr -> next == head ) { prev -> next = head ; free ( curr ) ; } else { prev -> next = curr -> next ; free ( curr ) ; } } } void insertNode ( Node * * head_ref , int x ) { Node * head = * head_ref ; Node * temp = new Node ( x ) ; if ( head == NULL ) { temp -> next = temp ; * head_ref = temp ; } else { Node * temp1 = head ; while ( temp1 -> next != head ) temp1 = temp1 -> next ; temp1 -> next = temp ; temp -> next = head ; } } int main ( ) { struct Node * head = NULL ; insertNode ( & head , 1 ) ; insertNode ( & head , 2 ) ; insertNode ( & head , 3 ) ; insertNode ( & head , 4 ) ; insertNode ( & head , 5 ) ; insertNode ( & head , 6 ) ; insertNode ( & head , 7 ) ; insertNode ( & head , 8 ) ; insertNode ( & head , 9 ) ; int k = 4 ; deleteK ( & head , k ) ; return 0 ; } |
Insertion at Specific Position in a Circular Doubly Linked List | CPP program to convert insert an element at a specific position in a circular doubly linked list ; Doubly linked list node ; Utility function to create a node in memory ; Function to display the list ; Function to count nunmber of elements in the list ; Declare temp pointer to traverse the list ; Variable to store the count ; Iterate the list and increment the count ; As the list is circular , increment the counter at last ; Function to insert a node at a given position in the circular doubly linked list ; Declare two pointers ; Create a new node in memory ; Point temp to start ; count of total elements in the list ; If list is empty or the position is not valid , return false ; Assign the data ; Iterate till the loc ; See in Image , circle 1 ; See in Image , Circle 2 ; See in Image , Circle 3 ; See in Image , Circle 4 ; Function to create circular doubly linked list from array elements ; Declare newNode and temporary pointer ; Iterate the loop until array length ; Create new node ; Assign the array data ; If it is first element Put that node prev and next as start as it is circular ; Find the last node ; Add the last node to make them in circular fashion ; Driver Code ; Array elements to create circular doubly linked list ; Start Pointer ; Create the List ; Display the list before insertion ; Inserting 8 at 3 rd position ; Display the list after insertion | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * next ; struct node * prev ; } ; struct node * getNode ( ) { return ( ( struct node * ) malloc ( sizeof ( struct node ) ) ) ; } int displayList ( struct node * temp ) { struct node * t = temp ; if ( temp == NULL ) return 0 ; else { cout << " The β list β is : β " ; while ( temp -> next != t ) { cout << temp -> data << " β " ; temp = temp -> next ; } cout << temp -> data << endl ; return 1 ; } } int countList ( struct node * start ) { struct node * temp = start ; int count = 0 ; while ( temp -> next != start ) { temp = temp -> next ; count ++ ; } count ++ ; return count ; } bool insertAtLocation ( struct node * start , int data , int loc ) { struct node * temp , * newNode ; int i , count ; newNode = getNode ( ) ; temp = start ; count = countList ( start ) ; if ( temp == NULL count < loc ) return false ; else { newNode -> data = data ; for ( i = 1 ; i < loc - 1 ; i ++ ) { temp = temp -> next ; } newNode -> next = temp -> next ; ( temp -> next ) -> prev = newNode ; temp -> next = newNode ; newNode -> prev = temp ; return true ; } return false ; } void createList ( int arr [ ] , int n , struct node * * start ) { struct node * newNode , * temp ; int i ; for ( i = 0 ; i < n ; i ++ ) { newNode = getNode ( ) ; newNode -> data = arr [ i ] ; if ( i == 0 ) { * start = newNode ; newNode -> prev = * start ; newNode -> next = * start ; } else { temp = ( * start ) -> prev ; temp -> next = newNode ; newNode -> next = * start ; newNode -> prev = temp ; temp = * start ; temp -> prev = newNode ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; struct node * start = NULL ; createList ( arr , n , & start ) ; displayList ( start ) ; insertAtLocation ( start , 8 , 3 ) ; displayList ( start ) ; return 0 ; } |
Convert an Array to a Circular Doubly Linked List | CPP program to convert array to circular doubly linked list ; Doubly linked list node ; Utility function to create a node in memory ; Function to display the list ; Function to convert array into list ; Declare newNode and temporary pointer ; Iterate the loop until array length ; Create new node ; Assign the array data ; If it is first element Put that node prev and next as start as it is circular ; Find the last node ; Add the last node to make them in circular fashion ; Driver Code ; Array to be converted ; Start Pointer ; Create the List ; Display the list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * next ; struct node * prev ; } ; struct node * getNode ( ) { return ( ( struct node * ) malloc ( sizeof ( struct node ) ) ) ; } int displayList ( struct node * temp ) { struct node * t = temp ; if ( temp == NULL ) return 0 ; else { cout << " The β list β is : β " ; while ( temp -> next != t ) { cout << temp -> data << " β " ; temp = temp -> next ; } cout << temp -> data ; return 1 ; } } void createList ( int arr [ ] , int n , struct node * * start ) { struct node * newNode , * temp ; int i ; for ( i = 0 ; i < n ; i ++ ) { newNode = getNode ( ) ; newNode -> data = arr [ i ] ; if ( i == 0 ) { * start = newNode ; newNode -> prev = * start ; newNode -> next = * start ; } else { temp = ( * start ) -> prev ; temp -> next = newNode ; newNode -> next = * start ; newNode -> prev = temp ; temp = * start ; temp -> prev = newNode ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; struct node * start = NULL ; createList ( arr , n , & start ) ; displayList ( start ) ; return 0 ; } |
Lucky alive person in a circle | Code Solution to sword puzzle | C ++ code to find the luckiest person ; Node structure ; Function to find the luckiest person ; Create a single node circular linked list . ; Starting from first soldier . ; condition for evaluating the existence of single soldier who is not killed . ; deleting soldier from the circular list who is killed in the fight . ; Returning the Luckiest soldier who remains alive . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> next = NULL ; return node ; } int alivesol ( int Num ) { if ( Num == 1 ) return 1 ; Node * last = newNode ( 1 ) ; last -> next = last ; for ( int i = 2 ; i <= Num ; i ++ ) { Node * temp = newNode ( i ) ; temp -> next = last -> next ; last -> next = temp ; last = temp ; } Node * curr = last -> next ; Node * temp ; while ( curr -> next != curr ) { temp = curr ; curr = curr -> next ; temp -> next = curr -> next ; delete curr ; temp = temp -> next ; curr = temp ; } int res = temp -> data ; delete temp ; return res ; } int main ( ) { int N = 100 ; cout << alivesol ( N ) << endl ; return 0 ; } |
Lowest Common Ancestor of the deepest leaves of a Binary Tree | C ++ program for the above approach ; Node of a Binary Tree ; Function to create a new tree Node ; Function to find the depth of the Binary Tree ; If root is not null ; Left recursive subtree ; Right recursive subtree ; Returns the maximum depth ; Function to perform the depth first search on the binary tree ; If root is null ; If curr is equal to depth ; Left recursive subtree ; Right recursive subtree ; If left and right are not null ; Return left , if left is not null Otherwise return right ; Function to find the LCA of the deepest nodes of the binary tree ; If root is null ; Stores the deepest depth of the binary tree ; Return the LCA of the nodes at level depth ; Driver Code ; Given Binary Tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { struct Node * left ; struct Node * right ; int data ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> left = temp -> right = NULL ; return temp ; } int finddepth ( Node * root ) { if ( ! root ) return 0 ; int left = finddepth ( root -> left ) ; int right = finddepth ( root -> right ) ; return 1 + max ( left , right ) ; } Node * dfs ( Node * root , int curr , int depth ) { if ( ! root ) return NULL ; if ( curr == depth ) return root ; Node * left = dfs ( root -> left , curr + 1 , depth ) ; Node * right = dfs ( root -> right , curr + 1 , depth ) ; if ( left != NULL && right != NULL ) return root ; return left ? left : right ; } Node * lcaOfDeepestLeaves ( Node * root ) { if ( ! root ) return NULL ; int depth = finddepth ( root ) - 1 ; return dfs ( root , 0 , depth ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> left = newNode ( 8 ) ; root -> right -> left -> right = newNode ( 9 ) ; cout << lcaOfDeepestLeaves ( root ) -> data ; return 0 ; } |
Check if two nodes are on same path in a tree | Set 2 | C ++ program to check if two nodes are on same path in a tree without using any extra space ; Function to filter the return Values ; Utility function to check if nodes are on same path or not ; Condition to check if any vertex is equal to given two vertex or not ; Check if the current position has 1 ; Recursive call ; Return LCA ; Function to check if nodes lies on same path or not ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int filter ( int x , int y , int z ) { if ( x != -1 && y != -1 ) { return z ; } return x == -1 ? y : x ; } int samePathUtil ( int mtrx [ ] [ 7 ] , int vrtx , int v1 , int v2 , int i ) { int ans = -1 ; if ( i == v1 i == v2 ) return i ; for ( int j = 0 ; j < vrtx ; j ++ ) { if ( mtrx [ i ] [ j ] == 1 ) { ans = filter ( ans , samePathUtil ( mtrx , vrtx , v1 , v2 , j ) , i ) ; } } return ans ; } bool isVertexAtSamePath ( int mtrx [ ] [ 7 ] , int vrtx , int v1 , int v2 , int i ) { int lca = samePathUtil ( mtrx , vrtx , v1 - 1 , v2 - 1 , i ) ; if ( lca == v1 - 1 lca == v2 - 1 ) return true ; return false ; } int main ( ) { int vrtx = 7 , edge = 6 ; int mtrx [ 7 ] [ 7 ] = { { 0 , 1 , 1 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 } } ; int v1 = 1 , v2 = 5 ; if ( isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , 0 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Find distance between two nodes in the given Binary tree for Q queries | C ++ Program to find distance between two nodes using LCA ; log2 ( MAX ) ; Array to store the level of each node ; Vector to store tree ; Pre - Processing to calculate values of lca [ ] [ ] , dist [ ] [ ] ; Using recursion formula to calculate the values of lca [ ] [ ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ ] [ ] and dist [ ] [ ] ; Function to find the distance between given nodes u and v ; The node which is present farthest from the root node is taken as v . If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Adding distance of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x ] [ 0 ] is ; Adding the distance of v and u to its 2 ^ i - th ancestor ; Adding the distance of u and v to its first ancestor ; Driver Code ; Number of nodes ; Add edges with their cost ; Initialising lca and dist values with - 1 and 0 respectively ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 3 } ; Query 3 : { 3 , 5 } | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE #define log 10 NEW_LINE int level [ MAX ] ; int lca [ MAX ] [ log ] ; int dist [ MAX ] [ log ] ; vector < pair < int , int > > graph [ MAX ] ; void addEdge ( int u , int v , int cost ) { graph [ u ] . push_back ( { v , cost } ) ; graph [ v ] . push_back ( { u , cost } ) ; } void dfs ( int node , int parent , int h , int cost ) { lca [ node ] [ 0 ] = parent ; level [ node ] = h ; if ( parent != -1 ) { dist [ node ] [ 0 ] = cost ; } for ( int i = 1 ; i < log ; i ++ ) { if ( lca [ node ] [ i - 1 ] != -1 ) { lca [ node ] [ i ] = lca [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; dist [ node ] [ i ] = dist [ node ] [ i - 1 ] + dist [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; } } for ( auto i : graph [ node ] ) { if ( i . first == parent ) continue ; dfs ( i . first , node , h + 1 , i . second ) ; } } void findDistance ( int u , int v ) { int ans = 0 ; if ( level [ u ] > level [ v ] ) swap ( u , v ) ; for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != -1 && level [ lca [ v ] [ i ] ] >= level [ u ] ) { ans += dist [ v ] [ i ] ; v = lca [ v ] [ i ] ; } } if ( v == u ) { cout << ans << endl ; } else { for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != lca [ u ] [ i ] ) { ans += dist [ u ] [ i ] + dist [ v ] [ i ] ; v = lca [ v ] [ i ] ; u = lca [ u ] [ i ] ; } } ans += dist [ u ] [ 0 ] + dist [ v ] [ 0 ] ; cout << ans << endl ; } } int main ( ) { int n = 5 ; addEdge ( 1 , 2 , 2 ) ; addEdge ( 1 , 3 , 3 ) ; addEdge ( 2 , 4 , 5 ) ; addEdge ( 2 , 5 , 7 ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j < log ; j ++ ) { lca [ i ] [ j ] = -1 ; dist [ i ] [ j ] = 0 ; } } dfs ( 1 , -1 , 0 , 0 ) ; findDistance ( 1 , 3 ) ; findDistance ( 2 , 3 ) ; findDistance ( 3 , 5 ) ; return 0 ; } |
Count of all prime weight nodes between given nodes in the given Tree | C ++ program Count prime weight nodes between two nodes in the given tree ; Function to perform Sieve Of Eratosthenes for prime number ; Initialize all entries of prime it as true A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Check if prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to perform dfs ; Stores parent of each node ; Stores level of each node from root ; Function to perform prime number between the path ; The node which is present farthest from the root node is taken as v If u is farther from root node then swap the two ; Find the ancestor of v which is at same level as u ; If Weight is prime increment count ; If u is the ancestor of v then u is the LCA of u and v Now check if weigh [ v ] is prime or not ; When v and u are on the same level but are in different subtree . Now move both u and v up by 1 till they are not same ; If weight of first ancestor is prime ; Driver code ; Precompute all the prime numbers till MAX ; Weights of the node ; Edges of the tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE int weight [ MAX ] ; int level [ MAX ] ; int par [ MAX ] ; bool prime [ MAX + 1 ] ; vector < int > graph [ MAX ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= MAX ; i += p ) prime [ i ] = false ; } } } void dfs ( int node , int parent , int h ) { par [ node ] = parent ; level [ node ] = h ; for ( int child : graph [ node ] ) { if ( child == parent ) continue ; dfs ( child , node , h + 1 ) ; } } int findPrimeOnPath ( int u , int v ) { int count = 0 ; if ( level [ u ] > level [ v ] ) swap ( u , v ) ; int d = level [ v ] - level [ u ] ; while ( d -- ) { if ( prime [ weight [ v ] ] ) count ++ ; v = par [ v ] ; } if ( v == u ) { if ( prime [ weight [ v ] ] ) count ++ ; return count ; } while ( v != u ) { if ( prime [ weight [ v ] ] ) count ++ ; if ( prime [ weight [ u ] ] ) count ++ ; u = par [ u ] ; v = par [ v ] ; } if ( prime [ weight [ v ] ] ) count ++ ; return count ; } int main ( ) { SieveOfEratosthenes ( ) ; weight [ 1 ] = 5 ; weight [ 2 ] = 10 ; weight [ 3 ] = 11 ; weight [ 4 ] = 8 ; weight [ 5 ] = 6 ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; dfs ( 1 , -1 , 0 ) ; int u = 3 , v = 5 ; cout << findPrimeOnPath ( u , v ) << endl ; return 0 ; } |
Query to find the maximum and minimum weight between two nodes in the given tree using LCA . | C ++ Program to find the maximum and minimum weight between two nodes in the given tree using LCA ; log2 ( MAX ) ; Array to store the level of each node ; Vector to store tree ; Array to store weight of nodes ; Pre - Processing to calculate values of lca [ ] [ ] , MinWeight [ ] [ ] and MaxWeight [ ] [ ] ; Using recursion formula to calculate the values of lca [ ] [ ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ ] [ ] , MinWeight [ ] [ ] and MaxWeight [ ] [ ] ; Function to find the minimum and maximum weights in the given range ; The node which is present farthest from the root node is taken as v If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Calculating Minimum and Maximum Weight of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x ] [ 0 ] is ; Calculating the minimum of MinWeight of v to its 2 ^ i - th ancestor and MinWeight of u to its 2 ^ i - th ancestor ; Calculating the maximum of MaxWeight of v to its 2 ^ i - th ancestor and MaxWeight of u to its 2 ^ i - th ancestor ; Calculating the Minimum of first ancestor of u and v ; Calculating the maximum of first ancestor of u and v ; Driver Code ; Number of nodes ; Add edges ; Initialising lca values with - 1 Initialising MinWeight values with INT_MAX Initialising MaxWeight values with INT_MIN ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 4 } ; Query 3 : { 3 , 5 } | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE #define log 10 NEW_LINE int level [ MAX ] ; int lca [ MAX ] [ log ] ; int minWeight [ MAX ] [ log ] ; int maxWeight [ MAX ] [ log ] ; vector < int > graph [ MAX ] ; int weight [ MAX ] ; void addEdge ( int u , int v ) { graph [ u ] . push_back ( v ) ; graph [ v ] . push_back ( u ) ; } void dfs ( int node , int parent , int h ) { lca [ node ] [ 0 ] = parent ; level [ node ] = h ; if ( parent != -1 ) { minWeight [ node ] [ 0 ] = min ( weight [ node ] , weight [ parent ] ) ; maxWeight [ node ] [ 0 ] = max ( weight [ node ] , weight [ parent ] ) ; } for ( int i = 1 ; i < log ; i ++ ) { if ( lca [ node ] [ i - 1 ] != -1 ) { lca [ node ] [ i ] = lca [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; minWeight [ node ] [ i ] = min ( minWeight [ node ] [ i - 1 ] , minWeight [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) ; maxWeight [ node ] [ i ] = max ( maxWeight [ node ] [ i - 1 ] , maxWeight [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) ; } } for ( int i : graph [ node ] ) { if ( i == parent ) continue ; dfs ( i , node , h + 1 ) ; } } void findMinMaxWeight ( int u , int v ) { int minWei = INT_MAX ; int maxWei = INT_MIN ; if ( level [ u ] > level [ v ] ) swap ( u , v ) ; for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != -1 && level [ lca [ v ] [ i ] ] >= level [ u ] ) { minWei = min ( minWei , minWeight [ v ] [ i ] ) ; maxWei = max ( maxWei , maxWeight [ v ] [ i ] ) ; v = lca [ v ] [ i ] ; } } if ( v == u ) { cout << minWei << " β " << maxWei << endl ; } else { for ( int i = log - 1 ; i >= 0 ; i -- ) { if ( lca [ v ] [ i ] != lca [ u ] [ i ] ) { minWei = min ( minWei , min ( minWeight [ v ] [ i ] , minWeight [ u ] [ i ] ) ) ; maxWei = max ( maxWei , max ( maxWeight [ v ] [ i ] , maxWeight [ u ] [ i ] ) ) ; v = lca [ v ] [ i ] ; u = lca [ u ] [ i ] ; } } minWei = min ( minWei , min ( minWeight [ v ] [ 0 ] , minWeight [ u ] [ 0 ] ) ) ; maxWei = max ( maxWei , max ( maxWeight [ v ] [ 0 ] , maxWeight [ u ] [ 0 ] ) ) ; cout << minWei << " β " << maxWei << endl ; } } int main ( ) { int n = 5 ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 5 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 3 ) ; weight [ 1 ] = -1 ; weight [ 2 ] = 5 ; weight [ 3 ] = -1 ; weight [ 4 ] = 3 ; weight [ 5 ] = -2 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j < log ; j ++ ) { lca [ i ] [ j ] = -1 ; minWeight [ i ] [ j ] = INT_MAX ; maxWeight [ i ] [ j ] = INT_MIN ; } } dfs ( 1 , -1 , 0 ) ; findMinMaxWeight ( 1 , 3 ) ; findMinMaxWeight ( 2 , 4 ) ; findMinMaxWeight ( 3 , 5 ) ; return 0 ; } |
Lowest Common Ancestor for a Set of Nodes in a Rooted Tree | C ++ Program to find the LCA in a rooted tree for a given set of nodes ; Set time 1 initially ; Case for root node ; In - time for node ; Out - time for the node ; level [ i ] -- > Level of node i ; t_in [ i ] -- > In - time of node i ; t_out [ i ] -- > Out - time of node i ; Fill the level , in - time and out - time of all nodes ; To find minimum in - time among all nodes in LCA set ; To find maximum in - time among all nodes in LCA set ; Node with same minimum and maximum out time is LCA for the set ; Take the minimum level as level of LCA ; If i - th node is at a higher level than that of the minimum among the nodes of the given set ; Compare in - time , out - time and level of i - th node to the respective extremes among all nodes of the given set ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int T = 1 ; void dfs ( int node , int parent , vector < int > g [ ] , int level [ ] , int t_in [ ] , int t_out [ ] ) { if ( parent == -1 ) { level [ node ] = 1 ; } else { level [ node ] = level [ parent ] + 1 ; } t_in [ node ] = T ; for ( auto i : g [ node ] ) { if ( i != parent ) { T ++ ; dfs ( i , node , g , level , t_in , t_out ) ; } } T ++ ; t_out [ node ] = T ; } int findLCA ( int n , vector < int > g [ ] , vector < int > v ) { int level [ n + 1 ] ; int t_in [ n + 1 ] ; int t_out [ n + 1 ] ; dfs ( 1 , -1 , g , level , t_in , t_out ) ; int mint = INT_MAX , maxt = INT_MIN ; int minv = -1 , maxv = -1 ; for ( auto i = v . begin ( ) ; i != v . end ( ) ; i ++ ) { if ( t_in [ * i ] < mint ) { mint = t_in [ * i ] ; minv = * i ; } if ( t_out [ * i ] > maxt ) { maxt = t_out [ * i ] ; maxv = * i ; } } if ( minv == maxv ) { return minv ; } int lev = min ( level [ minv ] , level [ maxv ] ) ; int node , l = INT_MIN ; for ( int i = 1 ; i <= n ; i ++ ) { if ( level [ i ] > lev ) continue ; if ( t_in [ i ] <= mint && t_out [ i ] >= maxt && level [ i ] > l ) { node = i ; l = level [ i ] ; } } return node ; } int main ( ) { int n = 10 ; vector < int > g [ n + 1 ] ; g [ 1 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 3 ) ; g [ 3 ] . push_back ( 1 ) ; g [ 1 ] . push_back ( 4 ) ; g [ 4 ] . push_back ( 1 ) ; g [ 2 ] . push_back ( 5 ) ; g [ 5 ] . push_back ( 2 ) ; g [ 2 ] . push_back ( 6 ) ; g [ 6 ] . push_back ( 2 ) ; g [ 3 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 3 ) ; g [ 4 ] . push_back ( 10 ) ; g [ 10 ] . push_back ( 4 ) ; g [ 8 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 8 ) ; g [ 9 ] . push_back ( 7 ) ; g [ 7 ] . push_back ( 9 ) ; vector < int > v = { 7 , 3 , 8 } ; cout << findLCA ( n , g , v ) << endl ; } |
Queries to check if the path between two nodes in a tree is a palindrome | C ++ implementation of the approach ; Function that returns true if a palindromic string can be formed using the given characters ; Count odd occurring characters ; Return false if odd count is more than 1 , ; Find to find the Lowest Common Ancestor in the tree ; Base case ; Base case ; Initially value - 1 denotes that we need to find the ancestor ; - 1 denotes that we need to find the lca for x and y , values other than x and y will be the LCA of x and y ; Iterating in the child substree of the currentNode ; Next node that will be checked ; Look for the next child subtree ; Both the nodes exist in the different subtrees , in this case parent node will be the lca ; Handle the cases where LCA is already calculated or both x and y are present in the same subtree ; Function to calculate the character count for each path from node i to 1 ( root node ) ; Updating the character count for each node ; Look for the child subtree ; Function that returns true if a palindromic path is possible between the nodes x and y ; If both x and y are same then lca will be the node itself ; Find the lca of x and y ; Calculating the character count for path node x to y ; Checking if we can form the palindrome string with the all character count ; Function to update character count at node v ; Updating the character count at node v ; Function to perform the queries ; If path can be a palindrome ; Driver code ; Fill the complete array with 0 ; Edge between 1 and 2 labelled " bbc " ; Edge between 1 and 3 labelled " ac " ; Update the character count from root to the ith node ; Perform the queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_SIZE = 100005 , MAX_CHAR = 26 ; int nodeCharactersCount [ MAX_SIZE ] [ MAX_CHAR ] ; vector < int > tree [ MAX_SIZE ] ; bool canFormPalindrome ( int * charArray ) { int oddCount = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( charArray [ i ] % 2 == 1 ) oddCount ++ ; } if ( oddCount >= 2 ) return false ; else return true ; } int LCA ( int currentNode , int x , int y ) { if ( currentNode == x ) return x ; if ( currentNode == y ) return y ; int xLca , yLca ; xLca = yLca = -1 ; int gotLca = -1 ; for ( int l = 0 ; l < tree [ currentNode ] . size ( ) ; l ++ ) { int nextNode = tree [ currentNode ] [ l ] ; int out_ = LCA ( nextNode , x , y ) ; if ( out_ == x ) xLca = out_ ; if ( out_ == y ) yLca = out_ ; if ( xLca != -1 and yLca != -1 ) return currentNode ; if ( out_ != -1 ) gotLca = out_ ; } return gotLca ; } void buildTree ( int i ) { for ( int l = 0 ; l < tree [ i ] . size ( ) ; l ++ ) { int nextNode = tree [ i ] [ l ] ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) { nodeCharactersCount [ nextNode ] [ j ] += nodeCharactersCount [ i ] [ j ] ; } buildTree ( nextNode ) ; } } bool canFormPalindromicPath ( int x , int y ) { int lcaNode ; if ( x == y ) lcaNode = x ; else lcaNode = LCA ( 1 , x , y ) ; int charactersCountFromXtoY [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { charactersCountFromXtoY [ i ] = nodeCharactersCount [ x ] [ i ] + nodeCharactersCount [ y ] [ i ] - 2 * nodeCharactersCount [ lcaNode ] [ i ] ; } if ( canFormPalindrome ( charactersCountFromXtoY ) ) return true ; return false ; } void updateNodeCharactersCount ( string str , int v ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) nodeCharactersCount [ v ] [ str [ i ] - ' a ' ] ++ ; } void performQueries ( vector < vector < int > > queries , int q ) { int i = 0 ; while ( i < q ) { int x = queries [ i ] [ 0 ] ; int y = queries [ i ] [ 1 ] ; if ( canFormPalindromicPath ( x , y ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; i ++ ; } } int main ( ) { memset ( nodeCharactersCount , 0 , sizeof ( nodeCharactersCount ) ) ; tree [ 1 ] . push_back ( 2 ) ; updateNodeCharactersCount ( " bbc " , 2 ) ; tree [ 1 ] . push_back ( 3 ) ; updateNodeCharactersCount ( " ac " , 3 ) ; buildTree ( 1 ) ; vector < vector < int > > queries { { 1 , 2 } , { 2 , 3 } , { 3 , 1 } , { 3 , 3 } } ; int q = queries . size ( ) ; performQueries ( queries , q ) ; return 0 ; } |
Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree | C ++ implementation of the approach ; Structure of binary tree ; Function to create a new node ; Function to store the path from root node to given node of the tree in path vector and then returns true if the path exists otherwise false ; Function to print the minimum and the maximum value present in the path connecting the given two nodes of the given binary tree ; To store the path from the root node to a ; To store the path from the root node to b ; To store the minimum and the maximum value in the path from LCA to a ; To store the minimum and the maximum value in the path from LCA to b ; If both a and b are present in the tree ; Compare the paths to get the first different value ; Find minimum and maximum value in the path from LCA to a ; Find minimum and maximum value in the path from LCA to b ; Minimum of min values in first path and second path ; Maximum of max values in first path and second path ; If no path exists ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * left ; Node * right ; int data ; } ; Node * newNode ( int key ) { Node * node = new Node ( ) ; node -> left = node -> right = NULL ; node -> data = key ; return node ; } bool FindPath ( Node * root , vector < int > & path , int key ) { if ( root == NULL ) return false ; path . push_back ( root -> data ) ; if ( root -> data == key ) return true ; if ( FindPath ( root -> left , path , key ) || FindPath ( root -> right , path , key ) ) return true ; path . pop_back ( ) ; return false ; } int minMaxNodeInPath ( Node * root , int a , int b ) { vector < int > Path1 ; vector < int > Path2 ; int min1 = INT_MAX ; int max1 = INT_MIN ; int min2 = INT_MAX ; int max2 = INT_MIN ; int i = 0 ; int j = 0 ; if ( FindPath ( root , Path1 , a ) && FindPath ( root , Path2 , b ) ) { for ( i = 0 ; i < Path1 . size ( ) && Path2 . size ( ) ; i ++ ) if ( Path1 [ i ] != Path2 [ i ] ) break ; i -- ; j = i ; for ( ; i < Path1 . size ( ) ; i ++ ) { if ( min1 > Path1 [ i ] ) min1 = Path1 [ i ] ; if ( max1 < Path1 [ i ] ) max1 = Path1 [ i ] ; } for ( ; j < Path2 . size ( ) ; j ++ ) { if ( min2 > Path2 [ j ] ) min2 = Path2 [ j ] ; if ( max2 < Path2 [ j ] ) max2 = Path2 [ j ] ; } cout << " Min β = β " << min ( min1 , min2 ) << endl ; cout << " Max β = β " << max ( max1 , max2 ) ; } else cout << " Max = -1 " ; } int main ( ) { Node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 22 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 25 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; int a = 5 ; int b = 1454 ; minMaxNodeInPath ( root , a , b ) ; return 0 ; } |
Sum of all odd nodes in the path connecting two given nodes | C ++ program to find sum of all odd nodes in the path connecting two given nodes ; Binary Tree node ; Utitlity function to create a new Binary Tree node ; Function to check if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is NULL there is no path ; push the node ' s β value β in β ' arr ' ; if it is the required node return true ; else check whether the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node Thus , remove current node ' s β value β from β β ' arr 'and then return false ; Function to get the sum of odd nodes in the path between any two nodes in a binary tree ; vector to store the path of first node n1 from root ; vector to store the path of second node n2 from root ; Get intersection point ; Keep moving forward until no intersection is found ; calculate sum of ODD nodes from the path ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return node ; } bool getPath ( Node * root , vector < int > & arr , int x ) { if ( ! root ) return false ; arr . push_back ( root -> data ) ; if ( root -> data == x ) return true ; if ( getPath ( root -> left , arr , x ) || getPath ( root -> right , arr , x ) ) return true ; arr . pop_back ( ) ; return false ; } int sumOddNodes ( Node * root , int n1 , int n2 ) { vector < int > path1 ; vector < int > path2 ; getPath ( root , path1 , n1 ) ; getPath ( root , path2 , n2 ) ; int intersection = -1 ; int i = 0 , j = 0 ; while ( i != path1 . size ( ) || j != path2 . size ( ) ) { if ( i == j && path1 [ i ] == path2 [ j ] ) { i ++ ; j ++ ; } else { intersection = j - 1 ; break ; } } int sum = 0 ; for ( int i = path1 . size ( ) - 1 ; i > intersection ; i -- ) if ( path1 [ i ] % 2 ) sum += path1 [ i ] ; for ( int i = intersection ; i < path2 . size ( ) ; i ++ ) if ( path2 [ i ] % 2 ) sum += path2 [ i ] ; return sum ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; int node1 = 5 ; int node2 = 6 ; cout << sumOddNodes ( root , node1 , node2 ) ; return 0 ; } |
Lowest Common Ancestor in Parent Array Representation | CPP program to find LCA in a tree represented as parent array . ; Maximum value in a node ; Function to find the Lowest common ancestor ; Create a visited vector and mark all nodes as not visited . ; Moving from n1 node till root and mark every accessed node as visited ; Move to the parent of node n1 ; For second node finding the first node common ; Insert function for Binary tree ; Driver Function ; Maximum capacity of binary tree ; Root marked | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int findLCA ( int n1 , int n2 , int parent [ ] ) { vector < bool > visited ( MAX , false ) ; visited [ n1 ] = true ; while ( parent [ n1 ] != -1 ) { visited [ n1 ] = true ; n1 = parent [ n1 ] ; } visited [ n1 ] = true ; while ( ! visited [ n2 ] ) n2 = parent [ n2 ] ; return n2 ; } void insertAdj ( int parent [ ] , int i , int j ) { parent [ i ] = j ; } int main ( ) { int parent [ MAX ] ; parent [ 20 ] = -1 ; insertAdj ( parent , 8 , 20 ) ; insertAdj ( parent , 22 , 20 ) ; insertAdj ( parent , 4 , 8 ) ; insertAdj ( parent , 12 , 8 ) ; insertAdj ( parent , 10 , 12 ) ; insertAdj ( parent , 14 , 12 ) ; cout << findLCA ( 10 , 14 , parent ) ; return 0 ; } |
Queries to find distance between two nodes of a Binary tree | C ++ program to find distance between two nodes for multiple queries ; A tree node structure ; Utility function to create a new Binary Tree node ; Array to store level of each node ; Utility Function to store level of all nodes ; queue to hold tree node with level ; let root node be at level 0 ; Do level Order Traversal of tree ; Node p . first is on level p . second ; If left child exits , put it in queue with current_level + 1 ; If right child exists , put it in queue with current_level + 1 ; Stores Euler Tour ; index in Euler array ; Find Euler Tour ; store current node 's data ; If left node exists ; traverse left subtree ; store parent node 's data ; If right node exists ; traverse right subtree ; store parent node 's data ; checks for visited nodes ; Stores level of Euler Tour ; Stores indices of first occurrence of nodes in Euler tour ; Preprocessing Euler Tour for finding LCA ; If node is not visited before ; Add to first occurrence ; Mark it visited ; Stores values and positions ; Utility function to find minimum of pair type values ; Utility function to build segment tree ; Utility function to find LCA ; Function to return distance between two nodes n1 and n2 ; Maintain original Values ; Get First Occurrence of n1 ; Get First Occurrence of n2 ; Swap if low > high ; Get position of minimum value ; Extract value out of Euler tour ; return calculated distance ; Build Tree ; Store Levels ; Find L and H array ; Build segment Tree ; Driver function to test above functions ; Number of nodes ; Constructing tree given in the above figure ; Function to do all preprocessing | #include <bits/stdc++.h> NEW_LINE #define MAX 100001 NEW_LINE using namespace std ; struct Node { int data ; struct Node * left ; struct Node * right ; } ; struct Node * newNode ( int data ) { struct Node * temp = new struct Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int level [ MAX ] ; void FindLevels ( struct Node * root ) { if ( ! root ) return ; queue < pair < struct Node * , int > > q ; q . push ( { root , 0 } ) ; pair < struct Node * , int > p ; while ( ! q . empty ( ) ) { p = q . front ( ) ; q . pop ( ) ; level [ p . first -> data ] = p . second ; if ( p . first -> left ) q . push ( { p . first -> left , p . second + 1 } ) ; if ( p . first -> right ) q . push ( { p . first -> right , p . second + 1 } ) ; } } int Euler [ MAX ] ; int idx = 0 ; void eulerTree ( struct Node * root ) { Euler [ ++ idx ] = root -> data ; if ( root -> left ) { eulerTree ( root -> left ) ; Euler [ ++ idx ] = root -> data ; } if ( root -> right ) { eulerTree ( root -> right ) ; Euler [ ++ idx ] = root -> data ; } } int vis [ MAX ] ; int L [ MAX ] ; int H [ MAX ] ; void preprocessEuler ( int size ) { for ( int i = 1 ; i <= size ; i ++ ) { L [ i ] = level [ Euler [ i ] ] ; if ( vis [ Euler [ i ] ] == 0 ) { H [ Euler [ i ] ] = i ; vis [ Euler [ i ] ] = 1 ; } } } pair < int , int > seg [ 4 * MAX ] ; pair < int , int > min ( pair < int , int > a , pair < int , int > b ) { if ( a . first <= b . first ) return a ; else return b ; } pair < int , int > buildSegTree ( int low , int high , int pos ) { if ( low == high ) { seg [ pos ] . first = L [ low ] ; seg [ pos ] . second = low ; return seg [ pos ] ; } int mid = low + ( high - low ) / 2 ; buildSegTree ( low , mid , 2 * pos ) ; buildSegTree ( mid + 1 , high , 2 * pos + 1 ) ; seg [ pos ] = min ( seg [ 2 * pos ] , seg [ 2 * pos + 1 ] ) ; } pair < int , int > LCA ( int qlow , int qhigh , int low , int high , int pos ) { if ( qlow <= low && qhigh >= high ) return seg [ pos ] ; if ( qlow > high qhigh < low ) return { INT_MAX , 0 } ; int mid = low + ( high - low ) / 2 ; return min ( LCA ( qlow , qhigh , low , mid , 2 * pos ) , LCA ( qlow , qhigh , mid + 1 , high , 2 * pos + 1 ) ) ; } int findDistance ( int n1 , int n2 , int size ) { int prevn1 = n1 , prevn2 = n2 ; n1 = H [ n1 ] ; n2 = H [ n2 ] ; if ( n2 < n1 ) swap ( n1 , n2 ) ; int lca = LCA ( n1 , n2 , 1 , size , 1 ) . second ; lca = Euler [ lca ] ; return level [ prevn1 ] + level [ prevn2 ] - 2 * level [ lca ] ; } void preProcessing ( Node * root , int N ) { eulerTree ( root ) ; FindLevels ( root ) ; preprocessEuler ( 2 * N - 1 ) ; buildSegTree ( 1 , 2 * N - 1 , 1 ) ; } int main ( ) { int N = 8 ; Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; preProcessing ( root , N ) ; cout << " Dist ( 4 , β 5 ) β = β " << findDistance ( 4 , 5 , 2 * N - 1 ) << " STRNEWLINE " ; cout << " Dist ( 4 , β 6 ) β = β " << findDistance ( 4 , 6 , 2 * N - 1 ) << " STRNEWLINE " ; cout << " Dist ( 3 , β 4 ) β = β " << findDistance ( 3 , 4 , 2 * N - 1 ) << " STRNEWLINE " ; cout << " Dist ( 2 , β 4 ) β = β " << findDistance ( 2 , 4 , 2 * N - 1 ) << " STRNEWLINE " ; cout << " Dist ( 8 , β 5 ) β = β " << findDistance ( 8 , 5 , 2 * N - 1 ) << " STRNEWLINE " ; return 0 ; } |
LCA for general or n | Program to find LCA of n1 and n2 using one DFS on the Tree ; Maximum number of nodes is 100000 and nodes are numbered from 1 to 100000 ; storing root to node path ; storing the path from root to node ; pushing current node into the path ; node found ; terminating the path ; This Function compares the path from root to ' a ' & root to ' b ' and returns LCA of a and b . Time Complexity : O ( n ) ; trivial case ; setting root to be first element in path ; calculating path from root to a ; calculating path from root to b ; runs till path 1 & path 2 mathches ; returns the last matching node in the paths ; Driver code ; Number of nodes | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100001 NEW_LINE vector < int > tree [ MAXN ] ; int path [ 3 ] [ MAXN ] ; void dfs ( int cur , int prev , int pathNumber , int ptr , int node , bool & flag ) { for ( int i = 0 ; i < tree [ cur ] . size ( ) ; i ++ ) { if ( tree [ cur ] [ i ] != prev and ! flag ) { path [ pathNumber ] [ ptr ] = tree [ cur ] [ i ] ; if ( tree [ cur ] [ i ] == node ) { flag = true ; path [ pathNumber ] [ ptr + 1 ] = -1 ; return ; } dfs ( tree [ cur ] [ i ] , cur , pathNumber , ptr + 1 , node , flag ) ; } } } int LCA ( int a , int b ) { if ( a == b ) return a ; path [ 1 ] [ 0 ] = path [ 2 ] [ 0 ] = 1 ; bool flag = false ; dfs ( 1 , 0 , 1 , 1 , a , flag ) ; flag = false ; dfs ( 1 , 0 , 2 , 1 , b , flag ) ; int i = 0 ; while ( path [ 1 ] [ i ] == path [ 2 ] [ i ] ) i ++ ; return path [ 1 ] [ i - 1 ] ; } void addEdge ( int a , int b ) { tree [ a ] . push_back ( b ) ; tree [ b ] . push_back ( a ) ; } int main ( ) { int n = 8 ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 2 , 6 ) ; addEdge ( 3 , 7 ) ; addEdge ( 3 , 8 ) ; cout << " LCA ( 4 , β 7 ) β = β " << LCA ( 4 , 7 ) << endl ; cout << " LCA ( 4 , β 6 ) β = β " << LCA ( 4 , 6 ) << endl ; return 0 ; } |
LCA for general or n | Sparse Matrix DP approach to find LCA of two nodes ; pre - compute the depth for each node and their first parent ( 2 ^ 0 th parent ) time complexity : O ( n ) ; Dynamic Programming Sparse Matrix Approach populating 2 ^ i parent for each node Time complexity : O ( nlogn ) ; Returning the LCA of u and v Time complexity : O ( log n ) ; Step 1 of the pseudocode ; now depth [ u ] = = depth [ v ] ; Step 2 of the pseudocode ; driver function ; running dfs and precalculating depth of each node . ; Precomputing the 2 ^ i th ancestor for evey node ; calling the LCA function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 100000 NEW_LINE #define level 18 NEW_LINE vector < int > tree [ MAXN ] ; int depth [ MAXN ] ; int parent [ MAXN ] [ level ] ; void dfs ( int cur , int prev ) { depth [ cur ] = depth [ prev ] + 1 ; parent [ cur ] [ 0 ] = prev ; for ( int i = 0 ; i < tree [ cur ] . size ( ) ; i ++ ) { if ( tree [ cur ] [ i ] != prev ) dfs ( tree [ cur ] [ i ] , cur ) ; } } void precomputeSparseMatrix ( int n ) { for ( int i = 1 ; i < level ; i ++ ) { for ( int node = 1 ; node <= n ; node ++ ) { if ( parent [ node ] [ i - 1 ] != -1 ) parent [ node ] [ i ] = parent [ parent [ node ] [ i - 1 ] ] [ i - 1 ] ; } } } int lca ( int u , int v ) { if ( depth [ v ] < depth [ u ] ) swap ( u , v ) ; int diff = depth [ v ] - depth [ u ] ; for ( int i = 0 ; i < level ; i ++ ) if ( ( diff >> i ) & 1 ) v = parent [ v ] [ i ] ; if ( u == v ) return u ; for ( int i = level - 1 ; i >= 0 ; i -- ) if ( parent [ u ] [ i ] != parent [ v ] [ i ] ) { u = parent [ u ] [ i ] ; v = parent [ v ] [ i ] ; } return parent [ u ] [ 0 ] ; } void addEdge ( int u , int v ) { tree [ u ] . push_back ( v ) ; tree [ v ] . push_back ( u ) ; } int main ( ) { memset ( parent , -1 , sizeof ( parent ) ) ; int n = 8 ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 2 , 6 ) ; addEdge ( 3 , 7 ) ; addEdge ( 3 , 8 ) ; depth [ 0 ] = 0 ; dfs ( 1 , 0 ) ; precomputeSparseMatrix ( n ) ; cout << " LCA ( 4 , β 7 ) β = β " << lca ( 4 , 7 ) << endl ; cout << " LCA ( 4 , β 6 ) β = β " << lca ( 4 , 6 ) << endl ; return 0 ; } |
Longest Common Extension / LCE | Set 1 ( Introduction and Naive Method ) | A C ++ Program to find the length of longest common extension using Naive Method ; Structure to represent a query of form ( L , R ) ; A utility function to find longest common extension from index - L and index - R ; A function to answer queries of longest common extension ; Driver Program to test above functions ; LCA Queries to answer | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Query { int L , R ; } ; int LCE ( string str , int n , int L , int R ) { int length = 0 ; while ( str [ L + length ] == str [ R + length ] && R + length < n ) length ++ ; return ( length ) ; } void LCEQueries ( string str , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L ; int R = q [ i ] . R ; printf ( " LCE β ( % d , β % d ) β = β % d STRNEWLINE " , L , R , LCE ( str , n , L , R ) ) ; } return ; } int main ( ) { string str = " abbababba " ; int n = str . length ( ) ; Query q [ ] = { { 1 , 2 } , { 1 , 6 } , { 0 , 5 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; LCEQueries ( str , n , q , m ) ; return ( 0 ) ; } |
Tarjan 's off | A C ++ Program to implement Tarjan Offline LCA Algorithm ; number of nodes in input tree ; COLOUR ' WHITE ' is assigned value 1 ; COLOUR ' BLACK ' is assigned value 2 ; A binary tree node has data , pointer to left child and a pointer to right child ; subset [ i ] . parent -- > Holds the parent of node - ' i ' subset [ i ] . rank -- > Holds the rank of node - ' i ' subset [ i ] . ancestor -- > Holds the LCA queries answers subset [ i ] . child -- > Holds one of the child of node - ' i ' if present , else - '0' subset [ i ] . sibling -- > Holds the right - sibling of node - ' i ' if present , else - '0' subset [ i ] . color -- > Holds the colour of node - ' i ' ; Structure to represent a query A query consists of ( L , R ) and we will process the queries offline a / c to Tarjan 's oflline LCA algorithm ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; A utility function to make set ; A utility function to find set of an element i ( uses path compression technique ) ; find root and make root as parent of i ( path compression ) ; A function that does union of two sets of x and y ( uses union by rank ) ; Attach smaller rank tree under root of high rank tree ( Union by Rank ) ; If ranks are same , then make one as root and increment its rank by one ; The main function that prints LCAs . u is root 's data. m is size of q[] ; Make Sets ; Initially , each node 's ancestor is the node itself. ; This while loop doesn 't run for more than 2 times as there can be at max. two children of a node ; This is basically an inorder traversal and we preprocess the arrays -> child [ ] and sibling [ ] in " struct β subset " with the tree structure using this function . ; Recur on left child ; Note that the below two lines can also be this - subsets [ node -> data ] . child = node -> right -> data ; subsets [ node -> right -> data ] . sibling = node -> left -> data ; This is because if both left and right children of node - ' i ' are present then we can store any of them in subsets [ i ] . child and correspondingly its sibling ; Recur on right child ; A function to initialise prior to pre - processing and LCA walk ; Initialising the structure with 0 's ; Prints LCAs for given queries q [ 0. . m - 1 ] in a tree with given root ; Allocate memory for V subsets and nodes ; Creates subsets and colors them WHITE ; Preprocess the tree ; Perform a tree walk to process the LCA queries offline ; Driver program to test above functions ; We construct a binary tree : - 1 / \ 2 3 / \ 4 5 ; LCA Queries to answer | #include <bits/stdc++.h> NEW_LINE #define V 5 NEW_LINE #define WHITE 1 NEW_LINE #define BLACK 2 NEW_LINE struct Node { int data ; Node * left , * right ; } ; struct subset { int parent , rank , ancestor , child , sibling , color ; } ; struct Query { int L , R ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void makeSet ( struct subset subsets [ ] , int i ) { if ( i < 1 i > V ) return ; subsets [ i ] . color = WHITE ; subsets [ i ] . parent = i ; subsets [ i ] . rank = 0 ; return ; } int findSet ( struct subset subsets [ ] , int i ) { if ( subsets [ i ] . parent != i ) subsets [ i ] . parent = findSet ( subsets , subsets [ i ] . parent ) ; return subsets [ i ] . parent ; } void unionSet ( struct subset subsets [ ] , int x , int y ) { int xroot = findSet ( subsets , x ) ; int yroot = findSet ( subsets , y ) ; if ( subsets [ xroot ] . rank < subsets [ yroot ] . rank ) subsets [ xroot ] . parent = yroot ; else if ( subsets [ xroot ] . rank > subsets [ yroot ] . rank ) subsets [ yroot ] . parent = xroot ; else { subsets [ yroot ] . parent = xroot ; ( subsets [ xroot ] . rank ) ++ ; } } void lcaWalk ( int u , struct Query q [ ] , int m , struct subset subsets [ ] ) { makeSet ( subsets , u ) ; subsets [ findSet ( subsets , u ) ] . ancestor = u ; int child = subsets [ u ] . child ; while ( child != 0 ) { lcaWalk ( child , q , m , subsets ) ; unionSet ( subsets , u , child ) ; subsets [ findSet ( subsets , u ) ] . ancestor = u ; child = subsets [ child ] . sibling ; } subsets [ u ] . color = BLACK ; for ( int i = 0 ; i < m ; i ++ ) { if ( q [ i ] . L == u ) { if ( subsets [ q [ i ] . R ] . color == BLACK ) { printf ( " LCA ( % d β % d ) β - > β % d STRNEWLINE " , q [ i ] . L , q [ i ] . R , subsets [ findSet ( subsets , q [ i ] . R ) ] . ancestor ) ; } } else if ( q [ i ] . R == u ) { if ( subsets [ q [ i ] . L ] . color == BLACK ) { printf ( " LCA ( % d β % d ) β - > β % d STRNEWLINE " , q [ i ] . L , q [ i ] . R , subsets [ findSet ( subsets , q [ i ] . L ) ] . ancestor ) ; } } } return ; } void preprocess ( Node * node , struct subset subsets [ ] ) { if ( node == NULL ) return ; preprocess ( node -> left , subsets ) ; if ( node -> left != NULL && node -> right != NULL ) { subsets [ node -> data ] . child = node -> left -> data ; subsets [ node -> left -> data ] . sibling = node -> right -> data ; } else if ( ( node -> left != NULL && node -> right == NULL ) || ( node -> left == NULL && node -> right != NULL ) ) { if ( node -> left != NULL && node -> right == NULL ) subsets [ node -> data ] . child = node -> left -> data ; else subsets [ node -> data ] . child = node -> right -> data ; } preprocess ( node -> right , subsets ) ; } void initialise ( struct subset subsets [ ] ) { memset ( subsets , 0 , ( V + 1 ) * sizeof ( struct subset ) ) ; for ( int i = 1 ; i <= V ; i ++ ) subsets [ i ] . color = WHITE ; return ; } void printLCAs ( Node * root , Query q [ ] , int m ) { struct subset * subsets = new subset [ V + 1 ] ; initialise ( subsets ) ; preprocess ( root , subsets ) ; lcaWalk ( root -> data , q , m , subsets ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; Query q [ ] = { { 5 , 4 } , { 1 , 3 } , { 2 , 3 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; printLCAs ( root , q , m ) ; return 0 ; } |
Heavy Light Decomposition | Set 2 ( Implementation ) | C ++ program for Heavy - Light Decomposition of a tree ; Matrix representing the tree ; a tree node structure . Every node has a parent , depth , subtree size , chain to which it belongs and a position in base array ; Parent of this node ; Depth of this node ; Size of subtree rooted with this node ; Position in segment tree base ; every Edge has a weight and two ends . We store deeper end ; Weight of Edge ; Deeper end ; we construct one segment tree , on base array ; A function to add Edges to the Tree matrix e is Edge ID , u and v are the two nodes , w is weight ; tree as undirected graph ; A recursive function for DFS on the tree curr is the current node , prev is the parent of curr , dep is its depth ; set parent of current node to predecessor ; for node 's every child ; set deeper end of the Edge as this child ; do a DFS on subtree ; update subtree size ; A recursive function that decomposes the Tree into chains ; if the current chain has no head , this node is the first node * and also chain head ; set chain ID to which the node belongs ; set position of node in the array acting as the base to the segment tree ; update array which is the base to the segment tree ; Find the special child ( child with maximum size ) ; if special child found , extend chain ; for every other ( normal ) child , do HLD on child subtree as separate chain ; A recursive function that constructs Segment Tree for array [ ss . . se ) . si is index of current node in segment tree st ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the minimum of two values in this node ; A recursive function that updates the Segment Tree x is the node to be updated to value val si is the starting index of the segment tree ss , se mark the corners of the range represented by si ; A function to update Edge e 's value to val in segment tree ; following lines of code make no change to our case as we are changing in ST above Edge_weights [ e ] = val ; segtree_Edges_weights [ deeper_end_of_edge [ e ] ] = val ; ; A function to get the LCA of nodes u and v ; array for storing path from u to root ; Set u is deeper node if it is not ; LCA_aux will store path from node u to the root ; find first node common in path from v to root and u to root using LCA_aux ; A recursive function to get the minimum value in a given range of array indexes . The following are parameters for this function . st -- > Pointer to segment tree index -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node , i . e . , st [ index ] qs & qe -- > Starting and ending indexes of query range ; If segment of this node is a part of given range , then return the min of the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; Return minimum of elements in range from index qs ( query start ) to qe ( query end ) . It mainly uses RMQUtil ( ) ; Check for erroneous input values ; A function to move from u to v keeping track of the maximum we move to the surface changing u and chains until u and v donot belong to the same ; if the two nodes belong to same chain , * we can query between their positions in the array * acting as base to the segment tree . After the RMQ , * we can break out as we have no where further to go ; trivial ; else , we query between node u and head of the chain to which u belongs and later change u to parent of head of the chain to which u belongs indicating change of chain ; A function for MAX_EDGE query ; driver function ; fill adjacency matrix with - 1 to indicate no connections ; arguments in order : Edge ID , node u , node v , weight w ; our tree is rooted at node 0 at depth 0 ; a DFS on the tree to set up : * arrays for parent , depth , subtree size for every node ; * deeper end of every Edge ; we have initialized no chain heads ; Stores number of edges for construction of segment tree . Initially we haven 't traversed any Edges. ; we start with filling the 0 th chain ; HLD of tree ; ST of segregated Edges ; Since indexes are 0 based , node 11 means index 11 - 1 , 8 means 8 - 1 , and so on ; Change value of edge number 8 ( index 8 - 1 ) to 28 ; Change value of edge number 5 ( index 5 - 1 ) to 22 | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1024 NEW_LINE int tree [ N ] [ N ] ; struct treeNode { int par ; int depth ; int size ; int pos_segbase ; int chain ; } node [ N ] ; struct Edge { int weight ; int deeper_end ; } edge [ N ] ; struct segmentTree { int base_array [ N ] , tree [ 6 * N ] ; } s ; void addEdge ( int e , int u , int v , int w ) { tree [ u - 1 ] [ v - 1 ] = e - 1 ; tree [ v - 1 ] [ u - 1 ] = e - 1 ; edge [ e - 1 ] . weight = w ; } void dfs ( int curr , int prev , int dep , int n ) { node [ curr ] . par = prev ; node [ curr ] . depth = dep ; node [ curr ] . size = 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != curr && j != node [ curr ] . par && tree [ curr ] [ j ] != -1 ) { edge [ tree [ curr ] [ j ] ] . deeper_end = j ; dfs ( j , curr , dep + 1 , n ) ; node [ curr ] . size += node [ j ] . size ; } } } void hld ( int curr_node , int id , int * edge_counted , int * curr_chain , int n , int chain_heads [ ] ) { if ( chain_heads [ * curr_chain ] == -1 ) chain_heads [ * curr_chain ] = curr_node ; node [ curr_node ] . chain = * curr_chain ; node [ curr_node ] . pos_segbase = * edge_counted ; s . base_array [ ( * edge_counted ) ++ ] = edge [ id ] . weight ; int spcl_chld = -1 , spcl_edg_id ; for ( int j = 0 ; j < n ; j ++ ) if ( j != curr_node && j != node [ curr_node ] . par && tree [ curr_node ] [ j ] != -1 ) if ( spcl_chld == -1 node [ spcl_chld ] . size < node [ j ] . size ) spcl_chld = j , spcl_edg_id = tree [ curr_node ] [ j ] ; if ( spcl_chld != -1 ) hld ( spcl_chld , spcl_edg_id , edge_counted , curr_chain , n , chain_heads ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != curr_node && j != node [ curr_node ] . par && j != spcl_chld && tree [ curr_node ] [ j ] != -1 ) { ( * curr_chain ) ++ ; hld ( j , tree [ curr_node ] [ j ] , edge_counted , curr_chain , n , chain_heads ) ; } } } int construct_ST ( int ss , int se , int si ) { if ( ss == se - 1 ) { s . tree [ si ] = s . base_array [ ss ] ; return s . base_array [ ss ] ; } int mid = ( ss + se ) / 2 ; s . tree [ si ] = max ( construct_ST ( ss , mid , si * 2 ) , construct_ST ( mid , se , si * 2 + 1 ) ) ; return s . tree [ si ] ; } int update_ST ( int ss , int se , int si , int x , int val ) { if ( ss > x se <= x ) ; else if ( ss == x && ss == se - 1 ) s . tree [ si ] = val ; else { int mid = ( ss + se ) / 2 ; s . tree [ si ] = max ( update_ST ( ss , mid , si * 2 , x , val ) , update_ST ( mid , se , si * 2 + 1 , x , val ) ) ; } return s . tree [ si ] ; } void change ( int e , int val , int n ) { update_ST ( 0 , n , 1 , node [ edge [ e ] . deeper_end ] . pos_segbase , val ) ; } int LCA ( int u , int v , int n ) { int LCA_aux [ n + 5 ] ; if ( node [ u ] . depth < node [ v ] . depth ) swap ( u , v ) ; memset ( LCA_aux , -1 , sizeof ( LCA_aux ) ) ; while ( u != -1 ) { LCA_aux [ u ] = 1 ; u = node [ u ] . par ; } while ( v ) { if ( LCA_aux [ v ] == 1 ) break ; v = node [ v ] . par ; } return v ; } int RMQUtil ( int ss , int se , int qs , int qe , int index ) { if ( qs <= ss && qe >= se - 1 ) return s . tree [ index ] ; if ( se - 1 < qs ss > qe ) return -1 ; int mid = ( ss + se ) / 2 ; return max ( RMQUtil ( ss , mid , qs , qe , 2 * index ) , RMQUtil ( mid , se , qs , qe , 2 * index + 1 ) ) ; } int RMQ ( int qs , int qe , int n ) { if ( qs < 0 qe > n -1 qs > qe ) { printf ( " Invalid β Input " ) ; return - 1 ; } return RMQUtil ( 0 , n , qs , qe , 1 ) ; } int crawl_tree ( int u , int v , int n , int chain_heads [ ] ) { int chain_u , chain_v = node [ v ] . chain , ans = 0 ; while ( true ) { chain_u = node [ u ] . chain ; if ( chain_u == chain_v ) { if ( u == v ) ; else ans = max ( RMQ ( node [ v ] . pos_segbase + 1 , node [ u ] . pos_segbase , n ) , ans ) ; break ; } else { ans = max ( ans , RMQ ( node [ chain_heads [ chain_u ] ] . pos_segbase , node [ u ] . pos_segbase , n ) ) ; u = node [ chain_heads [ chain_u ] ] . par ; } } return ans ; } void maxEdge ( int u , int v , int n , int chain_heads [ ] ) { int lca = LCA ( u , v , n ) ; int ans = max ( crawl_tree ( u , lca , n , chain_heads ) , crawl_tree ( v , lca , n , chain_heads ) ) ; printf ( " % d STRNEWLINE " , ans ) ; } int main ( ) { memset ( tree , -1 , sizeof ( tree ) ) ; int n = 11 ; addEdge ( 1 , 1 , 2 , 13 ) ; addEdge ( 2 , 1 , 3 , 9 ) ; addEdge ( 3 , 1 , 4 , 23 ) ; addEdge ( 4 , 2 , 5 , 4 ) ; addEdge ( 5 , 2 , 6 , 25 ) ; addEdge ( 6 , 3 , 7 , 29 ) ; addEdge ( 7 , 6 , 8 , 5 ) ; addEdge ( 8 , 7 , 9 , 30 ) ; addEdge ( 9 , 8 , 10 , 1 ) ; addEdge ( 10 , 8 , 11 , 6 ) ; int root = 0 , parent_of_root = -1 , depth_of_root = 0 ; dfs ( root , parent_of_root , depth_of_root , n ) ; int chain_heads [ N ] ; memset ( chain_heads , -1 , sizeof ( chain_heads ) ) ; int edge_counted = 0 ; int curr_chain = 0 ; hld ( root , n - 1 , & edge_counted , & curr_chain , n , chain_heads ) ; construct_ST ( 0 , edge_counted , 1 ) ; int u = 11 , v = 9 ; cout << " Max β edge β between β " << u << " β and β " << v << " β is β " ; maxEdge ( u - 1 , v - 1 , n , chain_heads ) ; change ( 8 - 1 , 28 , n ) ; cout << " After β Change : β max β edge β between β " << u << " β and β " << v << " β is β " ; maxEdge ( u - 1 , v - 1 , n , chain_heads ) ; v = 4 ; cout << " Max β edge β between β " << u << " β and β " << v << " β is β " ; maxEdge ( u - 1 , v - 1 , n , chain_heads ) ; change ( 5 - 1 , 22 , n ) ; cout << " After β Change : β max β edge β between β " << u << " β and β " << v << " β is β " ; maxEdge ( u - 1 , v - 1 , n , chain_heads ) ; return 0 ; } |
Time Complexity and Space Complexity | C ++ program for the above approach ; Function to find a pair in the given array whose sum is equal to z ; Iterate through all the pairs ; Check if the sum of the pair ( a [ i ] , a [ j ] ) is equal to z ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool findPair ( int a [ ] , int n , int z ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( i != j && a [ i ] + a [ j ] == z ) return true ; return false ; } int main ( ) { int a [ ] = { 1 , -2 , 1 , 0 , 5 } ; int z = 0 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( findPair ( a , n , z ) ) cout << " True " ; else cout << " False " ; return 0 ; } |
Analysis of Algorithms | Big | C ++ program for the above approach ; Function to print all possible pairs ; Driver Code ; Given array ; Store the size of the array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int print ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i != j ) cout << a [ i ] << " β " << a [ j ] << " STRNEWLINE " ; } } } int main ( ) { int a [ ] = { 1 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; print ( a , n ) ; return 0 ; } |
Maximum sum obtained by dividing Array into several subarrays as per given conditions | C ++ program for the above approach ; Function to find the required answer ; Stores maximum sum ; Adding the difference of elements at ends of increasing subarray to the answer ; Driver Code ; Input ; Functio calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int arr [ ] , int N ) { int Sum = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) Sum += ( arr [ i ] - arr [ i - 1 ] ) ; } return Sum ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 } ; int N = ( sizeof ( arr ) / ( sizeof ( arr [ 0 ] ) ) ) ; cout << maximumSum ( arr , N ) ; return 0 ; } |
Efficient method to store a Lower Triangular Matrix using Column | C ++ program for the above approach ; Dimensions of the matrix ; Structure of a memory efficient matrix ; Function to set the values in the Matrix ; Function to store the values in the Matrix ; Function to display the elements of the matrix ; Traverse the matrix ; Function to generate an efficient matrix ; Declare efficient Matrix ; Initialize the Matrix ; Set the values in matrix ; Return the matrix ; Driver Code ; Given Input ; Function call to create a memory efficient matrix ; Function call to print the Matrix | #include <bits/stdc++.h> NEW_LINE #include <stdio.h> NEW_LINE using namespace std ; const int N = 5 ; struct Matrix { int * A ; int size ; } ; void Set ( struct Matrix * m , int i , int j , int x ) { if ( i >= j ) m -> A [ ( ( m -> size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] = x ; } int Get ( struct Matrix m , int i , int j ) { if ( i >= j ) return m . A [ ( ( m . size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] ; else return 0 ; } void Display ( struct Matrix m ) { for ( int i = 1 ; i <= m . size ; i ++ ) { for ( int j = 1 ; j <= m . size ; j ++ ) { if ( i >= j ) cout << m . A [ ( ( m . size ) * ( j - 1 ) - ( ( ( j - 2 ) * ( j - 1 ) ) / 2 ) + ( i - j ) ) ] << " β " ; else cout << "0 β " ; } cout << endl ; } } struct Matrix createMat ( int Mat [ N ] [ N ] ) { struct Matrix mat ; mat . size = N ; mat . A = ( int * ) malloc ( mat . size * ( mat . size + 1 ) / 2 * sizeof ( int ) ) ; for ( int i = 1 ; i <= mat . size ; i ++ ) { for ( int j = 1 ; j <= mat . size ; j ++ ) { Set ( & mat , i , j , Mat [ i - 1 ] [ j - 1 ] ) ; } } return mat ; } int main ( ) { int Mat [ 5 ] [ 5 ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 2 , 0 , 0 , 0 } , { 1 , 2 , 3 , 0 , 0 } , { 1 , 2 , 3 , 4 , 0 } , { 1 , 2 , 3 , 4 , 5 } } ; struct Matrix mat = createMat ( Mat ) ; Display ( mat ) ; return 0 ; } |
Examples of Big | C ++ program to illustrate time complexity for single for - loop ; Driver Code ; This loop runs for N time ; This loop runs for M time | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int a = 0 , b = 0 ; int N = 4 , M = 4 ; for ( int i = 0 ; i < N ; i ++ ) { a = a + 10 ; } for ( int i = 0 ; i < M ; i ++ ) { b = b + 40 ; } cout << a << ' β ' << b ; return 0 ; } |
The Slowest Sorting Algorithms | C ++ program for the stooge sort ; Function to implement stooge sort ; Base Case ; If first element is smaller than last element , swap them ; If there are more than 2 elements in the array ; Recursively sort the first 2 / 3 elements ; Recursively sort the last 2 / 3 elements ; Recursively sort the first 2 / 3 elements again ; Driver Code ; Function Call ; Display the sorted array | #include <iostream> NEW_LINE using namespace std ; void stoogesort ( int arr [ ] , int l , int h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) swap ( arr [ l ] , arr [ h ] ) ; if ( h - l + 1 > 2 ) { int t = ( h - l + 1 ) / 3 ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; stoogesort ( arr , 0 , N - 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } return 0 ; } |
Time | C ++ program to find Nth Fibonacci number using recursion ; Function to find Nth Fibonacci term ; Base Case ; Recursively computing the term using recurrence relation ; Driver Code ; Function Call | #include <iostream> NEW_LINE using namespace std ; int Fibonacci ( int N ) { if ( N < 2 ) return N ; return Fibonacci ( N - 1 ) + Fibonacci ( N - 2 ) ; } int main ( ) { int N = 5 ; cout << Fibonacci ( N ) ; return 0 ; } |
Determine winner of the Game by arranging balls in a row | C ++ program for the above approach ; Function to find the winner of the Game by arranging the balls in a row ; Check if small balls are greater or equal to the large ones ; X can place balls therefore scores n - 1 ; Condition if large balls are greater than small ; X can have m - 1 as a score since greater number of balls can only be adjacent ; Compare the score ; Driver Code ; Given number of small balls ( N ) and number of large balls ( M ) ; Function call | #include <iostream> NEW_LINE using namespace std ; void findWinner ( int n , int m ) { int X = 0 ; int Y = 0 ; if ( n >= m ) { X = n - 1 ; Y = m ; } else { X = m - 1 ; Y = n ; } if ( X > Y ) cout << " X " ; else if ( Y > X ) cout << " Y " ; else cout << " - 1" ; } int main ( ) { int n = 3 , m = 1 ; findWinner ( n , m ) ; return 0 ; } |
Check if Pascal 's Triangle is possible with a complete layer by using numbers upto N | C ++ program for the above approach ; Function to check if Pascaltriangle can be made by N integers ; Find X ; If x is integer ; Driver Code ; Given number N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkPascaltriangle ( int N ) { double x = ( sqrt ( 8 * N + 1 ) - 1 ) / 2 ; if ( ceil ( x ) - x == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int N = 10 ; checkPascaltriangle ( N ) ; return 0 ; } |
Count subarrays having sum of elements at even and odd positions equal | C program for the above approach ; Function to count subarrays in which sum of elements at even and odd positions are equal ; Initialize variables ; Iterate over the array ; Check if position is even then add to sum then add it to sum ; Else subtract it to sum ; Increment the count if the sum equals 0 ; Print the count of subarrays ; Driver Code ; Given array arr [ ] ; Size of the array ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubarrays ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( ( j - i ) % 2 == 0 ) sum += arr [ j ] ; else sum -= arr [ j ] ; if ( sum == 0 ) count ++ ; } } cout << " β " << count ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countSubarrays ( arr , n ) ; return 0 ; } |
Find position of non | C ++ implementation to find count of placing non - attacking rooks on the N x N chessboard ; Function to find the count of placing non - attacking rooks on the N x N chessboard ; Count of the Non - attacking rooks ; Printing lexographically smallest configuration ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findCountRooks ( int row [ ] , int col [ ] , int n , int k ) { int res = n - k ; cout << res << " STRNEWLINE " ; int ri = 0 , ci = 0 ; while ( res -- > 0 ) { while ( ri < k && row [ ri ] == 1 ) { ri ++ ; } while ( ci < k && col [ ci ] == 1 ) { ci ++ ; } cout << ( ri + 1 ) << " β " << ( ci + 1 ) << " STRNEWLINE " ; ri ++ ; ci ++ ; } } int main ( ) { int n = 4 ; int k = 2 ; int row [ ] = { 1 , 2 } ; int col [ ] = { 4 , 2 } ; findCountRooks ( row , col , n , k ) ; return 0 ; } |
Check if a large number is divisible by a number which is a power of 2 | C ++ program for the above approach ; Function to check divisibility ; Calculate the number of digits in num ; Check if the length of the string is less than the powerOf2 then return false ; Check if the powerOf2 is 0 that means the given number is 1 and as every number is divisible by 1 so return true ; Find the number which is formed by the last n digits of the string where n = powerOf2 ; Check if the number formed is divisible by input num or not ; Driver Code ; Given number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIfDivisible ( string str , long long int num ) { long long int powerOf2 = log2 ( num ) ; if ( str . length ( ) < powerOf2 ) return false ; if ( powerOf2 == 0 ) return true ; long long int i , number = 0 ; int len = str . length ( ) ; for ( i = len - powerOf2 ; i < len ; i ++ ) { number += ( str [ i ] - '0' ) * pow ( 10 , powerOf2 - 1 ) ; powerOf2 -- ; } if ( number % num ) return false ; else return true ; } int main ( ) { string str = "213467756564" ; long long int num = 4 ; if ( checkIfDivisible ( str , num ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Check if given permutation of 1 to N can be counted in clockwise or anticlockwise direction | C ++ program to check Clockwise or counterclockwise order in an array ; Comparing the first and last value of array ; If the Count is greater than 1 then it can 't be represented in required order ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check_order ( vector < int > arr ) { int cnt = 0 ; for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) { if ( abs ( arr [ i + 1 ] - arr [ i ] ) > 1 ) cnt ++ ; } if ( abs ( arr [ 0 ] - arr [ arr . size ( ) - 1 ] ) > 1 ) cnt ++ ; if ( cnt > 1 ) return false ; return true ; } int main ( ) { vector < int > arr = { 2 , 3 , 4 , 5 , 1 } ; if ( check_order ( arr ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Largest number M less than N such that XOR of M and N is even | C ++ program for the above problem . ; Function to find the maximum possible value of M ; Edge case ; M = N - 2 is maximum possible value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getM ( int n ) { if ( n == 1 ) return -1 ; else return n - 2 ; } int main ( ) { int n = 10 ; int ans = getM ( n ) ; cout << ans ; } |
Maximize profit in buying and selling stocks with Rest condition | C ++ program for the above problem ; If there is only one day for buying and selling no profit can be made ; Array to store Maxprofit by resting on given day ; Array to store Maxprofit by buying or resting on the given day ; Array to store Maxprofit by selling on given day ; Initially there will 0 profit ; Buying on 1 st day results in negative profit ; zero profit since selling before buying isn 't possible ; max of profit on ( i - 1 ) th day by resting and profit on ( i - 1 ) th day by selling . ; max of profit by resting on ith day and buying on ith day . ; max of profit by selling on ith day ; maxprofit ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( int prices [ ] , int n ) { if ( n <= 1 ) return 0 ; int rest [ n ] = { 0 } ; int hold [ n ] = { 0 } ; int sold [ n ] = { 0 } ; rest [ 0 ] = 0 ; hold [ 0 ] = - prices [ 0 ] ; sold [ 0 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { rest [ i ] = max ( rest [ i - 1 ] , sold [ i - 1 ] ) ; hold [ i ] = max ( hold [ i - 1 ] , rest [ i - 1 ] - prices [ i ] ) ; sold [ i ] = hold [ i - 1 ] + prices [ i ] ; } return max ( rest [ n - 1 ] , sold [ n - 1 ] ) ; } int main ( ) { int price [ ] = { 2 , 4 , 5 , 0 , 2 } ; int n = sizeof ( price ) / sizeof ( price [ 0 ] ) ; cout << maxProfit ( price , n ) << endl ; return 0 ; } |
Count of subarrays of size K having at least one pair with absolute difference divisible by K | C ++ implementation of the above approach ; Function to return the required number of subarrays ; Return number of possible subarrays of length K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubarrays ( int arr [ ] , int N , int K ) { return N - K + 1 ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 2 , 17 , 18 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubarrays ( arr , N , K ) ; return 0 ; } |
Maximum length of subarray such that all elements are equal in the subarray | C ++ program for the above approach ; Function to find the longest subarray with same element ; Check if the elements are same then we can increment the length ; Reinitialize j ; Compare the maximum length e with j ; Return max length ; Driver Code ; Given array arr [ ] ; Function Call | #include <iostream> NEW_LINE using namespace std ; int longest_subarray ( int arr [ ] , int d ) { int i = 0 , j = 1 , e = 0 ; for ( i = 0 ; i < d - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { j = j + 1 ; } else { j = 1 ; } if ( e < j ) { e = j ; } } return e ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longest_subarray ( arr , N ) ; } |
Print all Strong numbers less than or equal to N | C ++ program for the above approach ; Store the factorial of all the digits from [ 0 , 9 ] ; Function to return true if number is strong or not ; Converting N to String so that can easily access all it 's digit ; sum will store summation of factorial of all digits of a number N ; Returns true of N is strong number ; Function to print all strong number till N ; Iterating from 1 to N ; Checking if a number is strong then print it ; Driver Code ; Given number ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial [ ] = { 1 , 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880 } ; bool isStrong ( int N ) { string num = to_string ( N ) ; int sum = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) { sum += factorial [ num [ i ] - '0' ] ; } return sum == N ; } void printStrongNumbers ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { if ( isStrong ( i ) ) { cout << i << " β " ; } } } int main ( ) { int N = 1000 ; printStrongNumbers ( N ) ; return 0 ; } |
Count of pairs in a given range with sum of their product and sum equal to their concatenated number | C ++ program to count all the possible pairs with X * Y + ( X + Y ) equal to number formed by concatenating X and Y ; Function for counting pairs ; Count possible values of Y ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int A , int B ) { int countY = 0 , countX = ( B - A ) + 1 , next_val = 9 ; while ( next_val <= B ) { if ( next_val >= A ) { countY += 1 ; } next_val = next_val * 10 + 9 ; } return ( countX * countY ) ; } int main ( ) { int A = 1 ; int B = 16 ; cout << countPairs ( A , B ) ; return 0 ; } |
Minimum sprinklers required to water a rectangular park | C ++ program to find the minimum number sprinklers required to water the park . ; Function to find the minimum number sprinklers required to water the park . ; General requirements of sprinklers ; if M is odd then add one additional sprinklers ; Driver code | #include <iostream> NEW_LINE using namespace std ; typedef long long int ll ; void solve ( int N , int M ) { ll ans = ( N ) * ( M / 2 ) ; if ( M % 2 == 1 ) { ans += ( N + 1 ) / 2 ; } cout << ans << endl ; } int main ( ) { int N , M ; N = 5 ; M = 3 ; solve ( N , M ) ; } |
Queries to find frequencies of a string within specified substrings | C ++ Program to find frequency of a string K in a substring [ L , R ] in S ; Store the frequency of string for each index ; Compute and store frequencies for every index ; Driver Code | #include <bits/stdc++.h> NEW_LINE #define max_len 100005 NEW_LINE using namespace std ; int cnt [ max_len ] ; void precompute ( string s , string K ) { int n = s . size ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { cnt [ i + 1 ] = cnt [ i ] + ( s . substr ( i , K . size ( ) ) == K ) ; } } int main ( ) { string s = " ABCABCABABC " ; string K = " ABC " ; precompute ( s , K ) ; vector < pair < int , int > > Q = { { 1 , 6 } , { 5 , 11 } } ; for ( auto it : Q ) { cout << cnt [ it . second - 1 ] - cnt [ it . first - 1 ] << endl ; } return 0 ; } |
XOR of elements in a given range with updates using Fenwick Tree | C ++ Program to find XOR of elements in given range [ L , R ] . ; Returns XOR of arr [ 0. . index ] . This function assumes that the array is preprocessed and partial XORs of array elements are stored in BITree [ ] . ; Traverse ancestors of BITree [ index ] ; XOR current element of BIT to ans ; Update index to that of the parent node in getXor ( ) view by subtracting LSB ( Least Significant Bit ) ; Updates the Binary Index Tree by replacing all ancestors of index by their respective XOR with val ; Traverse all ancestors and XOR with ' val ' . ; XOR ' val ' to current node of BIT ; Update index to that of the parent node in updateBit ( ) view by adding LSB ( Least Significant Bit ) ; Constructs and returns a Binary Indexed Tree for the given array ; Create and initialize the Binary Indexed Tree ; Store the actual values in BITree [ ] using update ( ) ; Driver Code ; Create the Binary Indexed Tree ; Solve each query in Q ; Update the values of all ancestors of idx | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getXOR ( int BITree [ ] , int index ) { int ans = 0 ; index += 1 ; while ( index > 0 ) { ans ^= BITree [ index ] ; index -= index & ( - index ) ; } return ans ; } void updateBIT ( int BITree [ ] , int n , int index , int val ) { index = index + 1 ; while ( index <= n ) { BITree [ index ] ^= val ; index += index & ( - index ) ; } } int * constructBITree ( int arr [ ] , int n ) { int * BITree = new int [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) BITree [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) updateBIT ( BITree , n , i , arr [ i ] ) ; return BITree ; } int rangeXor ( int BITree [ ] , int l , int r ) { return getXOR ( BITree , r ) ^ getXOR ( BITree , l - 1 ) ; } int main ( ) { int A [ ] = { 2 , 1 , 1 , 3 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; vector < vector < int > > q = { { 1 , 0 , 9 } , { 2 , 3 , 6 } , { 2 , 5 , 5 } , { 2 , 8 , 1 } , { 1 , 0 , 9 } } ; int * BITree = constructBITree ( A , n ) ; for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int id = q [ i ] [ 0 ] ; if ( id == 1 ) { int L = q [ i ] [ 1 ] ; int R = q [ i ] [ 2 ] ; cout << " XOR β of β elements β " << " in β given β range β is β " << rangeXor ( BITree , L , R ) << " STRNEWLINE " ; } else { int idx = q [ i ] [ 1 ] ; int val = q [ i ] [ 2 ] ; A [ idx ] ^= val ; updateBIT ( BITree , n , idx , val ) ; } } return 0 ; } |
Count of Double Prime numbers in a given range L to R | C ++ program to find the count of Double Prime numbers in the range L to R ; Array to make Sieve where arr [ i ] = 0 indicates non prime and arr [ i ] = 1 indicates prime ; Array to find double prime ; Function to find the number double prime numbers in range ; Assume all numbers as prime ; Check if the number is prime ; check for multiples of i ; Make all multiples of ith prime as non - prime ; Check if number at ith position is prime then increment count ; Indicates count of numbers from 1 to i that are also prime and hence double prime ; If number is not a double prime ; finding cumulative sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int arr [ 1000001 ] ; int dp [ 1000001 ] ; void count ( ) { int maxN = 1000000 , i , j ; for ( i = 0 ; i < maxN ; i ++ ) arr [ i ] = 1 ; arr [ 0 ] = 0 ; arr [ 1 ] = 0 ; for ( i = 2 ; i * i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) { for ( j = 2 * i ; j <= maxN ; j += i ) { arr [ j ] = 0 ; } } } int cnt = 0 ; for ( i = 0 ; i <= maxN ; i ++ ) { if ( arr [ i ] == 1 ) cnt ++ ; if ( arr [ cnt ] == 1 ) dp [ i ] = 1 ; else dp [ i ] = 0 ; } for ( i = 1 ; i <= maxN ; i ++ ) dp [ i ] += dp [ i - 1 ] ; } int main ( ) { int L = 4 , R = 12 ; count ( ) ; cout << dp [ R ] - dp [ L - 1 ] ; return 0 ; } |
Count of ungrouped characters after dividing a string into K groups of distinct characters | C ++ code to implement the above approach ; create array where index represents alphabets ; fill count of every alphabet to corresponding array index ; count for every element how much is exceeding from no . of groups then sum them ; print answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findUngroupedElement ( string s , int k ) { int n = s . length ( ) ; int b [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) b [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { char p = s . at ( i ) ; b [ p - ' a ' ] += 1 ; } int sum = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( b [ i ] > k ) sum += b [ i ] - k ; } cout << sum << endl ; } int main ( ) { string s = " stayinghomesaveslife " ; int k = 1 ; findUngroupedElement ( s , k ) ; return 0 ; } |
Range Queries to count the number of even parity values with updates | C ++ implementation to find number of Even Parity numbers in a subarray and performing updates ; Function that returns true if count of set bits in x is even ; parity will store the count of set bits ; A utility function to get the middle index ; Recursive function to get the number of Even Parity numbers in a given range ; If segment of this node is a part of given range , then return the number of Even Parity numbers in the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; Recursive function to update the nodes which have the given index in their range ; Base Case : ; If the input index is in range of this node , then update the value of the node and its children ; Function to update a value in the input array and segment tree ; Check for erroneous input index ; Update the value in array ; Case 1 : Old and new values both are Even Parity numbers ; Case 2 : Old and new values both not Even Parity numbers ; Case 3 : Old value was Even Parity , new value is non Even Parity ; Case 4 : Old value was non Even Parity , new_val is Even Parity ; Update the values of nodes in segment tree ; Return number of Even Parity numbers ; Recursive function that constructs Segment Tree for the given array ; If there is one element in array , check if it is Even Parity number then store 1 in the segment tree else store 0 and return ; if arr [ segmentStart ] is Even Parity number ; If there are more than one elements , then recur for left and right subtrees and store the sum of the two values in this node ; Function to construct a segment tree from given array ; Height of segment tree ; Maximum size of segment tree ; Fill the allocated memory st ; Return the constructed segment tree ; Driver Code ; Build segment tree from given array ; Query 1 : Query ( start = 0 , end = 4 ) ; Query 2 : Update ( i = 3 , x = 11 ) , i . e Update a [ i ] to x ; Query 3 : Query ( start = 0 , end = 4 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE bool isEvenParity ( int x ) { int parity = 0 ; while ( x != 0 ) { if ( x & 1 ) parity ++ ; x = x >> 1 ; } if ( parity % 2 == 0 ) return true ; else return false ; } int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } int queryEvenParityUtil ( int * segmentTree , int segmentStart , int segmentEnd , int queryStart , int queryEnd , int index ) { if ( queryStart <= segmentStart && queryEnd >= segmentEnd ) return segmentTree [ index ] ; if ( segmentEnd < queryStart segmentStart > queryEnd ) return 0 ; int mid = getMid ( segmentStart , segmentEnd ) ; return queryEvenParityUtil ( segmentTree , segmentStart , mid , queryStart , queryEnd , 2 * index + 1 ) + queryEvenParityUtil ( segmentTree , mid + 1 , segmentEnd , queryStart , queryEnd , 2 * index + 2 ) ; } void updateValueUtil ( int * segmentTree , int segmentStart , int segmentEnd , int i , int diff , int si ) { if ( i < segmentStart i > segmentEnd ) return ; segmentTree [ si ] = segmentTree [ si ] + diff ; if ( segmentEnd != segmentStart ) { int mid = getMid ( segmentStart , segmentEnd ) ; updateValueUtil ( segmentTree , segmentStart , mid , i , diff , 2 * si + 1 ) ; updateValueUtil ( segmentTree , mid + 1 , segmentEnd , i , diff , 2 * si + 2 ) ; } } void updateValue ( int arr [ ] , int * segmentTree , int n , int i , int new_val ) { if ( i < 0 i > n - 1 ) { printf ( " Invalid β Input " ) ; return ; } int diff , oldValue ; oldValue = arr [ i ] ; arr [ i ] = new_val ; if ( isEvenParity ( oldValue ) && isEvenParity ( new_val ) ) return ; if ( ! isEvenParity ( oldValue ) && ! isEvenParity ( new_val ) ) return ; if ( isEvenParity ( oldValue ) && ! isEvenParity ( new_val ) ) { diff = -1 ; } if ( ! isEvenParity ( oldValue ) && ! isEvenParity ( new_val ) ) { diff = 1 ; } updateValueUtil ( segmentTree , 0 , n - 1 , i , diff , 0 ) ; } void queryEvenParity ( int * segmentTree , int n , int queryStart , int queryEnd ) { int EvenParityInRange = queryEvenParityUtil ( segmentTree , 0 , n - 1 , queryStart , queryEnd , 0 ) ; cout << EvenParityInRange << " STRNEWLINE " ; } int constructSTUtil ( int arr [ ] , int segmentStart , int segmentEnd , int * segmentTree , int si ) { if ( segmentStart == segmentEnd ) { if ( isEvenParity ( arr [ segmentStart ] ) ) segmentTree [ si ] = 1 ; else segmentTree [ si ] = 0 ; return segmentTree [ si ] ; } int mid = getMid ( segmentStart , segmentEnd ) ; segmentTree [ si ] = constructSTUtil ( arr , segmentStart , mid , segmentTree , si * 2 + 1 ) + constructSTUtil ( arr , mid + 1 , segmentEnd , segmentTree , si * 2 + 2 ) ; return segmentTree [ si ] ; } int * constructST ( int arr [ ] , int n ) { int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int * segmentTree = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , segmentTree , 0 ) ; return segmentTree ; } int main ( ) { int arr [ ] = { 18 , 15 , 8 , 9 , 14 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * segmentTree = constructST ( arr , n ) ; int start = 0 ; int end = 4 ; queryEvenParity ( segmentTree , n , start , end ) ; int i = 3 ; int x = 11 ; updateValue ( arr , segmentTree , n , i , x ) ; start = 0 ; end = 4 ; queryEvenParity ( segmentTree , n , start , end ) ; return 0 ; } |
Generate an array of given size with equal count and sum of odd and even numbers | C ++ implementation to find the array containing same count of even and odd elements with equal sum of even and odd elements ; Function to find the array such that the array contains the same count of even and odd elements with equal sum of even and odd elements ; Length of array which is not divisible by 4 is unable to form such array ; Loop to find the resulted array containing the same count of even and odd elements ; Find the total sum of even elements ; Find the total sum of odd elements ; Find the difference between the total sum of even and odd elements ; The difference will be added in the last odd element ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSolution ( int N ) { if ( N % 4 != 0 ) cout << -1 << " STRNEWLINE " ; else { int temp = 0 , sum_odd = 0 , sum_even = 0 ; int result [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i += 2 ) { temp += 2 ; result [ i + 1 ] = temp ; sum_even += result [ i + 1 ] ; result [ i ] = temp - 1 ; sum_odd += result [ i ] ; } int diff = sum_even - sum_odd ; result [ N - 2 ] += diff ; for ( int i = 0 ; i < N ; i ++ ) cout << result [ i ] << " β " ; cout << " STRNEWLINE " ; } } int main ( ) { int N = 8 ; findSolution ( N ) ; return 0 ; } |
Number of ways to place two queens on a N * N chess | C ++ implementation to find the number of ways to place two queens on the N * N chess board ; Function to find number of valid positions for two queens in the N * N chess board ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE using namespace std ; ll possiblePositions ( ll n ) { ll term1 = pow ( n , 4 ) ; ll term2 = pow ( n , 3 ) ; ll term3 = pow ( n , 2 ) ; ll term4 = n / 3 ; ll ans = ( ceil ) ( term1 ) / 2 - ( ceil ) ( 5 * term2 ) / 3 + ( ceil ) ( 3 * term3 ) / 2 - term4 ; return ans ; } int main ( ) { ll n ; n = 3 ; ll ans = possiblePositions ( n ) ; cout << ans << endl ; return 0 ; } |
Group all co | C ++ implementation to group mutually coprime numbers into one group with minimum group possible ; Function to group the mutually co - prime numbers into one group ; Loop for the numbers less than the 4 ; Integers 1 , 2 and 3 can be grouped into one group ; Consecutive even and odd numbers ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void mutually_coprime ( int n ) { if ( n <= 3 ) { for ( int j = 1 ; j <= n ; j ++ ) { cout << j << " β " ; } cout << " STRNEWLINE " ; } else { cout << "1 β 2 β 3 STRNEWLINE " ; for ( int j = 4 ; j < n ; j += 2 ) { cout << j << " β " << j + 1 << " STRNEWLINE " ; } if ( n % 2 == 0 ) cout << n << " STRNEWLINE " ; } } int main ( ) { int n = 9 ; mutually_coprime ( n ) ; } |
Maximum sum subset having equal number of positive and negative elements | C ++ implementation to find the maximum sum subset having equal number of positive and negative elements in the subset ; Function to find maximum sum subset with equal number of positive and negative elements ; Loop to store the positive and negative elements in two different array ; Sort both the array ; Pointers starting from the highest elements ; Find pairs having sum greater than zero ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSum ( int * arr , int n ) { vector < int > a ; vector < int > b ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) { a . push_back ( arr [ i ] ) ; } else if ( arr [ i ] < 0 ) { b . push_back ( arr [ i ] ) ; } } sort ( a . begin ( ) , a . end ( ) ) ; sort ( b . begin ( ) , b . end ( ) ) ; int p = a . size ( ) - 1 ; int q = b . size ( ) - 1 ; int s = 0 ; while ( p >= 0 && q >= 0 ) { if ( a [ p ] + b [ q ] > 0 ) { s = s + a [ p ] + b [ q ] ; } else { break ; } p = p - 1 ; q = q - 1 ; } return s ; } int main ( ) { int arr1 [ ] = { 1 , -2 , 3 , 4 , -5 , 8 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << findMaxSum ( arr1 , n1 ) << endl ; return 0 ; } |
Print the nodes with a prime degree in given Prufer sequence of a Tree | C ++ implementation to print the nodes with prime degree from the given prufer sequence ; Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to print the nodes with prime degree in the tree whose Prufer sequence is given ; Hash - table to mark the degree of every node ; Initially let all the degrees be 1 ; Increase the count of the degree ; Print the nodes with prime degree ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } void PrimeDegreeNodes ( int prufer [ ] , int n ) { int nodes = n + 2 ; bool prime [ nodes + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , nodes + 1 ) ; int degree [ n + 2 + 1 ] ; for ( int i = 1 ; i <= nodes ; i ++ ) degree [ i ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) degree [ prufer [ i ] ] ++ ; for ( int i = 1 ; i <= nodes ; i ++ ) { if ( prime [ degree [ i ] ] ) { cout << i << " β " ; } } } int main ( ) { int a [ ] = { 4 , 1 , 3 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; PrimeDegreeNodes ( a , n ) ; return 0 ; } |
Find K 'th smallest number such that A + B = A | B | C ++ program for the above approach ; Function to find k 'th smallest number such that A + B = A | B ; res will store final answer ; Skip when j ' th β position β β has β 1 β in β binary β representation β β as β in β res , β j ' th position will be 0. ; j 'th bit is set ; If i ' th β bit β of β k β is β 1 β β and β i ' th bit of j is 0 then set i 'th bit in res. ; Proceed to next bit ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long kthSmallest ( long long a , long long k ) { long long res = 0 ; long long j = 0 ; for ( long long i = 0 ; i < 32 ; i ++ ) { while ( j < 32 && ( a & ( 1 << j ) ) ) { j ++ ; } if ( k & ( 1 << i ) ) { res |= ( 1LL << j ) ; } j ++ ; } return res ; } int main ( ) { long long a = 5 , k = 3 ; cout << kthSmallest ( a , k ) << " STRNEWLINE " ; return 0 ; } |
Nodes with prime degree in an undirected Graph | C ++ implementation of the approach ; To store Prime Numbers ; Function to find the prime numbers till 10 ^ 5 ; Traverse all multiple of i and make it false ; Function to print the nodes having prime degree ; To store Adjacency List of a Graph ; Make Adjacency List ; To precompute prime numbers till 10 ^ 5 ; Traverse each vertex ; Find size of Adjacency List ; If length of Adj [ i ] is Prime then print it ; Driver code ; Vertices and Edges ; Edges ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int n = 10005 ; vector < bool > Prime ( n + 1 , true ) ; void SieveOfEratosthenes ( ) { int i , j ; Prime [ 0 ] = Prime [ 1 ] = false ; for ( i = 2 ; i * i <= 10005 ; i ++ ) { if ( Prime [ i ] ) { for ( j = 2 * i ; j < 10005 ; j += i ) { Prime [ j ] = false ; } } } } void primeDegreeNodes ( int N , int M , int edges [ ] [ 2 ] ) { vector < int > Adj [ N + 1 ] ; for ( int i = 0 ; i < M ; i ++ ) { int x = edges [ i ] [ 0 ] ; int y = edges [ i ] [ 1 ] ; Adj [ x ] . push_back ( y ) ; Adj [ y ] . push_back ( x ) ; } SieveOfEratosthenes ( ) ; for ( int i = 1 ; i <= N ; i ++ ) { int x = Adj [ i ] . size ( ) ; if ( Prime [ x ] ) cout << i << ' β ' ; } } int main ( ) { int N = 4 , M = 6 ; int edges [ M ] [ 2 ] = { { 1 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 3 } , { 2 , 4 } , { 3 , 4 } } ; primeDegreeNodes ( N , M , edges ) ; return 0 ; } |
Number of ways to color N | C ++ program for the above approach ; Recursive function to count the ways ; Base case ; Initialise answer to 0 ; Color each uncolored block according to the given condition ; If any block is uncolored ; Check if adjacent blocks are colored or not ; Color the block ; recursively iterate for next uncolored block ; Uncolored for the next recursive call ; Return the final count ; Function to count the ways to color block ; Mark which blocks are colored in each recursive step ; Function call to count the ways ; Driver Code ; Number of blocks ; Number of colored blocks ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int mod = 1000000007 ; int countWays ( int colored [ ] , int count , int n ) { if ( count == n ) { return 1 ; } int answer = 0 ; for ( int i = 1 ; i < n + 1 ; i ++ ) { if ( colored [ i ] == 0 ) { if ( colored [ i - 1 ] == 1 colored [ i + 1 ] == 1 ) { colored [ i ] = 1 ; answer = ( answer + countWays ( colored , count + 1 , n ) ) % mod ; colored [ i ] = 0 ; } } } return answer ; } int waysToColor ( int arr [ ] , int n , int k ) { int colored [ n + 2 ] = { 0 } ; for ( int i = 0 ; i < k ; i ++ ) { colored [ arr [ i ] ] = 1 ; } return countWays ( colored , k , n ) ; } int main ( ) { int N = 6 ; int K = 3 ; int arr [ K ] = { 1 , 2 , 6 } ; cout << waysToColor ( arr , N , K ) ; return 0 ; } |
Shortest Palindromic Substring | C ++ program to find the shortest palindromic substring ; Function return the shortest palindromic substring ; Finding the smallest character present in the string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char ShortestPalindrome ( string s ) { int n = s . length ( ) ; char ans = s [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { ans = min ( ans , s [ i ] ) ; } return ans ; } int main ( ) { string s = " geeksforgeeks " ; cout << ShortestPalindrome ( s ) ; return 0 ; } |
Maximum length Subsequence with alternating sign and maximum Sum | C ++ implementation to find the subsequence with alternating sign having maximum size and maximum sum . ; Function to find the subsequence with alternating sign having maximum size and maximum sum . ; Find whether each element is positive or negative ; Find the required subsequence ; Find the maximum element in the specified range ; print the result ; Driver code ; array declaration ; size of array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubsequence ( int arr [ ] , int n ) { int sign [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) sign [ i ] = 1 ; else sign [ i ] = -1 ; } int k = 0 ; int result [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int cur = arr [ i ] ; int j = i ; while ( j < n && sign [ i ] == sign [ j ] ) { cur = max ( cur , arr [ j ] ) ; ++ j ; } result [ k ++ ] = cur ; i = j - 1 ; } for ( int i = 0 ; i < k ; i ++ ) cout << result [ i ] << " β " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { -4 , 9 , 4 , 11 , -5 , -17 , 9 , -3 , -5 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSubsequence ( arr , n ) ; return 0 ; } |
Longest Palindrome in a String formed by concatenating its prefix and suffix | C ++ program to find the longest palindrome in a string formed by concatenating its prefix and suffix ; Function to check whether the string is a palindrome ; Reverse the string to compare with the original string ; Check if both are same ; Function to find the longest palindrome in a string formed by concatenating its prefix and suffix ; Length of the string ; Finding the length upto which the suffix and prefix forms a palindrome together ; Check whether the string has prefix and suffix substrings which are palindromes . ; Removing the suffix and prefix substrings which already forms a palindrome and storing them in separate strings ; Check all prefix substrings in the remaining string str ; Check if the prefix substring is a palindrome ; If the prefix substring is a palindrome then check if it is of maximum length so far ; Check all the suffix substrings in the remaining string str ; Check if the suffix substring is a palindrome ; If the suffix substring is a palindrome then check if it is of maximum length so far ; Combining all the thee parts of the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string r ) { string p = r ; reverse ( p . begin ( ) , p . end ( ) ) ; return ( r == p ) ; } string PrefixSuffixPalindrome ( string str ) { int n = str . size ( ) , len = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) { if ( str [ i ] != str [ n - i - 1 ] ) { len = i ; break ; } } string prefix = " " , suffix = " " ; string midPal = " " ; prefix = str . substr ( 0 , len ) ; suffix = str . substr ( n - len ) ; str = str . substr ( len , n - 2 * len ) ; for ( int i = 1 ; i <= str . size ( ) ; i ++ ) { string y = str . substr ( 0 , i ) ; if ( isPalindrome ( y ) ) { if ( midPal . size ( ) < y . size ( ) ) { midPal = y ; } } } for ( int i = 1 ; i <= str . size ( ) ; i ++ ) { string y = str . substr ( str . size ( ) - i ) ; if ( isPalindrome ( y ) ) { if ( midPal . size ( ) < y . size ( ) ) { midPal = y ; } } } string answer = prefix + midPal + suffix ; return answer ; } int main ( ) { string str = " abcdfdcecba " ; cout << PrefixSuffixPalindrome ( str ) << " STRNEWLINE " ; return 0 ; } |
Minimize the maximum difference between adjacent elements in an array | C ++ implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Initialising the minimum difference ; Traversing over subsets in iterative manner ; Number of elements to be taken in the subset ON bits of i represent elements not to be removed ; If the removed set is of size k ; Creating the new array after removing elements ; Maximum difference of adjacent elements of remaining array ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumAdjacentDifference ( vector < int > a , int n , int k ) { int minDiff = INT_MAX ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { int cnt = __builtin_popcount ( i ) ; if ( cnt == n - k ) { vector < int > temp ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) temp . push_back ( a [ j ] ) ; } int maxDiff = INT_MIN ; for ( int j = 0 ; j < temp . size ( ) - 1 ; j ++ ) { maxDiff = max ( maxDiff , temp [ j + 1 ] - temp [ j ] ) ; } minDiff = min ( minDiff , maxDiff ) ; } } return minDiff ; } int main ( ) { int n = 5 ; int k = 2 ; vector < int > a = { 3 , 7 , 8 , 10 , 14 } ; cout << minimumAdjacentDifference ( a , n , k ) ; return 0 ; } |
Minimize the maximum difference between adjacent elements in an array | C ++ implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Initialising the minimum difference ; Iterating over all subarrays of size n - k ; Maximum difference after removing elements ; Minimum Adjacent Difference ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumAdjacentDifference ( vector < int > a , int n , int k ) { int minDiff = INT_MAX ; for ( int i = 0 ; i <= k ; i ++ ) { int maxDiff = INT_MIN ; for ( int j = 0 ; j < n - k - 1 ; j ++ ) { for ( int p = i ; p <= i + j ; p ++ ) { maxDiff = max ( maxDiff , a [ p + 1 ] - a [ p ] ) ; } } minDiff = min ( minDiff , maxDiff ) ; } return minDiff ; } int main ( ) { int n = 5 ; int k = 2 ; vector < int > a = { 3 , 7 , 8 , 10 , 14 } ; cout << minimumAdjacentDifference ( a , n , k ) ; return 0 ; } |
Minimize the maximum difference between adjacent elements in an array | C ++ implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum different in the subarrays of size K in the array ; Create a Double Ended Queue , Qi that will store indexes of array elements , queue will store indexes of useful elements in every window ; Process first k ( or first window ) elements of array ; For every element , the previous smaller elements are useless so remove them from Qi ; Add new element at rear of queue ; Process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; The element at the front of the queue is the largest element of previous window ; Remove the elements which are out of this window ; Remove all elements smaller than the currently being added element ( remove useless elements ) ; Add current element at the rear of Qi ; compare the maximum element of last window ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Create the difference array ; find minimum of all maximum of subarray sizes n - k - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findKMin ( vector < int > arr , int n , int k ) { deque < int > Qi ( k ) ; int i ; for ( i = 0 ; i < k ; ++ i ) { while ( ( ! Qi . empty ( ) ) && arr [ i ] >= arr [ Qi . back ( ) ] ) Qi . push_back ( i ) ; } int minDiff = INT_MAX ; for ( ; i < n ; ++ i ) { minDiff = min ( minDiff , arr [ Qi . front ( ) ] ) ; while ( ( ! Qi . empty ( ) ) && Qi . front ( ) <= i - k ) Qi . pop_front ( ) ; while ( ( ! Qi . empty ( ) ) && arr [ i ] >= arr [ Qi . back ( ) ] ) Qi . pop_back ( ) ; Qi . push_back ( i ) ; } minDiff = min ( minDiff , arr [ Qi . front ( ) ] ) ; return minDiff ; } int minimumAdjacentDifference ( vector < int > a , int n , int k ) { vector < int > diff ( n - 1 ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { diff [ i ] = a [ i + 1 ] - a [ i ] ; } int answer = findKMin ( diff , n - 1 , n - k - 1 ) ; return answer ; } int main ( ) { int n = 5 ; int k = 2 ; vector < int > a = { 3 , 7 , 8 , 10 , 14 } ; cout << minimumAdjacentDifference ( a , n , k ) ; return 0 ; } |
Minimum elements inserted in a sorted array to form an Arithmetic progression | C ++ implementation to find the minimum elements required to be inserted into an array to form an arithmetic progression ; Function to find the greatest common divisor of two numbers ; Function to find the minimum the minimum number of elements required to be inserted into array ; Difference array of consecutive elements of the array ; GCD of the difference array ; Loop to calculate the minimum number of elements required ; Driver Code ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; int gcdFunc ( int a , int b ) { if ( b == 0 ) return a ; return gcdFunc ( b , a % b ) ; } int findMinimumElements ( int * a , int n ) { int b [ n - 1 ] ; for ( int i = 1 ; i < n ; i ++ ) { b [ i - 1 ] = a [ i ] - a [ i - 1 ] ; } int gcd = b [ 0 ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { gcd = gcdFunc ( gcd , b [ i ] ) ; } int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans += ( b [ i ] / gcd ) - 1 ; } return ans ; } int main ( ) { int arr1 [ ] = { 1 , 6 , 8 , 10 , 14 , 16 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << findMinimumElements ( arr1 , n1 ) << endl ; } |
Check if a Sequence is a concatenation of two permutations | C ++ program to check if a given sequence is a concatenation of two permutations or not ; Function to Check if a given sequence is a concatenation of two permutations or not ; Computing the sum of all the elements in the array ; Computing the prefix sum for all the elements in the array ; Iterating through the i from lengths 1 to n - 1 ; Sum of first i + 1 elements ; Sum of remaining n - i - 1 elements ; Lengths of the 2 permutations ; Checking if the sums satisfy the formula or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPermutation ( int arr [ ] , int n ) { long long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; long long prefix [ n + 1 ] = { 0 } ; prefix [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix [ i ] = prefix [ i - 1 ] + arr [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { long long lsum = prefix [ i ] ; long long rsum = sum - prefix [ i ] ; long long l_len = i + 1 , r_len = n - i - 1 ; if ( ( ( 2 * lsum ) == ( l_len * ( l_len + 1 ) ) ) && ( ( 2 * rsum ) == ( r_len * ( r_len + 1 ) ) ) ) return true ; } return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 4 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; if ( checkPermutation ( arr , n ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; } |
Find a N | CPP program to find N digit number such that it is not divisible by any of its digits ; Function that print the answer ; if n == 1 then it is not possible ; loop to n - 1 times ; print 4 as last digit of the number ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTheNumber ( int n ) { if ( n == 1 ) { cout << " Impossible " << endl ; return ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { cout << "5" ; } cout << "4" ; } int main ( ) { int n = 12 ; findTheNumber ( n ) ; return 0 ; } |
Queries to check whether bitwise AND of a subarray is even or odd | C ++ implementation of the approach ; Function to precompute the count of even and odd numbers ; If the current element is odd then put 1 at odd [ i ] ; If the current element is even then put 1 at even [ i ] ; Taking the prefix sums of these two arrays so we can get the count of even and odd numbers in a range [ L , R ] in O ( 1 ) ; Function that returns true if the bitwise AND of the subarray a [ L ... R ] is odd ; cnt will store the count of odd numbers in the range [ L , R ] ; Check if all the numbers in the range are odd or not ; Function to perform the queries ; Perform queries ; Driver code ; Queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAXN = 1000005 ; int even [ MAXN ] , odd [ MAXN ] ; void precompute ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % 2 == 1 ) odd [ i ] = 1 ; if ( arr [ i ] % 2 == 0 ) even [ i ] = 1 ; } for ( int i = 1 ; i < n ; i ++ ) { even [ i ] = even [ i ] + even [ i - 1 ] ; odd [ i ] = odd [ i ] + odd [ i - 1 ] ; } } bool isOdd ( int L , int R ) { int cnt = odd [ R ] ; if ( L > 0 ) cnt -= odd [ L - 1 ] ; if ( cnt == R - L + 1 ) return true ; return false ; } void performQueries ( int a [ ] , int n , int q [ ] [ 2 ] , int m ) { precompute ( a , n ) ; for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] [ 0 ] , R = q [ i ] [ 1 ] ; if ( isOdd ( L , R ) ) cout << " Odd STRNEWLINE " ; else cout << " Even STRNEWLINE " ; } } int main ( ) { int a [ ] = { 2 , 1 , 5 , 7 , 6 , 8 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int q [ ] [ 2 ] = { { 0 , 2 } , { 1 , 2 } , { 2 , 3 } , { 3 , 6 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; performQueries ( a , n , q , m ) ; return 0 ; } |
Find distinct integers for a triplet with given product | C ++ implementation of the approach ; Function to find the required triplets ; To store the factors ; Find factors in sqrt ( x ) time ; Choose a factor ; Choose another factor ; These conditions need to be met for a valid triplet ; Print the valid triplet ; Triplet found ; Triplet not found ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriplets ( int x ) { vector < int > fact ; unordered_set < int > factors ; for ( int i = 2 ; i <= sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { fact . push_back ( i ) ; if ( x / i != i ) fact . push_back ( x / i ) ; factors . insert ( i ) ; factors . insert ( x / i ) ; } } bool found = false ; int k = fact . size ( ) ; for ( int i = 0 ; i < k ; i ++ ) { int a = fact [ i ] ; for ( int j = 0 ; j < k ; j ++ ) { int b = fact [ j ] ; if ( ( a != b ) && ( x % ( a * b ) == 0 ) && ( x / ( a * b ) != a ) && ( x / ( a * b ) != b ) && ( x / ( a * b ) != 1 ) ) { cout << a << " β " << b << " β " << ( x / ( a * b ) ) ; found = true ; break ; } } if ( found ) break ; } if ( ! found ) cout << " - 1" ; } int main ( ) { int x = 105 ; findTriplets ( x ) ; return 0 ; } |
Count of pairs satisfying the given condition | C ++ implementation of the approach ; Function to return the number of pairs satisfying the equation ; Converting integer b to string by using to_string function ; Loop to check if all the digits of b are 9 or not ; If '9' doesn 't appear then break the loop ; If all the digits of b contain 9 then multiply a with string length else multiply a with string length - 1 ; Return the number of pairs ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPair ( int a , int b ) { string s = to_string ( b ) ; int i ; for ( i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] != '9' ) break ; } int result ; if ( i == s . length ( ) ) result = a * s . length ( ) ; else result = a * ( s . length ( ) - 1 ) ; return result ; } int main ( ) { int a = 5 , b = 101 ; cout << countPair ( a , b ) ; return 0 ; } |
Partition the digits of an integer such that it satisfies a given condition | C ++ implementation of the approach ; Function to generate sequence from the given string ; Initialize vector to store sequence ; First add all the digits of group A from left to right ; Then add all the digits of group B from left to right ; Return the sequence ; Function that returns true if the sequence is non - decreasing ; Initialize result ; Function to partition the digits of an integer such that it satisfies the given conditions ; Convert the integer to string ; Length of the string ; Array to store the digits ; Storing the digits of X in array ; Initialize the result ; Loop through the digits ; Put into group A if digit less than D ; Put into group B if digit greater than D ; Put into group C if digit equal to D ; Loop through the digits to decide for group C digits ; Set flag equal to true if group B digit present ; If flag is true put in group A or else put in B ; Generate the sequence from partition ; Check if the sequence is non decreasing ; Return - 1 if no such partition is possible ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > makeSeq ( string s , int a [ ] ) { vector < int > seq ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) if ( s [ i ] == ' A ' ) seq . push_back ( a [ i ] ) ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) if ( s [ i ] == ' B ' ) seq . push_back ( a [ i ] ) ; return seq ; } bool checkSeq ( vector < int > v ) { bool check = true ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) if ( v [ i ] < v [ i - 1 ] ) check = false ; return check ; } string digitPartition ( int X ) { string num = to_string ( X ) ; int l = num . size ( ) ; int a [ l ] ; for ( int i = 0 ; i < l ; i ++ ) a [ i ] = ( num [ i ] - '0' ) ; for ( int D = 0 ; D < 10 ; D ++ ) { string res = " " ; for ( int i = 0 ; i < l ; i ++ ) { if ( a [ i ] < D ) res += ' A ' ; else if ( a [ i ] > D ) res += ' B ' ; else res += ' C ' ; } bool flag = false ; for ( int i = 0 ; i < l ; i ++ ) { if ( res [ i ] == ' B ' ) flag = true ; if ( res [ i ] == ' C ' ) res [ i ] = flag ? ' A ' : ' B ' ; } vector < int > seq = makeSeq ( res , a ) ; if ( checkSeq ( seq ) ) return res ; } return " - 1" ; } int main ( ) { int X = 777147777 ; cout << digitPartition ( X ) ; return 0 ; } |
Area of the circle that has a square and a circle inscribed in it | C ++ implementation of the approach ; Function to return the required area ; Calculate the area ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; float getArea ( int a ) { float area = ( M_PI * a * a ) / 4.0 ; return area ; } int main ( ) { int a = 3 ; cout << getArea ( a ) ; return 0 ; } |
Check if all the elements can be made of same parity by inverting adjacent elements | C ++ implementation of the approach ; Function to check if parity can be made same or not ; Iterate and count the parity ; Odd ; Even ; Condition check ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool flipsPossible ( int a [ ] , int n ) { int count_odd = 0 , count_even = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] & 1 ) count_odd ++ ; else count_even ++ ; } if ( count_odd % 2 && count_even % 2 ) return false ; else return true ; } int main ( ) { int a [ ] = { 1 , 0 , 1 , 1 , 0 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( flipsPossible ( a , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Queries On Array with disappearing and reappearing elements | C ++ implementation of the approach ; Function to perform the queries ; Size of the array with 1 - based indexing ; Number of queries ; Iterating through the queries ; If m is more than the size of the array ; Count of turns ; Find the remainder ; If the remainder is 0 and turn is odd then the array is empty ; If the remainder is 0 and turn is even then array is full and is in its initial state ; If the remainder is not 0 and the turn is even ; Current size of the array ; Current size of the array ; Print the result ; Driver code ; The initial array , - 1 is for 1 base indexing ; Queries in the form of the pairs of ( t , M ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; void PerformQueries ( vector < int > & a , vector < pair < long long , int > > & vec ) { vector < int > ans ; int n = ( int ) a . size ( ) - 1 ; int q = ( int ) vec . size ( ) ; for ( int i = 0 ; i < q ; ++ i ) { long long t = vec [ i ] . first ; int m = vec [ i ] . second ; if ( m > n ) { ans . push_back ( -1 ) ; continue ; } int turn = t / n ; int rem = t % n ; if ( rem == 0 and turn % 2 == 1 ) { ans . push_back ( -1 ) ; continue ; } if ( rem == 0 and turn % 2 == 0 ) { ans . push_back ( a [ m ] ) ; continue ; } if ( turn % 2 == 0 ) { int cursize = n - rem ; if ( cursize < m ) { ans . push_back ( -1 ) ; continue ; } ans . push_back ( a [ m + rem ] ) ; } else { int cursize = rem ; if ( cursize < m ) { ans . push_back ( -1 ) ; continue ; } ans . push_back ( a [ m ] ) ; } } for ( int i : ans ) cout << i << " STRNEWLINE " ; } int main ( ) { vector < int > a = { -1 , 1 , 2 , 3 , 4 , 5 } ; vector < pair < long long , int > > vec = { { 1 , 4 } , { 6 , 1 } , { 3 , 5 } } ; PerformQueries ( a , vec ) ; return 0 ; } |
Number of pairs in an array having sum equal to product | C ++ implementation of the approach ; Function to return the count of the required pairs ; Find the count of 0 s and 2 s in the array ; Find the count of required pairs ; Return the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumEqualProduct ( int a [ ] , int n ) { int zero = 0 , two = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { zero ++ ; } if ( a [ i ] == 2 ) { two ++ ; } } int cnt = ( zero * ( zero - 1 ) ) / 2 + ( two * ( two - 1 ) ) / 2 ; return cnt ; } int main ( ) { int a [ ] = { 2 , 2 , 3 , 4 , 2 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << sumEqualProduct ( a , n ) ; return 0 ; } |
Minimize the sum of digits of A and B such that A + B = N | C ++ implementation of the approach ; Function to return the minimum possible sum of digits of A and B such that A + B = n ; Find the sum of digits of n ; If num is a power of 10 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += ( n % 10 ) ; n /= 10 ; } if ( sum == 1 ) return 10 ; return sum ; } int main ( ) { int n = 1884 ; cout << minSum ( n ) ; return 0 ; } |
Multiplication on Array : Range update query in O ( 1 ) | C ++ program for the above approach ; Creates a mul [ ] array for A [ ] and returns it after filling initial values . ; Does range update ; Prints updated Array ; Driver code ; ; Array to be updated ; Create and fill mul and div Array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void initialize ( int mul [ ] , int div [ ] , int size ) { for ( int i = 1 ; i < size ; i ++ ) { mul [ i ] = ( mul [ i ] * mul [ i - 1 ] ) / div [ i ] ; } } void update ( int l , int r , int x , int mul [ ] , int div [ ] ) { mul [ l ] *= x ; div [ r + 1 ] *= x ; } void printArray ( int ar [ ] , int mul [ ] , int div [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { ar [ i ] = ar [ i ] * mul [ i ] ; cout << ar [ i ] << " β " ; } } int main ( ) { int ar [ ] = { 10 , 5 , 20 , 40 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; int mul [ n + 1 ] , div [ n + 1 ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) { mul [ i ] = div [ i ] = 1 ; } update ( 0 , 1 , 10 , mul , div ) ; update ( 1 , 3 , 20 , mul , div ) ; update ( 2 , 2 , 2 , mul , div ) ; initialize ( mul , div , n + 1 ) ; printArray ( ar , mul , div , n ) ; return 0 ; } |
Optimal Strategy for a Game | Special Gold Coin | C ++ implementation of the approach ; Function to return the winner of the game ; To store the count of silver coins ; Update the position of the gold coin ; First player will win the game ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string getWinner ( string str , int len ) { int total = 0 ; if ( str [ 0 ] == ' G ' str [ len - 1 ] == ' G ' ) return " First " ; else { for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == ' S ' ) { total ++ ; } } if ( ( total % 2 ) == 1 ) return " First " ; return " Second " ; } } int main ( ) { string str = " GSSS " ; int len = str . length ( ) ; cout << getWinner ( str , len ) ; return 0 ; } |
Find the coordinates of a triangle whose Area = ( S / 2 ) | C ++ implementation of the approach ; Function to find the triangle with area = ( S / 2 ) ; Fix the two pairs of coordinates ; Find ( X3 , Y3 ) with integer coordinates ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const long MAX = 1000000000 ; void findTriangle ( long S ) { long X1 = 0 , Y1 = 0 ; long X2 = MAX , Y2 = 1 ; long X3 = ( MAX - S % MAX ) % MAX ; long Y3 = ( S + X3 ) / MAX ; cout << " ( " << X1 << " , β " << Y1 << " ) STRNEWLINE " ; cout << " ( " << X2 << " , β " << Y2 << " ) STRNEWLINE " ; cout << " ( " << X3 << " , β " << Y3 << " ) " ; } int main ( ) { long S = 4 ; findTriangle ( S ) ; return 0 ; } |
Rearrange array elements such that Bitwise AND of first N | C ++ implementation of the approach ; Utility function to print the elements of an array ; Function to find the required arrangement ; There has to be atleast 2 elements ; Minimum element from the array ; Swap any occurrence of the minimum element with the last element ; Find the bitwise AND of the first ( n - 1 ) elements ; If the bitwise AND is equal to the last element then print the arrangement ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void findArrangement ( int arr [ ] , int n ) { if ( n < 2 ) { cout << " - 1" ; return ; } int minVal = * min_element ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == minVal ) { swap ( arr [ i ] , arr [ n - 1 ] ) ; break ; } } int andVal = arr [ 0 ] ; for ( int i = 1 ; i < n - 1 ; i ++ ) { andVal &= arr [ i ] ; } if ( andVal == arr [ n - 1 ] ) printArr ( arr , n ) ; else cout << " - 1" ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; findArrangement ( arr , n ) ; return 0 ; } |
Maximum prime moves to convert X to Y | C ++ implementation of the approach ; Function to return the maximum operations required to convert X to Y ; X cannot be converted to Y ; If the difference is 1 ; If the difference is even ; Add 3 to X and the new difference will be even ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOperations ( int X , int Y ) { if ( X > Y ) return -1 ; int diff = Y - X ; if ( diff == 1 ) return -1 ; if ( diff % 2 == 0 ) return ( diff / 2 ) ; return ( 1 + ( ( diff - 3 ) / 2 ) ) ; } int main ( ) { int X = 5 , Y = 16 ; cout << maxOperations ( X , Y ) ; return 0 ; } |
Sum of Digits of the Good Strings | C ++ implementation of the approach ; To store the states of the dp ; Function to fill the dp table ; Sum of digits of the string of length 1 is i as i is only number in that string and count of good strings of length 1 that end with i is also 1 ; Adjacent digits are different ; Increment the count as digit at ( i - 1 ) 'th index is k and count of good strings is equal to this because at the end of the strings of length (i - 1) we are just putting digit j as the last digit ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define DIGITS 10 NEW_LINE #define MAX 10000 NEW_LINE #define MOD 1000000007 NEW_LINE long dp [ MAX ] [ DIGITS ] , cnt [ MAX ] [ DIGITS ] ; void precompute ( ) { for ( int i = 0 ; i < DIGITS ; i ++ ) dp [ 1 ] [ i ] = i , cnt [ 1 ] [ i ] = 1 ; for ( int i = 2 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < DIGITS ; j ++ ) { for ( int k = 0 ; k < DIGITS ; k ++ ) { if ( j != k ) { dp [ i ] [ j ] = dp [ i ] [ j ] + ( dp [ i - 1 ] [ k ] + ( cnt [ i - 1 ] [ k ] * j ) % MOD ) % MOD ; dp [ i ] [ j ] %= MOD ; cnt [ i ] [ j ] += cnt [ i - 1 ] [ k ] ; cnt [ i ] [ j ] %= MOD ; } } } } } int main ( ) { long long int x = 6 , y = 4 ; precompute ( ) ; cout << dp [ x ] [ y ] ; return 0 ; } |
Count non | C ++ implementation of the approach ; Function to pre - compute the sequence ; For N = 1 the answer will be 2 ; Starting two terms of the sequence ; Compute the rest of the sequence with the relation F [ i ] = F [ i - 1 ] + F [ i - 2 ] ; Driver code ; Pre - compute the sequence | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE const ll N = 10000 ; const ll MOD = 1000000007 ; ll F [ N ] ; void precompute ( ) { F [ 1 ] = 2 ; F [ 2 ] = 3 ; F [ 3 ] = 4 ; for ( int i = 4 ; i < N ; i ++ ) F [ i ] = ( F [ i - 1 ] + F [ i - 2 ] ) % MOD ; } int main ( ) { int n = 8 ; precompute ( ) ; cout << F [ n ] ; return 0 ; } |
Minimize sum by dividing all elements of a subarray by K | C ++ implementation of the approach ; Function to return the maximum subarray sum ; Function to return the minimized sum of the array elements after performing the given operation ; Find maximum subarray sum ; Find total sum of the array ; Maximum subarray sum is already negative ; Choose the subarray whose sum is maximum and divide all elements by K ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubArraySum ( int a [ ] , int size ) { int max_so_far = INT_MIN , max_ending_here = 0 ; for ( int i = 0 ; i < size ; i ++ ) { max_ending_here = max_ending_here + a [ i ] ; if ( max_so_far < max_ending_here ) max_so_far = max_ending_here ; if ( max_ending_here < 0 ) max_ending_here = 0 ; } return max_so_far ; } double minimizedSum ( int a [ ] , int n , int K ) { int sum = maxSubArraySum ( a , n ) ; double totalSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) totalSum += a [ i ] ; if ( sum < 0 ) return totalSum ; totalSum = totalSum - sum + ( double ) sum / ( double ) K ; return totalSum ; } int main ( ) { int a [ ] = { 1 , -2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int K = 2 ; cout << minimizedSum ( a , n , K ) ; return 0 ; } |
Minimum numbers with one 's place as 9 to be added to get N | C ++ implementation of the approach ; Function to find minimum count of numbers ( with one 's digit 9) that sum up to N ; Fetch one 's digit ; Apply Cases mentioned in approach ; If no possible answer exists ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int N ) { int digit = N % 10 ; switch ( digit ) { case 0 : if ( N >= 90 ) return 10 ; break ; case 1 : if ( N >= 81 ) return 9 ; break ; case 2 : if ( N >= 72 ) return 8 ; break ; case 3 : if ( N >= 63 ) return 7 ; break ; case 4 : if ( N >= 54 ) return 6 ; break ; case 5 : if ( N >= 45 ) return 5 ; break ; case 6 : if ( N >= 36 ) return 4 ; break ; case 7 : if ( N >= 27 ) return 3 ; break ; case 8 : if ( N >= 18 ) return 2 ; break ; case 9 : if ( N >= 9 ) return 1 ; break ; } return -1 ; } int main ( ) { int N = 27 ; cout << findMin ( N ) ; } |
Random list of M non | C ++ implementation of the approach ; Utility function to print the elements of an array ; Function to generate a list of m random non - negative integers whose sum is n ; Create an array of size m where every element is initialized to 0 ; To make the sum of the final list as n ; Increment any random element from the array by 1 ; Print the generated list ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " β " ; } void randomList ( int m , int n ) { int arr [ m ] = { 0 } ; srand ( time ( 0 ) ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ rand ( ) % m ] ++ ; } printArr ( arr , m ) ; } int main ( ) { int m = 4 , n = 8 ; randomList ( m , n ) ; return 0 ; } |
Maximum String Partition | C ++ implementation of the above approach ; Return the count of string ; P will store the answer ; Current will store current string Previous will store the previous string that has been taken already ; Add a character to current string ; Here we will create a partition and update the previous string with current string ; Now we will clear the current string ; Increment the count of partition . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPartition ( string s ) { int n = s . length ( ) , P = 0 ; string current = " " , previous = " " ; for ( int i = 0 ; i < n ; i ++ ) { current += s [ i ] ; if ( current != previous ) { previous = current ; current . clear ( ) ; P ++ ; } } return P ; } int main ( ) { string s = " geeksforgeeks " ; int ans = maxPartition ( s ) ; cout << ans << " STRNEWLINE " ; return 0 ; } |
How to learn Pattern printing easily ? | | #include <iostream> NEW_LINE using namespace std ; int main ( ) { int N = 4 , i , j , min ; cout << " Value β of β N : β " << N << endl ; for ( i = 1 ; i <= N ; i ++ ) { for ( j = 1 ; j <= N ; j ++ ) { min = i < j ? i : j ; cout << N - min + 1 ; } for ( j = N - 1 ; j >= 1 ; j -- ) { min = i < j ? i : j ; cout << N - min + 1 ; } cout << endl ; } return 0 ; } |
Find the smallest positive number missing from an unsorted array | Set 3 | CPP program to find the smallest positive missing number ; Function to find the smallest positive missing number ; Default smallest Positive Integer ; Store values in set which are greater than variable m ; Store value when m is less than current index of given array ; Increment m when it is equal to current element ; Increment m when it is one of the element of the set ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMissingPositive ( int arr [ ] , int n ) { int m = 1 ; set < int > x ; for ( int i = 0 ; i < n ; i ++ ) { if ( m < arr [ i ] ) { x . insert ( arr [ i ] ) ; } else if ( m == arr [ i ] ) { m = m + 1 ; while ( x . count ( m ) ) { x . erase ( m ) ; m = m + 1 ; } } } return m ; } int main ( ) { int arr [ ] = { 2 , 3 , -7 , 6 , 8 , 1 , -10 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMissingPositive ( arr , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.