text
stringlengths
25
2.53k
code
stringlengths
46
4.32k
Program for Identity Matrix | C program to print Identity Matrix ; Checking if row is equal to column ; Driver Code
#include <stdio.h> NEW_LINE int Identity ( int num ) { int row , col ; for ( row = 0 ; row < num ; row ++ ) { for ( col = 0 ; col < num ; col ++ ) { if ( row == col ) printf ( " % d ▁ " , 1 ) ; else printf ( " % d ▁ " , 0 ) ; } printf ( " STRNEWLINE " ) ; } return 0 ; } int main ( ) { int size = 5 ; identity ( size ) ; return 0 ; }
Search in a row wise and column wise sorted matrix | C program to search an element in row - wise and column - wise sorted matrix ; Searches the element x in mat [ ] [ ] . If the element is found , then prints its position and returns true , otherwise prints " not ▁ found " and returns false ; set indexes for top right element ; if mat [ i ] [ j ] < x ; if ( i == n j == - 1 ) ; driver program to test above function
#include <stdio.h> NEW_LINE int search ( int mat [ 4 ] [ 4 ] , int n , int x ) { if ( n == 0 ) return -1 ; int smallest = mat [ 0 ] [ 0 ] , largest = mat [ n - 1 ] [ n - 1 ] ; if ( x < smallest x > largest ) return -1 ; int i = 0 , j = n - 1 ; while ( i < n && j >= 0 ) { if ( mat [ i ] [ j ] == x ) { printf ( " Found at % d , % d " , i , j ) ; return 1 ; } if ( mat [ i ] [ j ] > x ) j -- ; else i ++ ; } printf ( " n ▁ Element ▁ not ▁ found " ) ; return 0 ; } int main ( ) { int mat [ 4 ] [ 4 ] = { { 10 , 20 , 30 , 40 } , { 15 , 25 , 35 , 45 } , { 27 , 29 , 37 , 48 } , { 32 , 33 , 39 , 50 } , } ; search ( mat , 4 , 29 ) ; return 0 ; }
Create a matrix with alternating rectangles of O and X | ; Function to print alternating rectangles of 0 and X ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Store given number of rows and columns for later use ; A 2D array to store the output to be printed ; Iniitialize the character to be stoed in a [ ] [ ] ; Fill characters in a [ ] [ ] in spiral form . Every iteration fills one rectangle of either Xs or Os ; Fill the first row from the remaining rows ; Fill the last column from the remaining columns ; Fill the last row from the remaining rows ; Print the first column from the remaining columns ; Flip character for next iteration ; Print the filled matrix ; Driver program to test above functions
#include <stdio.h> NEW_LINE void fill0X ( int m , int n ) { int i , k = 0 , l = 0 ; int r = m , c = n ; char a [ m ] [ n ] ; char x = ' X ' ; while ( k < m && l < n ) { for ( i = l ; i < n ; ++ i ) a [ k ] [ i ] = x ; k ++ ; for ( i = k ; i < m ; ++ i ) a [ i ] [ n - 1 ] = x ; n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) a [ m - 1 ] [ i ] = x ; m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) a [ i ] [ l ] = x ; l ++ ; } x = ( x == '0' ) ? ' X ' : '0' ; } for ( i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) printf ( " % c ▁ " , a [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } int main ( ) { puts ( " Output ▁ for ▁ m ▁ = ▁ 5 , ▁ n ▁ = ▁ 6" ) ; fill0X ( 5 , 6 ) ; puts ( " Output for m = 4 , n = 4 " ) ; fill0X ( 4 , 4 ) ; puts ( " Output for m = 3 , n = 4 " ) ; fill0X ( 3 , 4 ) ; return 0 ; }
Program to Interchange Diagonals of Matrix | C program to interchange the diagonals of matrix ; Function to interchange diagonals ; swap elements of diagonal ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE void interchangeDiagonals ( int array [ ] [ N ] ) { for ( int i = 0 ; i < N ; ++ i ) if ( i != N / 2 ) swap ( array [ i ] [ i ] , array [ i ] [ N - i - 1 ] ) ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) printf ( " ▁ % d " , array [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } int main ( ) { int array [ N ] [ N ] = { 4 , 5 , 6 , 1 , 2 , 3 , 7 , 8 , 9 } ; interchangeDiagonals ( array ) ; return 0 ; }
Linked complete binary tree & its creation | Program for linked implementation of complete binary tree ; For Queue Size ; A tree node ; A queue node ; A utility function to create a new tree node ; A utility function to create a new Queue ; Standard Queue Functions ; A utility function to check if a tree node has both left and right children ; Function to insert a new node in complete binary tree ; Create a new node for given data ; If the tree is empty , initialize the root with new node . ; get the front node of the queue . ; If the left child of this front node doesn t exist , set the left child as the new node ; If the right child of this front node doesn t exist , set the right child as the new node ; If the front node has both the left child and right child , Dequeue ( ) it . ; Enqueue ( ) the new node for later insertions ; Standard level order traversal to test above function ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define SIZE 50 NEW_LINE struct node { int data ; struct node * right , * left ; } ; struct Queue { int front , rear ; int size ; struct node * * array ; } ; struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } struct Queue * createQueue ( int size ) { struct Queue * queue = ( struct Queue * ) malloc ( sizeof ( struct Queue ) ) ; queue -> front = queue -> rear = -1 ; queue -> size = size ; queue -> array = ( struct node * * ) malloc ( queue -> size * sizeof ( struct node * ) ) ; int i ; for ( i = 0 ; i < size ; ++ i ) queue -> array [ i ] = NULL ; return queue ; } int isEmpty ( struct Queue * queue ) { return queue -> front == -1 ; } int isFull ( struct Queue * queue ) { return queue -> rear == queue -> size - 1 ; } int hasOnlyOneItem ( struct Queue * queue ) { return queue -> front == queue -> rear ; } void Enqueue ( struct node * root , struct Queue * queue ) { if ( isFull ( queue ) ) return ; queue -> array [ ++ queue -> rear ] = root ; if ( isEmpty ( queue ) ) ++ queue -> front ; } struct node * Dequeue ( struct Queue * queue ) { if ( isEmpty ( queue ) ) return NULL ; struct node * temp = queue -> array [ queue -> front ] ; if ( hasOnlyOneItem ( queue ) ) queue -> front = queue -> rear = -1 ; else ++ queue -> front ; return temp ; } struct node * getFront ( struct Queue * queue ) { return queue -> array [ queue -> front ] ; } int hasBothChild ( struct node * temp ) { return temp && temp -> left && temp -> right ; } void insert ( struct node * * root , int data , struct Queue * queue ) { struct node * temp = newNode ( data ) ; if ( ! * root ) * root = temp ; else { struct node * front = getFront ( queue ) ; if ( ! front -> left ) front -> left = temp ; else if ( ! front -> right ) front -> right = temp ; if ( hasBothChild ( front ) ) Dequeue ( queue ) ; } Enqueue ( temp , queue ) ; } void levelOrder ( struct node * root ) { struct Queue * queue = createQueue ( SIZE ) ; Enqueue ( root , queue ) ; while ( ! isEmpty ( queue ) ) { struct node * temp = Dequeue ( queue ) ; printf ( " % d ▁ " , temp -> data ) ; if ( temp -> left ) Enqueue ( temp -> left , queue ) ; if ( temp -> right ) Enqueue ( temp -> right , queue ) ; } } int main ( ) { struct node * root = NULL ; struct Queue * queue = createQueue ( SIZE ) ; int i ; for ( i = 1 ; i <= 12 ; ++ i ) insert ( & root , i , queue ) ; levelOrder ( root ) ; return 0 ; }
Convert a given Binary Tree to Doubly Linked List | Set 1 | A C program for in - place conversion of Binary Tree to DLL ; A binary tree node has data , and left and right pointers ; This is the core function to convert Tree to list . This function follows steps 1 and 2 of the above algorithm ; Base case ; Convert the left subtree and link to root ; Convert the left subtree ; Find inorder predecessor . After this loop , left will point to the inorder predecessor ; Make root as next of the predecessor ; Make predecssor as previous of root ; Convert the right subtree and link to root ; Convert the right subtree ; Find inorder successor . After this loop , right will point to the inorder successor ; Make root as previous of successor ; Make successor as next of root ; The main function that first calls bintree2listUtil ( ) , then follows step 3 of the above algorithm ; Base case ; Convert to DLL using bintree2listUtil ( ) ; bintree2listUtil ( ) returns root node of the converted DLL . We need pointer to the leftmost node which is head of the constructed DLL , so move to the leftmost node ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function to print nodes in a given doubly linked list ; Driver program to test above functions ; Let us create the tree shown in above diagram ; Convert to DLL ; Print the converted list
#include <stdio.h> NEW_LINE struct node { int data ; node * left ; node * right ; } ; node * bintree2listUtil ( node * root ) { if ( root == NULL ) return root ; if ( root -> left != NULL ) { node * left = bintree2listUtil ( root -> left ) ; for ( ; left -> right != NULL ; left = left -> right ) ; left -> right = root ; root -> left = left ; } if ( root -> right != NULL ) { node * right = bintree2listUtil ( root -> right ) ; for ( ; right -> left != NULL ; right = right -> left ) ; right -> left = root ; root -> right = right ; } return root ; } node * bintree2list ( node * root ) { if ( root == NULL ) return root ; root = bintree2listUtil ( root ) ; while ( root -> left != NULL ) root = root -> left ; return ( root ) ; } node * newNode ( int data ) { node * new_node = new node ; new_node -> data = data ; new_node -> left = new_node -> right = NULL ; return ( new_node ) ; } void printList ( node * node ) { while ( node != NULL ) { printf ( " % d ▁ " , node -> data ) ; node = node -> right ; } } int main ( ) { node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; node * head = bintree2list ( root ) ; printList ( head ) ; return 0 ; }
Print unique rows in a given boolean matrix | Given a binary matrix of M X N of integers , you need to return only unique rows of binary array ; A Trie node ; Only two children needed for 0 and 1 ; A utility function to allocate memory for a new Trie node ; Inserts a new matrix row to Trie . If row is already present , then returns 0 , otherwise insets the row and return 1 ; base case ; Recur if there are more entries in this row ; If all entries of this row are processed ; unique row found , return 1 ; duplicate row found , return 0 ; A utility function to print a row ; The main function that prints all unique rows in a given matrix . ; create an empty Trie ; Iterate through all rows ; insert row to TRIE ; unique row found , print it ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <stdbool.h> NEW_LINE #define ROW 4 NEW_LINE #define COL 5 NEW_LINE typedef struct Node { bool isEndOfCol ; struct Node * child [ 2 ] ; } Node ; Node * newNode ( ) { Node * temp = ( Node * ) malloc ( sizeof ( Node ) ) ; temp -> isEndOfCol = 0 ; temp -> child [ 0 ] = temp -> child [ 1 ] = NULL ; return temp ; } bool insert ( Node * * root , int ( * M ) [ COL ] , int row , int col ) { if ( * root == NULL ) * root = newNode ( ) ; if ( col < COL ) return insert ( & ( ( * root ) -> child [ M [ row ] [ col ] ] ) , M , row , col + 1 ) ; else { if ( ! ( ( * root ) -> isEndOfCol ) ) return ( * root ) -> isEndOfCol = 1 ; return 0 ; } } void printRow ( int ( * M ) [ COL ] , int row ) { int i ; for ( i = 0 ; i < COL ; ++ i ) printf ( " % d ▁ " , M [ row ] [ i ] ) ; printf ( " STRNEWLINE " ) ; } void findUniqueRows ( int ( * M ) [ COL ] ) { Node * root = NULL ; int i ; for ( i = 0 ; i < ROW ; ++ i ) if ( insert ( & root , M , i , 0 ) ) printRow ( M , i ) ; } int main ( ) { int M [ ROW ] [ COL ] = { { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 0 , 0 , 1 } , { 1 , 0 , 1 , 0 , 0 } } ; findUniqueRows ( M ) ; return 0 ; }
Find a common element in all rows of a given row | A C program to find a common element in all rows of a row wise sorted array ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; An array to store indexes of current last column ; To store index of row whose current last element is minimum ; Initialize current last element of all rows ; Initialize min_row as first row ; Keep finding min_row in current last column , till either all elements of last column become same or we hit first column . ; Find minimum in current last column ; eq_count is count of elements equal to minimum in current last column . ; Traverse current last column elements again to update it ; Decrease last column index of a row whose value is more than minimum . ; Reduce last column index by 1 ; If equal count becomes M , return the value ; driver program to test above function
#include <stdio.h> NEW_LINE #define M 4 NEW_LINE #define N 5 NEW_LINE int findCommon ( int mat [ M ] [ N ] ) { int column [ M ] ; int min_row ; int i ; for ( i = 0 ; i < M ; i ++ ) column [ i ] = N - 1 ; min_row = 0 ; while ( column [ min_row ] >= 0 ) { for ( i = 0 ; i < M ; i ++ ) { if ( mat [ i ] [ column [ i ] ] < mat [ min_row ] [ column [ min_row ] ] ) min_row = i ; } int eq_count = 0 ; for ( i = 0 ; i < M ; i ++ ) { if ( mat [ i ] [ column [ i ] ] > mat [ min_row ] [ column [ min_row ] ] ) { if ( column [ i ] == 0 ) return -1 ; column [ i ] -= 1 ; } else eq_count ++ ; } if ( eq_count == M ) return mat [ min_row ] [ column [ min_row ] ] ; } return -1 ; } int main ( ) { int mat [ M ] [ N ] = { { 1 , 2 , 3 , 4 , 5 } , { 2 , 4 , 5 , 8 , 10 } , { 3 , 5 , 7 , 9 , 11 } , { 1 , 3 , 5 , 7 , 9 } , } ; int result = findCommon ( mat ) ; if ( result == -1 ) printf ( " No ▁ common ▁ element " ) ; else printf ( " Common ▁ element ▁ is ▁ % d " , result ) ; return 0 ; }
Convert a given Binary Tree to Doubly Linked List | Set 2 | A simple inorder traversal based program to convert a Binary Tree to DLL ; A tree node ; A utility function to create a new tree node ; Standard Inorder traversal of tree ; Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node ; Changes right pointers to work as next pointers in converted DLL ; Find the right most node in BT or last node in DLL ; Start from the rightmost node , traverse back using left pointers . While traversing , change right pointer of nodes . ; The leftmost node is head of linked list , return it ; The main function that converts BST to DLL and returns head of DLL ; Set the previous pointer ; Set the next pointer and return head of DLL ; Traverses the DLL from left tor right ; Driver program to test above functions ; Let us create the tree shown in above diagram
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void inorder ( struct node * root ) { if ( root != NULL ) { inorder ( root -> left ) ; printf ( " TABSYMBOL % d " , root -> data ) ; inorder ( root -> right ) ; } } void fixPrevPtr ( struct node * root ) { static struct node * pre = NULL ; if ( root != NULL ) { fixPrevPtr ( root -> left ) ; root -> left = pre ; pre = root ; fixPrevPtr ( root -> right ) ; } } struct node * fixNextPtr ( struct node * root ) { struct node * prev = NULL ; while ( root && root -> right != NULL ) root = root -> right ; while ( root && root -> left != NULL ) { prev = root ; root = root -> left ; root -> right = prev ; } return ( root ) ; } struct node * BTToDLL ( struct node * root ) { fixPrevPtr ( root ) ; return fixNextPtr ( root ) ; } void printList ( struct node * root ) { while ( root != NULL ) { printf ( " TABSYMBOL % d " , root -> data ) ; root = root -> right ; } } int main ( void ) { struct node * root = newNode ( 10 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 15 ) ; root -> left -> left = newNode ( 25 ) ; root -> left -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 36 ) ; printf ( " Inorder Tree Traversal " inorder ( root ) ; struct node * head = BTToDLL ( root ) ; printf ( " DLL Traversal " printList ( head ) ; return 0 ; }
Convert an arbitrary Binary Tree to a tree that holds Children Sum Property | Program to convert an aribitary binary tree to a tree that holds children sum property ; A binary tree node ; This function is used to increment left subtree ; This function changes a tree to hold children sum property ; If tree is empty or it 's a leaf node then return true ; convert left and right subtrees ; If left child is not present then 0 is used as data of left child ; If right child is not present then 0 is used as data of right child ; get the diff of node 's data and children sum ; If node ' s ▁ children ▁ sum ▁ is ▁ greater ▁ than ▁ the ▁ node ' s data ; THIS IS TRICKY -- > If node 's data is greater than children sum, then increment subtree by diff ; - diff is used to make diff positive ; This function is used to increment subtree by diff ; IF left child is not NULL then increment it ; Recursively call to fix the descendants of node -> left ; Else increment right child ; Recursively call to fix the descendants of node -> right ; Given a binary tree , printInorder ( ) prints out its inorder traversal ; first recur on left child ; then print the data of node ; now recur on right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; void increment ( struct node * node , int diff ) ; void convertTree ( struct node * node ) { int left_data = 0 , right_data = 0 , diff ; if ( node == NULL || ( node -> left == NULL && node -> right == NULL ) ) return ; else { convertTree ( node -> left ) ; convertTree ( node -> right ) ; if ( node -> left != NULL ) left_data = node -> left -> data ; if ( node -> right != NULL ) right_data = node -> right -> data ; diff = left_data + right_data - node -> data ; if ( diff > 0 ) node -> data = node -> data + diff ; if ( diff < 0 ) increment ( node , - diff ) ; } } void increment ( struct node * node , int diff ) { if ( node -> left != NULL ) { node -> left -> data = node -> left -> data + diff ; increment ( node -> left , diff ) ; } else if ( node -> right != NULL ) { node -> right -> data = node -> right -> data + diff ; increment ( node -> right , diff ) ; } } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 50 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 1 ) ; root -> right -> right = newNode ( 30 ) ; printf ( " Inorder traversal before conversion " printInorder ( root ) ; convertTree ( root ) ; printf ( " Inorder traversal after conversion " printInorder ( root ) ; getchar ( ) ; return 0 ; }
Convert a given tree to its Sum Tree | ; A tree node structure ; Convert a given tree to a tree where every node contains sum of values of nodes in left and right subtrees in the original tree ; Base case ; Store the old value ; Recursively call for left and right subtrees and store the sum as new value of this node ; Return the sum of values of nodes in left and right subtrees and old_value of this node ; A utility function to print inorder traversal of a Binary Tree ; Utility function to create a new Binary Tree node ; Driver function to test above functions ; Constructing tree given in the above figure ; Print inorder traversal of the converted tree to test result of toSumTree ( )
#include <stdio.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; int toSumTree ( struct node * node ) { if ( node == NULL ) return 0 ; int old_val = node -> data ; node -> data = toSumTree ( node -> left ) + toSumTree ( node -> right ) ; return node -> data + old_val ; } void printInorder ( struct node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; printf ( " % d ▁ " , node -> data ) ; printInorder ( node -> right ) ; } struct node * newNode ( int data ) { struct node * temp = new struct node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = NULL ; int x ; root = newNode ( 10 ) ; root -> left = newNode ( -2 ) ; root -> right = newNode ( 6 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( -4 ) ; root -> right -> left = newNode ( 7 ) ; root -> right -> right = newNode ( 5 ) ; toSumTree ( root ) ; printf ( " Inorder ▁ Traversal ▁ of ▁ the ▁ resultant ▁ tree ▁ is : ▁ STRNEWLINE " ) ; printInorder ( root ) ; getchar ( ) ; return 0 ; }
Find a peak element | C program to find a peak element using divide and conquer ; A binary search based function that returns index of a peak element ; Find index of middle element ( low + high ) / 2 ; Compare middle element with its neighbours ( if neighbours exist ) ; If middle element is not peak and its left neighbour is greater than it , then left half must have a peak element ; If middle element is not peak and its right neighbour is greater than it , then right half must have a peak element ; A wrapper over recursive function findPeakUtil ( ) ; Driver program to check above functions
#include <stdio.h> NEW_LINE int findPeakUtil ( int arr [ ] , int low , int high , int n ) { int mid = low + ( high - low ) / 2 ; if ( ( mid == 0 arr [ mid - 1 ] <= arr [ mid ] ) && ( mid == n - 1 arr [ mid + 1 ] <= arr [ mid ] ) ) return mid ; else if ( mid > 0 && arr [ mid - 1 ] > arr [ mid ] ) return findPeakUtil ( arr , low , ( mid - 1 ) , n ) ; else return findPeakUtil ( arr , ( mid + 1 ) , high , n ) ; } int findPeak ( int arr [ ] , int n ) { return findPeakUtil ( arr , 0 , n - 1 , n ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 20 , 4 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Index ▁ of ▁ a ▁ peak ▁ point ▁ is ▁ % d " , findPeak ( arr , n ) ) ; return 0 ; }
Find the two repeating elements in a given array | ; Print Repeating function ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void printRepeating ( int arr [ ] , int size ) { int i , j ; printf ( " ▁ Repeating ▁ elements ▁ are ▁ " ) ; for ( i = 0 ; i < size ; i ++ ) for ( j = i + 1 ; j < size ; j ++ ) if ( arr [ i ] == arr [ j ] ) printf ( " ▁ % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Find the two repeating elements in a given array | ; Function ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void printRepeating ( int arr [ ] , int size ) { int * count = ( int * ) calloc ( sizeof ( int ) , ( size - 2 ) ) ; int i ; printf ( " ▁ Repeating ▁ elements ▁ are ▁ " ) ; for ( i = 0 ; i < size ; i ++ ) { if ( count [ arr [ i ] ] == 1 ) printf ( " ▁ % d ▁ " , arr [ i ] ) ; else count [ arr [ i ] ] ++ ; } } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Find the two repeating elements in a given array | ; printRepeating function ; S is for sum of elements in arr [ ] ; P is for product of elements in arr [ ] ; x and y are two repeating elements ; D is for difference of x and y , i . e . , x - y ; Calculate Sum and Product of all elements in arr [ ] ; S is x + y now ; P is x * y now ; D is x - y now ; factorial of n ; driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <math.h> NEW_LINE int fact ( int n ) ; void printRepeating ( int arr [ ] , int size ) { int S = 0 ; int P = 1 ; int x , y ; int D ; int n = size - 2 , i ; for ( i = 0 ; i < size ; i ++ ) { S = S + arr [ i ] ; P = P * arr [ i ] ; } S = S - n * ( n + 1 ) / 2 ; P = P / fact ( n ) ; D = sqrt ( S * S - 4 * P ) ; x = ( D + S ) / 2 ; y = ( S - D ) / 2 ; printf ( " The ▁ two ▁ Repeating ▁ elements ▁ are ▁ % d ▁ & ▁ % d " , x , y ) ; } int fact ( int n ) { return ( n == 0 ) ? 1 : n * fact ( n - 1 ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Find the two repeating elements in a given array | C code to Find the two repeating elements in a given array ; Will hold xor of all elements ; Will have only single set bit of xor ; Get the xor of all elements in arr [ ] and { 1 , 2 . . n } ; Get the rightmost set bit in set_bit_no ; Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element . ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; XOR of first set in arr [ ] and { 1 , 2 , ... n } ; XOR of second set in arr [ ] and { 1 , 2 , ... n } ; driver code
void printRepeating ( int arr [ ] , int size ) { int xor = arr [ 0 ] ; int set_bit_no ; int i ; int n = size - 2 ; int x = 0 , y = 0 ; for ( i = 1 ; i < size ; i ++ ) xor ^= arr [ i ] ; for ( i = 1 ; i <= n ; i ++ ) xor ^= i ; set_bit_no = xor & ~ ( xor - 1 ) ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } for ( i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) x = x ^ i ; else y = y ^ i ; } printf ( " n ▁ The ▁ two ▁ repeating ▁ elements ▁ are ▁ % d ▁ & ▁ % d ▁ " , x , y ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Find the two repeating elements in a given array | ; Function to print repeating ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void printRepeating ( int arr [ ] , int size ) { int i ; printf ( " The repeating elements are " for ( i = 0 ; i < size ; i ++ ) { if ( arr [ abs ( arr [ i ] ) ] > 0 ) arr [ abs ( arr [ i ] ) ] = - arr [ abs ( arr [ i ] ) ] ; else printf ( " ▁ % d ▁ " , abs ( arr [ i ] ) ) ; } } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeating ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | A simple program to print subarray with sum as given sum ; Returns true if the there is a subarray of arr [ ] with a sum equal to ' sum ' otherwise returns false . Also , prints the result ; Pick a starting point ; try all subarrays starting with ' i ' ; Driver program to test above function
#include <stdio.h> NEW_LINE int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum , i , j ; for ( i = 0 ; i < n ; i ++ ) { curr_sum = arr [ i ] ; for ( j = i + 1 ; j <= n ; j ++ ) { if ( curr_sum == sum ) { printf ( " Sum ▁ found ▁ between ▁ indexes ▁ % d ▁ and ▁ % d " , i , j - 1 ) ; return 1 ; } if ( curr_sum > sum j == n ) break ; curr_sum = curr_sum + arr [ j ] ; } } printf ( " No ▁ subarray ▁ found " ) ; return 0 ; } int main ( ) { int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 23 ; subArraySum ( arr , n , sum ) ; return 0 ; }
Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | An efficient program to print subarray with sum as given sum ; Returns true if the there is a subarray of arr [ ] with a sum equal to ' sum ' otherwise returns false . Also , prints the result ; Initialize curr_sum as value of first element and starting point as 0 ; Add elements one by one to curr_sum and if the curr_sum exceeds the sum , then remove starting element ; If curr_sum exceeds the sum , then remove the starting elements ; If curr_sum becomes equal to sum , then return true ; Add this element to curr_sum ; If we reach here , then no subarray ; Driver program to test above function
#include <stdio.h> NEW_LINE int subArraySum ( int arr [ ] , int n , int sum ) { int curr_sum = arr [ 0 ] , start = 0 , i ; for ( i = 1 ; i <= n ; i ++ ) { while ( curr_sum > sum && start < i - 1 ) { curr_sum = curr_sum - arr [ start ] ; start ++ ; } if ( curr_sum == sum ) { printf ( " Sum ▁ found ▁ between ▁ indexes ▁ % d ▁ and ▁ % d " , start , i - 1 ) ; return 1 ; } if ( i < n ) curr_sum = curr_sum + arr [ i ] ; } printf ( " No ▁ subarray ▁ found " ) ; return 0 ; } int main ( ) { int arr [ ] = { 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 23 ; subArraySum ( arr , n , sum ) ; return 0 ; }
Find a triplet that sum to a given value | ; returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; If we reach here , then no triplet was found ; Driver program to test above function
#include <stdio.h> NEW_LINE bool find3Numbers ( int A [ ] , int arr_size , int sum ) { int l , r ; for ( int i = 0 ; i < arr_size - 2 ; i ++ ) { for ( int j = i + 1 ; j < arr_size - 1 ; j ++ ) { for ( int k = j + 1 ; k < arr_size ; k ++ ) { if ( A [ i ] + A [ j ] + A [ k ] == sum ) { printf ( " Triplet ▁ is ▁ % d , ▁ % d , ▁ % d " , A [ i ] , A [ j ] , A [ k ] ) ; return true ; } } } } return false ; } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int sum = 22 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; find3Numbers ( A , arr_size , sum ) ; return 0 ; }
Analysis of Algorithms | Set 2 ( Worst , Average and Best Cases ) | C implementation of the approach ; Linearly search x in arr [ ] . If x is present then return the index , otherwise return - 1 ; Driver program to test above functions
#include <stdio.h> NEW_LINE int search ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) return i ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 10 , 30 , 15 } ; int x = 30 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d ▁ is ▁ present ▁ at ▁ index ▁ % d " , x , search ( arr , n , x ) ) ; getchar ( ) ; return 0 ; }
Binary Search | C program to implement recursive Binary Search ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver method to test above
#include <stdio.h> NEW_LINE int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % d " , result ) ; return 0 ; }
Binary Search | C program to implement iterative Binary Search ; A iterative binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver method to test above
#include <stdio.h> NEW_LINE int binarySearch ( int arr [ ] , int l , int r , int x ) { while ( l <= r ) { int m = l + ( r - l ) / 2 ; if ( arr [ m ] == x ) return m ; if ( arr [ m ] < x ) l = m + 1 ; else r = m - 1 ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present " " ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ " " index ▁ % d " , result ) ; return 0 ; }
Interpolation Search | C program to implement interpolation search with recursion ; If x is present in arr [ 0. . n - 1 ] , then returns index of it , else returns - 1. ; Since array is sorted , an element present in array must be in range defined by corner ; Probing the position with keeping uniform distribution in mind . ; Condition of target found ; If x is larger , x is in right sub array ; If x is smaller , x is in left sub array ; Driver Code ; Array of items on which search will be conducted . ; Element to be searched ; If element was found
#include <stdio.h> NEW_LINE int interpolationSearch ( int arr [ ] , int lo , int hi , int x ) { int pos ; if ( lo <= hi && x >= arr [ lo ] && x <= arr [ hi ] ) { pos = lo + ( ( ( double ) ( hi - lo ) / ( arr [ hi ] - arr [ lo ] ) ) * ( x - arr [ lo ] ) ) ; if ( arr [ pos ] == x ) return pos ; if ( arr [ pos ] < x ) return interpolationSearch ( arr , pos + 1 , hi , x ) ; if ( arr [ pos ] > x ) return interpolationSearch ( arr , lo , pos - 1 , x ) ; } return -1 ; } int main ( ) { int arr [ ] = { 10 , 12 , 13 , 16 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 33 , 35 , 42 , 47 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 18 ; int index = interpolationSearch ( arr , 0 , n - 1 , x ) ; if ( index != -1 ) printf ( " Element ▁ found ▁ at ▁ index ▁ % d " , index ) ; else printf ( " Element ▁ not ▁ found . " ) ; return 0 ; }
Merge Sort | C program for Merge Sort ; Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] ; Find sizes of two subarrays to be merged ; create temp arrays ; Copy data to temp arrays L [ ] and R [ ] ; Merge the temp arrays Initial indexes of first and second subarrays ; Initial index of merged subarray ; Copy the remaining elements of L [ ] , if there are any ; Copy the remaining elements of R [ ] , if there are any ; l is for left index and r is right index of the sub - array of arr to be sorted ; Same as ( l + r ) / 2 , but avoids overflow for large l and h ; Sort first and second halves ; Merge the sorted halves ; Function to print an array ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE void merge ( int arr [ ] , int l , int m , int r ) { int i , j , k ; int n1 = m - l + 1 ; int n2 = r - m ; int L [ n1 ] , R [ n2 ] ; for ( i = 0 ; i < n1 ; i ++ ) L [ i ] = arr [ l + i ] ; for ( j = 0 ; j < n2 ; j ++ ) R [ j ] = arr [ m + 1 + j ] ; i = 0 ; j = 0 ; k = l ; while ( i < n1 && j < n2 ) { if ( L [ i ] <= R [ j ] ) { arr [ k ] = L [ i ] ; i ++ ; } else { arr [ k ] = R [ j ] ; j ++ ; } k ++ ; } while ( i < n1 ) { arr [ k ] = L [ i ] ; i ++ ; k ++ ; } while ( j < n2 ) { arr [ k ] = R [ j ] ; j ++ ; k ++ ; } } void mergeSort ( int arr [ ] , int l , int r ) { if ( l < r ) { int m = l + ( r - l ) / 2 ; mergeSort ( arr , l , m ) ; mergeSort ( arr , m + 1 , r ) ; merge ( arr , l , m , r ) ; } } void printArray ( int A [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , A [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , arr_size ) ; mergeSort ( arr , 0 , arr_size - 1 ) ; printf ( " Sorted array is " printArray ( arr , arr_size ) ; return 0 ; }
Iterative Quick Sort | An iterative implementation of quick sort ; A utility function to swap two elements ; This function is same in both iterative and recursive ; A [ ] -- > Array to be sorted , l -- > Starting index , h -- > Ending index ; Create an auxiliary stack ; initialize top of stack ; push initial values of l and h to stack ; Keep popping from stack while is not empty ; Pop h and l ; Set pivot element at its correct position in sorted array ; If there are elements on left side of pivot , then push left side to stack ; If there are elements on right side of pivot , then push right side to stack ; A utility function to print contents of arr ; Driver program to test above functions ; Function calling
#include <stdio.h> NEW_LINE void swap ( int * a , int * b ) { int t = * a ; * a = * b ; * b = t ; } int partition ( int arr [ ] , int l , int h ) { int x = arr [ h ] ; int i = ( l - 1 ) ; for ( int j = l ; j <= h - 1 ; j ++ ) { if ( arr [ j ] <= x ) { i ++ ; swap ( & arr [ i ] , & arr [ j ] ) ; } } swap ( & arr [ i + 1 ] , & arr [ h ] ) ; return ( i + 1 ) ; } void quickSortIterative ( int arr [ ] , int l , int h ) { int stack [ h - l + 1 ] ; int top = -1 ; stack [ ++ top ] = l ; stack [ ++ top ] = h ; while ( top >= 0 ) { h = stack [ top -- ] ; l = stack [ top -- ] ; int p = partition ( arr , l , h ) ; if ( p - 1 > l ) { stack [ ++ top ] = l ; stack [ ++ top ] = p - 1 ; } if ( p + 1 < h ) { stack [ ++ top ] = p + 1 ; stack [ ++ top ] = h ; } } } void printArr ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; ++ i ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 4 , 3 , 5 , 2 , 1 , 3 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( * arr ) ; quickSortIterative ( arr , 0 , n - 1 ) ; printArr ( arr , n ) ; return 0 ; }
Activity Selection Problem | Greedy Algo | C program for activity selection problem . The following implementation assumes that the activities are already sorted according to their finish time ; Prints a maximum set of activities that can be done by a single person , one at a time . n -- > Total number of activities s [ ] -- > An array that contains start time of all activities f [ ] -- > An array that contains finish time of all activities ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; driver program to test above function
#include <stdio.h> NEW_LINE void printMaxActivities ( int s [ ] , int f [ ] , int n ) { int i , j ; printf ( " Following ▁ activities ▁ are ▁ selected ▁ n " ) ; i = 0 ; printf ( " % d ▁ " , i ) ; for ( j = 1 ; j < n ; j ++ ) { if ( s [ j ] >= f [ i ] ) { printf ( " % d ▁ " , j ) ; i = j ; } } } int main ( ) { int s [ ] = { 1 , 3 , 0 , 5 , 8 , 5 } ; int f [ ] = { 2 , 4 , 6 , 7 , 9 , 9 } ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; printMaxActivities ( s , f , n ) ; return 0 ; }
Efficient Huffman Coding for Sorted Input | Greedy Algo | C Program for Efficient Huffman Coding for Sorted input ; This constant can be avoided by explicitly calculating height of Huffman Tree ; A node of huffman tree ; Structure for Queue : collection of Huffman Tree nodes ( orQueueNodes ) ; A utility function to create a new Queuenode ; A utility function to create a Queue of given capacity ; A utility function to check if size of given queue is 1 ; A utility function to check if given queue is empty ; A utility function to check if given queue is full ; A utility function to add an item to queue ; A utility function to remove an item from queue ; If there is only one item in queue ; A utility function to get from of queue ; A function to get minimum item from two queues ; Step 3. a : If first queue is empty , dequeue from second queue ; Step 3. b : If second queue is empty , dequeue from first queue ; Step 3. c : Else , compare the front of two queues and dequeue minimum ; Utility function to check if this node is leaf ; A utility function to print an array of size n ; The main function that builds Huffman tree ; Step 1 : Create two empty queues ; Step 2 : Create a leaf node for each unique character and Enqueue it to the first queue in non - decreasing order of frequency . Initially second queue is empty ; Run while Queues contain more than one node . Finally , first queue will be empty and second queue will contain only one node ; Step 3 : Dequeue two nodes with the minimum frequency by examining the front of both queues ; Step 4 : Create a new internal node with frequency equal to the sum of the two nodes frequencies . Enqueue this node to second queue . ; Prints huffman codes from the root of Huffman Tree . It uses arr [ ] to store codes ; Assign 0 to left edge and recur ; Assign 1 to right edge and recur ; If this is a leaf node , then it contains one of the input characters , print the character and its code from arr [ ] ; The main function that builds a Huffman Tree and print codes by traversing the built Huffman Tree ; Construct Huffman Tree ; Print Huffman codes using the Huffman tree built above ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define MAX_TREE_HT 100 NEW_LINE struct QueueNode { char data ; unsigned freq ; struct QueueNode * left , * right ; } ; struct Queue { int front , rear ; int capacity ; struct QueueNode * * array ; } ; struct QueueNode * newNode ( char data , unsigned freq ) { struct QueueNode * temp = ( struct QueueNode * ) malloc ( sizeof ( struct QueueNode ) ) ; temp -> left = temp -> right = NULL ; temp -> data = data ; temp -> freq = freq ; return temp ; } struct Queue * createQueue ( int capacity ) { struct Queue * queue = ( struct Queue * ) malloc ( sizeof ( struct Queue ) ) ; queue -> front = queue -> rear = -1 ; queue -> capacity = capacity ; queue -> array = ( struct QueueNode * * ) malloc ( queue -> capacity * sizeof ( struct QueueNode * ) ) ; return queue ; } int isSizeOne ( struct Queue * queue ) { return queue -> front == queue -> rear && queue -> front != -1 ; } int isEmpty ( struct Queue * queue ) { return queue -> front == -1 ; } int isFull ( struct Queue * queue ) { return queue -> rear == queue -> capacity - 1 ; } void enQueue ( struct Queue * queue , struct QueueNode * item ) { if ( isFull ( queue ) ) return ; queue -> array [ ++ queue -> rear ] = item ; if ( queue -> front == -1 ) ++ queue -> front ; } struct QueueNode * deQueue ( struct Queue * queue ) { if ( isEmpty ( queue ) ) return NULL ; struct QueueNode * temp = queue -> array [ queue -> front ] ; if ( queue -> front == queue -> rear ) queue -> front = queue -> rear = -1 ; else ++ queue -> front ; return temp ; } struct QueueNode * getFront ( struct Queue * queue ) { if ( isEmpty ( queue ) ) return NULL ; return queue -> array [ queue -> front ] ; } struct QueueNode * findMin ( struct Queue * firstQueue , struct Queue * secondQueue ) { if ( isEmpty ( firstQueue ) ) return deQueue ( secondQueue ) ; if ( isEmpty ( secondQueue ) ) return deQueue ( firstQueue ) ; if ( getFront ( firstQueue ) -> freq < getFront ( secondQueue ) -> freq ) return deQueue ( firstQueue ) ; return deQueue ( secondQueue ) ; } int isLeaf ( struct QueueNode * root ) { return ! ( root -> left ) && ! ( root -> right ) ; } void printArr ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; ++ i ) printf ( " % d " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } struct QueueNode * buildHuffmanTree ( char data [ ] , int freq [ ] , int size ) { struct QueueNode * left , * right , * top ; struct Queue * firstQueue = createQueue ( size ) ; struct Queue * secondQueue = createQueue ( size ) ; for ( int i = 0 ; i < size ; ++ i ) enQueue ( firstQueue , newNode ( data [ i ] , freq [ i ] ) ) ; while ( ! ( isEmpty ( firstQueue ) && isSizeOne ( secondQueue ) ) ) { left = findMin ( firstQueue , secondQueue ) ; right = findMin ( firstQueue , secondQueue ) ; top = newNode ( ' $ ' , left -> freq + right -> freq ) ; top -> left = left ; top -> right = right ; enQueue ( secondQueue , top ) ; } return deQueue ( secondQueue ) ; } void printCodes ( struct QueueNode * root , int arr [ ] , int top ) { if ( root -> left ) { arr [ top ] = 0 ; printCodes ( root -> left , arr , top + 1 ) ; } if ( root -> right ) { arr [ top ] = 1 ; printCodes ( root -> right , arr , top + 1 ) ; } if ( isLeaf ( root ) ) { printf ( " % c : ▁ " , root -> data ) ; printArr ( arr , top ) ; } } void HuffmanCodes ( char data [ ] , int freq [ ] , int size ) { struct QueueNode * root = buildHuffmanTree ( data , freq , size ) ; int arr [ MAX_TREE_HT ] , top = 0 ; printCodes ( root , arr , top ) ; } int main ( ) { char arr [ ] = { ' a ' , ' b ' , ' c ' , ' d ' , ' e ' , ' f ' } ; int freq [ ] = { 5 , 9 , 12 , 13 , 16 , 45 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; HuffmanCodes ( arr , freq , size ) ; return 0 ; }
Longest Common Subsequence | DP | A Naive recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Utility function to get max of 2 integers ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE int max ( int a , int b ) ; int lcs ( char * X , char * Y , int m , int n ) { if ( m == 0 n == 0 ) return 0 ; if ( X [ m - 1 ] == Y [ n - 1 ] ) return 1 + lcs ( X , Y , m - 1 , n - 1 ) ; else return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int main ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % d " , lcs ( X , Y , m , n ) ) ; return 0 ; }
Longest Common Subsequence | DP | Dynamic Programming C implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Utility function to get max of 2 integers ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE int max ( int a , int b ) ; int lcs ( char * X , char * Y , int m , int n ) { int L [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } int main ( ) { char X [ ] = " AGGTAB " ; char Y [ ] = " GXTXAYB " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; printf ( " Length ▁ of ▁ LCS ▁ is ▁ % d " , lcs ( X , Y , m , n ) ) ; return 0 ; }
Min Cost Path | DP | A Naive recursive implementation of MCP ( Minimum Cost Path ) problem ; A utility function that returns minimum of 3 integers ; Returns cost of minimum cost path from ( 0 , 0 ) to ( m , n ) in mat [ R ] [ C ] ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE int min ( int x , int y , int z ) ; int min ( int x , int y , int z ) { if ( x < y ) return ( x < z ) ? x : z ; else return ( y < z ) ? y : z ; } int minCost ( int cost [ R ] [ C ] , int m , int n ) { if ( n < 0 m < 0 ) return INT_MAX ; else if ( m == 0 && n == 0 ) return cost [ m ] [ n ] ; else return cost [ m ] [ n ] + min ( minCost ( cost , m - 1 , n - 1 ) , minCost ( cost , m - 1 , n ) , minCost ( cost , m , n - 1 ) ) ; } int main ( ) { int cost [ R ] [ C ] = { { 1 , 2 , 3 } , { 4 , 8 , 2 } , { 1 , 5 , 3 } } ; printf ( " ▁ % d ▁ " , minCost ( cost , 2 , 2 ) ) ; return 0 ; }
Min Cost Path | DP | Dynamic Programming implementation of MCP problem ; Instead of following line , we can use int tc [ m + 1 ] [ n + 1 ] or dynamically allocate memory to save space . The following line is used to keep the program simple and make it working on all compilers . ; Initialize first column of total cost ( tc ) array ; Initialize first row of tc array ; Construct rest of the tc array ; A utility function that returns minimum of 3 integers ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE int min ( int x , int y , int z ) ; int minCost ( int cost [ R ] [ C ] , int m , int n ) { int i , j ; int tc [ R ] [ C ] ; tc [ 0 ] [ 0 ] = cost [ 0 ] [ 0 ] ; for ( i = 1 ; i <= m ; i ++ ) tc [ i ] [ 0 ] = tc [ i - 1 ] [ 0 ] + cost [ i ] [ 0 ] ; for ( j = 1 ; j <= n ; j ++ ) tc [ 0 ] [ j ] = tc [ 0 ] [ j - 1 ] + cost [ 0 ] [ j ] ; for ( i = 1 ; i <= m ; i ++ ) for ( j = 1 ; j <= n ; j ++ ) tc [ i ] [ j ] = min ( tc [ i - 1 ] [ j - 1 ] , tc [ i - 1 ] [ j ] , tc [ i ] [ j - 1 ] ) + cost [ i ] [ j ] ; return tc [ m ] [ n ] ; } int min ( int x , int y , int z ) { if ( x < y ) return ( x < z ) ? x : z ; else return ( y < z ) ? y : z ; } int main ( ) { int cost [ R ] [ C ] = { { 1 , 2 , 3 } , { 4 , 8 , 2 } , { 1 , 5 , 3 } } ; printf ( " ▁ % d ▁ " , minCost ( cost , 2 , 2 ) ) ; return 0 ; }
0 | A Naive recursive implementation of 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack capacity W , then this item cannot be included in the optimal solution ; Return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver program to test above function
#include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { if ( n == 0 W == 0 ) return 0 ; if ( wt [ n - 1 ] > W ) return knapSack ( W , wt , val , n - 1 ) ; else return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printf ( " % d " , knapSack ( W , wt , val , n ) ) ; return 0 ; }
0 | A Dynamic Programming based solution for 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; Driver Code
#include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { int i , w ; int K [ n + 1 ] [ W + 1 ] ; for ( i = 0 ; i <= n ; i ++ ) { for ( w = 0 ; w <= W ; w ++ ) { if ( i == 0 w == 0 ) K [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) ; else K [ i ] [ w ] = K [ i - 1 ] [ w ] ; } } return K [ n ] [ W ] ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; printf ( " % d " , knapSack ( W , wt , val , n ) ) ; return 0 ; }
Egg Dropping Puzzle | DP | ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver program to test to pront printDups
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { if ( k == 1 k == 0 ) return k ; if ( n == 1 ) return k ; int min = INT_MAX , x , res ; for ( x = 1 ; x <= k ; x ++ ) { res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) ; if ( res < min ) min = res ; } return min + 1 ; } int main ( ) { int n = 2 , k = 10 ; printf ( " nMinimum ▁ number ▁ of ▁ trials ▁ in ▁ " " worst ▁ case ▁ with ▁ % d ▁ eggs ▁ and ▁ " " % d ▁ floors ▁ is ▁ % d ▁ STRNEWLINE " , n , k , eggDrop ( n , k ) ) ; return 0 ; }
Longest Palindromic Subsequence | DP | C program of above approach ; A utility function to get max of two integers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and last characters do not match ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int max ( int x , int y ) { return ( x > y ) ? x : y ; } int lps ( char * seq , int i , int j ) { if ( i == j ) return 1 ; if ( seq [ i ] == seq [ j ] && i + 1 == j ) return 2 ; if ( seq [ i ] == seq [ j ] ) return lps ( seq , i + 1 , j - 1 ) + 2 ; return max ( lps ( seq , i , j - 1 ) , lps ( seq , i + 1 , j ) ) ; } int main ( ) { char seq [ ] = " GEEKSFORGEEKS " ; int n = strlen ( seq ) ; printf ( " The ▁ length ▁ of ▁ the ▁ LPS ▁ is ▁ % d " , lps ( seq , 0 , n - 1 ) ) ; getchar ( ) ; return 0 ; }
Word Wrap Problem | DP | A Dynamic programming solution for Word Wrap Problem ; A utility function to print the solution ; l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa ▁ bb ▁ cc ▁ ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; For simplicity , 1 extra space is used in all below arrays extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . The value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; Calculate line cost corresponding to the above calculated extra spaces . The value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; Driver program to test above functions
#include <limits.h> NEW_LINE #include <stdio.h> NEW_LINE #define INF INT_MAX NEW_LINE int printSolution ( int p [ ] , int n ) ; int printSolution ( int p [ ] , int n ) { int k ; if ( p [ n ] == 1 ) k = 1 ; else k = printSolution ( p , p [ n ] - 1 ) + 1 ; printf ( " Line ▁ number ▁ % d : ▁ From ▁ word ▁ no . ▁ % d ▁ to ▁ % d ▁ STRNEWLINE " , k , p [ n ] , n ) ; return k ; } void solveWordWrap ( int l [ ] , int n , int M ) { int extras [ n + 1 ] [ n + 1 ] ; int lc [ n + 1 ] [ n + 1 ] ; int c [ n + 1 ] ; int p [ n + 1 ] ; int i , j ; for ( i = 1 ; i <= n ; i ++ ) { extras [ i ] [ i ] = M - l [ i - 1 ] ; for ( j = i + 1 ; j <= n ; j ++ ) extras [ i ] [ j ] = extras [ i ] [ j - 1 ] - l [ j - 1 ] - 1 ; } for ( i = 1 ; i <= n ; i ++ ) { for ( j = i ; j <= n ; j ++ ) { if ( extras [ i ] [ j ] < 0 ) lc [ i ] [ j ] = INF ; else if ( j == n && extras [ i ] [ j ] >= 0 ) lc [ i ] [ j ] = 0 ; else lc [ i ] [ j ] = extras [ i ] [ j ] * extras [ i ] [ j ] ; } } c [ 0 ] = 0 ; for ( j = 1 ; j <= n ; j ++ ) { c [ j ] = INF ; for ( i = 1 ; i <= j ; i ++ ) { if ( c [ i - 1 ] != INF && lc [ i ] [ j ] != INF && ( c [ i - 1 ] + lc [ i ] [ j ] < c [ j ] ) ) { c [ j ] = c [ i - 1 ] + lc [ i ] [ j ] ; p [ j ] = i ; } } } printSolution ( p , n ) ; } int main ( ) { int l [ ] = { 3 , 2 , 2 , 5 } ; int n = sizeof ( l ) / sizeof ( l [ 0 ] ) ; int M = 6 ; solveWordWrap ( l , n , M ) ; return 0 ; }
Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A recursive function to calculate cost of optimal binary search tree ; Base cases no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } int optCost ( int freq [ ] , int i , int j ) { if ( j < i ) return 0 ; if ( j == i ) return freq [ i ] ; int fsum = sum ( freq , i , j ) ; int min = INT_MAX ; for ( int r = i ; r <= j ; ++ r ) { int cost = optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ; if ( cost < min ) min = cost ; } return min + fsum ; } int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { return optCost ( freq , 0 , n - 1 ) ; } int main ( ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = sizeof ( keys ) / sizeof ( keys [ 0 ] ) ; printf ( " Cost ▁ of ▁ Optimal ▁ BST ▁ is ▁ % d ▁ " , optimalSearchTree ( keys , freq , n ) ) ; return 0 ; }
Optimal Binary Search Tree | DP | Dynamic Programming code for Optimal Binary Search Tree Problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A Dynamic Programming based function that calculates minimum cost of a Binary Search Tree . ; Create an auxiliary 2D matrix to store results of subproblems ; For a single key , cost is equal to frequency of the key ; Now we need to consider chains of length 2 , 3 , ... . L is chain length . ; i is row number in cost [ ] [ ] ; Get column number j from row number i and chain length L ; Try making all keys in interval keys [ i . . j ] as root ; c = cost when keys [ r ] becomes root of this subtree ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { int cost [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) cost [ i ] [ i ] = freq [ i ] ; for ( int L = 2 ; L <= n ; L ++ ) { for ( int i = 0 ; i <= n - L + 1 ; i ++ ) { int j = i + L - 1 ; cost [ i ] [ j ] = INT_MAX ; for ( int r = i ; r <= j ; r ++ ) { int c = ( ( r > i ) ? cost [ i ] [ r - 1 ] : 0 ) + ( ( r < j ) ? cost [ r + 1 ] [ j ] : 0 ) + sum ( freq , i , j ) ; if ( c < cost [ i ] [ j ] ) cost [ i ] [ j ] = c ; } } } return cost [ 0 ] [ n - 1 ] ; } int main ( ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = sizeof ( keys ) / sizeof ( keys [ 0 ] ) ; printf ( " Cost ▁ of ▁ Optimal ▁ BST ▁ is ▁ % d ▁ " , optimalSearchTree ( keys , freq , n ) ) ; return 0 ; }
Largest Independent Set Problem | DP | A naive recursive implementation of Largest Independent Set problem ; A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree ; Caculate size excluding the current node ; Calculate size including the current node ; Return the maximum of two sizes ; A utility function to create a node ; Driver program to test above functions ; Let us construct the tree given in the above diagram
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int max ( int x , int y ) { return ( x > y ) ? x : y ; } struct node { int data ; struct node * left , * right ; } ; int LISS ( struct node * root ) { if ( root == NULL ) return 0 ; int size_excl = LISS ( root -> left ) + LISS ( root -> right ) ; int size_incl = 1 ; if ( root -> left ) size_incl += LISS ( root -> left -> left ) + LISS ( root -> left -> right ) ; if ( root -> right ) size_incl += LISS ( root -> right -> left ) + LISS ( root -> right -> right ) ; return max ( size_incl , size_excl ) ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; root -> right = newNode ( 22 ) ; root -> right -> right = newNode ( 25 ) ; printf ( " Size ▁ of ▁ the ▁ Largest ▁ Independent ▁ Set ▁ is ▁ % d ▁ " , LISS ( root ) ) ; return 0 ; }
Mobile Numeric Keypad Problem | A Space Optimized C program to count number of possible numbers of given length ; Return count of all possible numbers of length n in a given numeric keyboard ; odd [ i ] , even [ i ] arrays represent count of numbers starting with digit i for any length j ; for j = 1 ; Bottom Up calculation from j = 2 to n ; Here we are explicitly writing lines for each number 0 to 9. But it can always be written as DFS on 4 X3 grid using row , column array valid moves ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver program to test above function
#include <stdio.h> NEW_LINE int getCount ( char keypad [ ] [ 3 ] , int n ) { if ( keypad == NULL n <= 0 ) return 0 ; if ( n == 1 ) return 10 ; int odd [ 10 ] , even [ 10 ] ; int i = 0 , j = 0 , useOdd = 0 , totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) odd [ i ] = 1 ; for ( j = 2 ; j <= n ; j ++ ) { useOdd = 1 - useOdd ; if ( useOdd == 1 ) { even [ 0 ] = odd [ 0 ] + odd [ 8 ] ; even [ 1 ] = odd [ 1 ] + odd [ 2 ] + odd [ 4 ] ; even [ 2 ] = odd [ 2 ] + odd [ 1 ] + odd [ 3 ] + odd [ 5 ] ; even [ 3 ] = odd [ 3 ] + odd [ 2 ] + odd [ 6 ] ; even [ 4 ] = odd [ 4 ] + odd [ 1 ] + odd [ 5 ] + odd [ 7 ] ; even [ 5 ] = odd [ 5 ] + odd [ 2 ] + odd [ 4 ] + odd [ 8 ] + odd [ 6 ] ; even [ 6 ] = odd [ 6 ] + odd [ 3 ] + odd [ 5 ] + odd [ 9 ] ; even [ 7 ] = odd [ 7 ] + odd [ 4 ] + odd [ 8 ] ; even [ 8 ] = odd [ 8 ] + odd [ 0 ] + odd [ 5 ] + odd [ 7 ] + odd [ 9 ] ; even [ 9 ] = odd [ 9 ] + odd [ 6 ] + odd [ 8 ] ; } else { odd [ 0 ] = even [ 0 ] + even [ 8 ] ; odd [ 1 ] = even [ 1 ] + even [ 2 ] + even [ 4 ] ; odd [ 2 ] = even [ 2 ] + even [ 1 ] + even [ 3 ] + even [ 5 ] ; odd [ 3 ] = even [ 3 ] + even [ 2 ] + even [ 6 ] ; odd [ 4 ] = even [ 4 ] + even [ 1 ] + even [ 5 ] + even [ 7 ] ; odd [ 5 ] = even [ 5 ] + even [ 2 ] + even [ 4 ] + even [ 8 ] + even [ 6 ] ; odd [ 6 ] = even [ 6 ] + even [ 3 ] + even [ 5 ] + even [ 9 ] ; odd [ 7 ] = even [ 7 ] + even [ 4 ] + even [ 8 ] ; odd [ 8 ] = even [ 8 ] + even [ 0 ] + even [ 5 ] + even [ 7 ] + even [ 9 ] ; odd [ 9 ] = even [ 9 ] + even [ 6 ] + even [ 8 ] ; } } totalCount = 0 ; if ( useOdd == 1 ) { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += even [ i ] ; } else { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += odd [ i ] ; } return totalCount ; } int main ( ) { char keypad [ 4 ] [ 3 ] = { { '1' , '2' , '3' } , { '4' , '5' , '6' } , { '7' , '8' , '9' } , { ' * ' , '0' , ' # ' } } ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 1 , getCount ( keypad , 1 ) ) ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 2 , getCount ( keypad , 2 ) ) ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 3 , getCount ( keypad , 3 ) ) ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 4 , getCount ( keypad , 4 ) ) ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 5 , getCount ( keypad , 5 ) ) ; return 0 ; }
Vertex Cover Problem | Set 2 ( Dynamic Programming Solution for Tree ) | Dynamic programming based program for Vertex Cover problem for a Binary Tree ; A utility function to find min of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; A memoization based function that returns size of the minimum vertex cover . ; The size of minimum vertex cover is zero if tree is empty or there is only one node ; If vertex cover for this node is already evaluated , then return it to save recomputation of same subproblem again . ; Calculate size of vertex cover when root is part of it ; Calculate size of vertex cover when root is not part of it ; Minimum of two values is vertex cover , store it before returning ; A utility function to create a node ; Set the vertex cover as 0 ; Driver program to test above functions ; Let us construct the tree given in the above diagram
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int min ( int x , int y ) { return ( x < y ) ? x : y ; } struct node { int data ; int vc ; struct node * left , * right ; } ; int vCover ( struct node * root ) { if ( root == NULL ) return 0 ; if ( root -> left == NULL && root -> right == NULL ) return 0 ; if ( root -> vc != 0 ) return root -> vc ; int size_incl = 1 + vCover ( root -> left ) + vCover ( root -> right ) ; int size_excl = 0 ; if ( root -> left ) size_excl += 1 + vCover ( root -> left -> left ) + vCover ( root -> left -> right ) ; if ( root -> right ) size_excl += 1 + vCover ( root -> right -> left ) + vCover ( root -> right -> right ) ; root -> vc = min ( size_incl , size_excl ) ; return root -> vc ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; temp -> vc = 0 ; return temp ; } int main ( ) { struct node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; root -> right = newNode ( 22 ) ; root -> right -> right = newNode ( 25 ) ; printf ( " Size ▁ of ▁ the ▁ smallest ▁ vertex ▁ cover ▁ is ▁ % d ▁ " , vCover ( root ) ) ; return 0 ; }
Count number of ways to reach a given score in a game | A C program to count number of possible ways to a given score can be reached in a game where a move can earn 3 or 5 or 10 ; Returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; Initialize all table values as 0 ; Base case ( If given value is 0 ) ; One by one consider given 3 moves and update the table [ ] values after the index greater than or equal to the value of the picked move ; Driver program
#include <stdio.h> NEW_LINE int count ( int n ) { int table [ n + 1 ] , i ; memset ( table , 0 , sizeof ( table ) ) ; table [ 0 ] = 1 ; for ( i = 3 ; i <= n ; i ++ ) table [ i ] += table [ i - 3 ] ; for ( i = 5 ; i <= n ; i ++ ) table [ i ] += table [ i - 5 ] ; for ( i = 10 ; i <= n ; i ++ ) table [ i ] += table [ i - 10 ] ; return table [ n ] ; } int main ( void ) { int n = 20 ; printf ( " Count ▁ for ▁ % d ▁ is ▁ % d STRNEWLINE " , n , count ( n ) ) ; n = 13 ; printf ( " Count ▁ for ▁ % d ▁ is ▁ % d " , n , count ( n ) ) ; return 0 ; }
Naive algorithm for Pattern Searching | C program for Naive Pattern Searching algorithm ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void search ( char * pat , char * txt ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) printf ( " Pattern ▁ found ▁ at ▁ index ▁ % d ▁ STRNEWLINE " , i ) ; } } int main ( ) { char txt [ ] = " AABAACAADAABAAABAA " ; char pat [ ] = " AABA " ; search ( pat , txt ) ; return 0 ; }
Rabin | Following program is a C implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern ; hash value for txt ; The value of h would be " pow ( d , ▁ M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver Code ; A prime number ; function call
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define d 256 NEW_LINE void search ( char pat [ ] , char txt [ ] , int q ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i , j ; int p = 0 ; int t = 0 ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat [ i ] ) % q ; t = ( d * t + txt [ i ] ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { for ( j = 0 ; j < M ; j ++ ) { if ( txt [ i + j ] != pat [ j ] ) break ; } if ( j == M ) printf ( " Pattern ▁ found ▁ at ▁ index ▁ % d ▁ STRNEWLINE " , i ) ; } if ( i < N - M ) { t = ( d * ( t - txt [ i ] * h ) + txt [ i + M ] ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } int main ( ) { char txt [ ] = " GEEKS ▁ FOR ▁ GEEKS " ; char pat [ ] = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; return 0 ; }
Optimized Naive Algorithm for Pattern Searching | C program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pettern Searching algorithn that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE void search ( char pat [ ] , char txt [ ] ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { printf ( " Pattern ▁ found ▁ at ▁ index ▁ % d ▁ STRNEWLINE " , i ) ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } int main ( ) { char txt [ ] = " ABCEABCDABCEABCD " ; char pat [ ] = " ABCD " ; search ( pat , txt ) ; return 0 ; }
Finite Automata algorithm for Pattern Searching | C program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; ns stores the result which is next state ; ns finally contains the longest prefix which is also suffix in " pat [ 0 . . state - 1 ] c " Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents4 Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define NO_OF_CHARS 256 NEW_LINE int getNextState ( char * pat , int M , int state , int x ) { if ( state < M && x == pat [ state ] ) return state + 1 ; int ns , i ; for ( ns = state ; ns > 0 ; ns -- ) { if ( pat [ ns - 1 ] == x ) { for ( i = 0 ; i < ns - 1 ; i ++ ) if ( pat [ i ] != pat [ state - ns + 1 + i ] ) break ; if ( i == ns - 1 ) return ns ; } } return 0 ; } void computeTF ( char * pat , int M , int TF [ ] [ NO_OF_CHARS ] ) { int state , x ; for ( state = 0 ; state <= M ; ++ state ) for ( x = 0 ; x < NO_OF_CHARS ; ++ x ) TF [ state ] [ x ] = getNextState ( pat , M , state , x ) ; } void search ( char * pat , char * txt ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int TF [ M + 1 ] [ NO_OF_CHARS ] ; computeTF ( pat , M , TF ) ; int i , state = 0 ; for ( i = 0 ; i < N ; i ++ ) { state = TF [ state ] [ txt [ i ] ] ; if ( state == M ) printf ( " Pattern found at index % d " , i - M + 1 ) ; } } int main ( ) { char * txt = " AABAACAADAABAAABAA " ; char * pat = " AABA " ; search ( pat , txt ) ; return 0 ; }
Boyer Moore Algorithm for Pattern Searching | C Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm ; A utility function to get maximum of two integers ; The preprocessing function for Boyer Moore 's bad character heuristic ; Initialize all occurrences as - 1 ; Fill the actual value of last occurrence of a character ; A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm ; Fill the bad character array by calling the preprocessing function badCharHeuristic ( ) for given pattern ; s is shift of the pattern with respect to text ; there are n - m + 1 potential allignments ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at current shift , then index j will become - 1 after the above loop ; Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern . The condition s + m < n is necessary for the case when pattern occurs at the end of text ; Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern . The max function is used to make sure that we get a positive shift . We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character . ; Driver program to test above function
# include <limits.h> NEW_LINE # include <string.h> NEW_LINE # include <stdio.h> NEW_LINE # define NO_OF_CHARS 256 NEW_LINE int max ( int a , int b ) { return ( a > b ) ? a : b ; } void badCharHeuristic ( char * str , int size , int badchar [ NO_OF_CHARS ] ) { int i ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) badchar [ i ] = -1 ; for ( i = 0 ; i < size ; i ++ ) badchar [ ( int ) str [ i ] ] = i ; } void search ( char * txt , char * pat ) { int m = strlen ( pat ) ; int n = strlen ( txt ) ; int badchar [ NO_OF_CHARS ] ; badCharHeuristic ( pat , m , badchar ) ; int s = 0 ; while ( s <= ( n - m ) ) { int j = m - 1 ; while ( j >= 0 && pat [ j ] == txt [ s + j ] ) j -- ; if ( j < 0 ) { printf ( " pattern occurs at shift = % d " , s ) ; s += ( s + m < n ) ? m - badchar [ txt [ s + m ] ] : 1 ; } else s += max ( 1 , j - badchar [ txt [ s + j ] ] ) ; } } int main ( ) { char txt [ ] = " ABAAABCD " ; char pat [ ] = " ABC " ; search ( txt , pat ) ; return 0 ; }
Subset Sum | Backtracking | ; prints subset found ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found subset ; Exclude previously added item and consider next candidate ; generate nodes along the breadth ; consider next level node ( along depth ) ; Wrapper to print subsets that sum to target_sum input is weights vector and target_sum ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define ARRAYSIZE ( a ) (sizeof(a))/(sizeof(a[0])) NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { printf ( " % * d " , 5 , A [ i ] ) ; } printf ( " STRNEWLINE " ) ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; return ; } else { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = ( int * ) malloc ( size * sizeof ( int ) ) ; subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 10 , 7 , 5 , 18 , 12 , 20 , 15 } ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , 35 ) ; printf ( " Nodes ▁ generated ▁ % d ▁ STRNEWLINE " , total_nodes ) ; return 0 ; }
Subset Sum | Backtracking | ; prints subset found ; qsort compare function ; inputs s - set vector t - tuplet vector s_size - set size t_size - tuplet size so far sum - sum so far ite - nodes count target_sum - sum to be found ; We found sum ; constraint check ; Exclude previous added item and consider next candidate ; constraint check ; generate nodes along the breadth ; consider next level node ( along depth ) ; Wrapper that prints subsets that sum to target_sum ; sort the set ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define ARRAYSIZE ( a ) (sizeof(a))/(sizeof(a[0])) NEW_LINE static int total_nodes ; void printSubset ( int A [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { printf ( " % * d " , 5 , A [ i ] ) ; } printf ( " STRNEWLINE " ) ; } int comparator ( const void * pLhs , const void * pRhs ) { int * lhs = ( int * ) pLhs ; int * rhs = ( int * ) pRhs ; return * lhs > * rhs ; } void subset_sum ( int s [ ] , int t [ ] , int s_size , int t_size , int sum , int ite , int const target_sum ) { total_nodes ++ ; if ( target_sum == sum ) { printSubset ( t , t_size ) ; if ( ite + 1 < s_size && sum - s [ ite ] + s [ ite + 1 ] <= target_sum ) { subset_sum ( s , t , s_size , t_size - 1 , sum - s [ ite ] , ite + 1 , target_sum ) ; } return ; } else { if ( ite < s_size && sum + s [ ite ] <= target_sum ) { for ( int i = ite ; i < s_size ; i ++ ) { t [ t_size ] = s [ i ] ; if ( sum + s [ i ] <= target_sum ) { subset_sum ( s , t , s_size , t_size + 1 , sum + s [ i ] , i + 1 , target_sum ) ; } } } } } void generateSubsets ( int s [ ] , int size , int target_sum ) { int * tuplet_vector = ( int * ) malloc ( size * sizeof ( int ) ) ; int total = 0 ; qsort ( s , size , sizeof ( int ) , & comparator ) ; for ( int i = 0 ; i < size ; i ++ ) { total += s [ i ] ; } if ( s [ 0 ] <= target_sum && total >= target_sum ) { subset_sum ( s , tuplet_vector , size , 0 , 0 , 0 , target_sum ) ; } free ( tuplet_vector ) ; } int main ( ) { int weights [ ] = { 15 , 22 , 14 , 26 , 32 , 9 , 16 , 8 } ; int target = 53 ; int size = ARRAYSIZE ( weights ) ; generateSubsets ( weights , size , target ) ; printf ( " Nodes ▁ generated ▁ % d STRNEWLINE " , total_nodes ) ; return 0 ; }
Sudoku | Backtracking | ; N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return 0 ; Check if we find the same num in the similar column , we return 0 ; Check if we find the same num in the particular 3 * 3 matrix , we return 0 ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; assigning the num in the current ( row , col ) position of the grid and assuming our assined num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #define N 9 NEW_LINE void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) printf ( " % d ▁ " , arr [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } int isSafe ( int grid [ N ] [ N ] , int row , int col , int num ) { for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ row ] [ x ] == num ) return 0 ; for ( int x = 0 ; x <= 8 ; x ++ ) if ( grid [ x ] [ col ] == num ) return 0 ; int startRow = row - row % 3 , startCol = col - col % 3 ; for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) if ( grid [ i + startRow ] [ j + startCol ] == num ) return 0 ; return 1 ; } int solveSuduko ( int grid [ N ] [ N ] , int row , int col ) { if ( row == N - 1 && col == N ) return 1 ; if ( col == N ) { row ++ ; col = 0 ; } if ( grid [ row ] [ col ] > 0 ) return solveSuduko ( grid , row , col + 1 ) ; for ( int num = 1 ; num <= N ; num ++ ) { if ( isSafe ( grid , row , col , num ) == 1 ) { grid [ row ] [ col ] = num ; if ( solveSuduko ( grid , row , col + 1 ) == 1 ) return 1 ; } grid [ row ] [ col ] = 0 ; } return 0 ; } int main ( ) { int grid [ N ] [ N ] = { { 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 } , { 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 } , { 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 } , { 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 } , { 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 } , { 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 } , { 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 } } ; if ( solveSuduko ( grid , 0 , 0 ) == 1 ) print ( grid ) ; else printf ( " No ▁ solution ▁ exists " ) ; return 0 ; }
Median of two sorted arrays of same size | A Simple Merge based O ( n ) solution to find median of two sorted arrays ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; Store the prev median ; Store the prev median ; Driver program to test above function
#include <stdio.h> NEW_LINE int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { int i = 0 ; int j = 0 ; int count ; int m1 = -1 , m2 = -1 ; for ( count = 0 ; count <= n ; count ++ ) { if ( i == n ) { m1 = m2 ; m2 = ar2 [ 0 ] ; break ; } else if ( j == n ) { m1 = m2 ; m2 = ar1 [ 0 ] ; break ; } if ( ar1 [ i ] <= ar2 [ j ] ) { m1 = m2 ; m2 = ar1 [ i ] ; i ++ ; } else { m1 = m2 ; m2 = ar2 [ j ] ; j ++ ; } } return ( m1 + m2 ) / 2 ; } int main ( ) { int ar1 [ ] = { 1 , 12 , 15 , 26 , 38 } ; int ar2 [ ] = { 2 , 13 , 17 , 30 , 45 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) printf ( " Median ▁ is ▁ % d " , getMedian ( ar1 , ar2 , n1 ) ) ; else printf ( " Doesn ' t ▁ work ▁ for ▁ arrays ▁ of ▁ unequal ▁ size " ) ; getchar ( ) ; return 0 ; }
Median of two sorted arrays of same size | A divide and conquer based efficient solution to find median of two sorted arrays of same size . ; to get median of a sorted array ; This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; get the median of the first array ; get the median of the second array ; If medians are equal then return either m1 or m2 ; if m1 < m2 then median must exist in ar1 [ m1 ... . ] and ar2 [ ... . m2 ] ; if m1 > m2 then median must exist in ar1 [ ... . m1 ] and ar2 [ m2 ... ] ; Function to get median of a sorted array ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int median ( int [ ] , int ) ; int getMedian ( int ar1 [ ] , int ar2 [ ] , int n ) { if ( n <= 0 ) return -1 ; if ( n == 1 ) return ( ar1 [ 0 ] + ar2 [ 0 ] ) / 2 ; if ( n == 2 ) return ( max ( ar1 [ 0 ] , ar2 [ 0 ] ) + min ( ar1 [ 1 ] , ar2 [ 1 ] ) ) / 2 ; int m1 = median ( ar1 , n ) ; int m2 = median ( ar2 , n ) ; if ( m1 == m2 ) return m1 ; if ( m1 < m2 ) { if ( n % 2 == 0 ) return getMedian ( ar1 + n / 2 - 1 , ar2 , n - n / 2 + 1 ) ; return getMedian ( ar1 + n / 2 , ar2 , n - n / 2 ) ; } if ( n % 2 == 0 ) return getMedian ( ar2 + n / 2 - 1 , ar1 , n - n / 2 + 1 ) ; return getMedian ( ar2 + n / 2 , ar1 , n - n / 2 ) ; } int median ( int arr [ ] , int n ) { if ( n % 2 == 0 ) return ( arr [ n / 2 ] + arr [ n / 2 - 1 ] ) / 2 ; else return arr [ n / 2 ] ; } int main ( ) { int ar1 [ ] = { 1 , 2 , 3 , 6 } ; int ar2 [ ] = { 4 , 6 , 8 , 10 } ; int n1 = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n2 = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; if ( n1 == n2 ) printf ( " Median ▁ is ▁ % d " , getMedian ( ar1 , ar2 , n1 ) ) ; else printf ( " Doesn ' t ▁ work ▁ for ▁ arrays ▁ of ▁ unequal ▁ size " ) ; return 0 ; }
Closest Pair of Points using Divide and Conquer algorithm | A divide and conquer program in C / C ++ to find the smallest distance from a given set of points . ; A structure to represent a Point in 2D plane ; Needed to sort array of points according to X coordinate ; Needed to sort array of points according to Y coordinate ; A utility function to find the distance between two points ; A Brute Force method to return the smallest distance between two points in P [ ] of size n ; A utility function to find a minimum of two float values ; A utility function to find the distance between the closest points of strip of a given size . All points in strip [ ] are sorted according to y coordinate . They all have an upper bound on minimum distance as d . Note that this method seems to be a O ( n ^ 2 ) method , but it 's a O(n) method as the inner loop runs at most 6 times ; Initialize the minimum distance as d ; Pick all points one by one and try the next points till the difference between y coordinates is smaller than d . This is a proven fact that this loop runs at most 6 times ; A recursive function to find the smallest distance . The array P contains all points sorted according to x coordinate ; If there are 2 or 3 points , then use brute force ; Find the middle point ; Consider the vertical line passing through the middle point calculate the smallest distance dl on left of middle point and dr on right side ; Find the smaller of two distances ; Build an array strip [ ] that contains points close ( closer than d ) to the line passing through the middle point ; Find the closest points in strip . Return the minimum of d and closest distance is strip [ ] ; The main function that finds the smallest distance This method mainly uses closestUtil ( ) ; Use recursive function closestUtil ( ) to find the smallest distance ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <float.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <math.h> NEW_LINE struct Point { int x , y ; } ; int compareX ( const void * a , const void * b ) { Point * p1 = ( Point * ) a , * p2 = ( Point * ) b ; return ( p1 -> x - p2 -> x ) ; } int compareY ( const void * a , const void * b ) { Point * p1 = ( Point * ) a , * p2 = ( Point * ) b ; return ( p1 -> y - p2 -> y ) ; } float dist ( Point p1 , Point p2 ) { return sqrt ( ( p1 . x - p2 . x ) * ( p1 . x - p2 . x ) + ( p1 . y - p2 . y ) * ( p1 . y - p2 . y ) ) ; } float bruteForce ( Point P [ ] , int n ) { float min = FLT_MAX ; for ( int i = 0 ; i < n ; ++ i ) for ( int j = i + 1 ; j < n ; ++ j ) if ( dist ( P [ i ] , P [ j ] ) < min ) min = dist ( P [ i ] , P [ j ] ) ; return min ; } float min ( float x , float y ) { return ( x < y ) ? x : y ; } float stripClosest ( Point strip [ ] , int size , float d ) { float min = d ; qsort ( strip , size , sizeof ( Point ) , compareY ) ; for ( int i = 0 ; i < size ; ++ i ) for ( int j = i + 1 ; j < size && ( strip [ j ] . y - strip [ i ] . y ) < min ; ++ j ) if ( dist ( strip [ i ] , strip [ j ] ) < min ) min = dist ( strip [ i ] , strip [ j ] ) ; return min ; } float closestUtil ( Point P [ ] , int n ) { if ( n <= 3 ) return bruteForce ( P , n ) ; int mid = n / 2 ; Point midPoint = P [ mid ] ; float dl = closestUtil ( P , mid ) ; float dr = closestUtil ( P + mid , n - mid ) ; float d = min ( dl , dr ) ; Point strip [ n ] ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( abs ( P [ i ] . x - midPoint . x ) < d ) strip [ j ] = P [ i ] , j ++ ; return min ( d , stripClosest ( strip , j , d ) ) ; } float closest ( Point P [ ] , int n ) { qsort ( P , n , sizeof ( Point ) , compareX ) ; return closestUtil ( P , n ) ; } int main ( ) { Point P [ ] = { { 2 , 3 } , { 12 , 30 } , { 40 , 50 } , { 5 , 1 } , { 12 , 10 } , { 3 , 4 } } ; int n = sizeof ( P ) / sizeof ( P [ 0 ] ) ; printf ( " The ▁ smallest ▁ distance ▁ is ▁ % f ▁ " , closest ( P , n ) ) ; return 0 ; }
Lucky Numbers | ; Returns 1 if n is a lucky no . ohterwise returns 0 ; variable next_position is just for readability of the program we can remove it and use n only ; calculate next position of input no ; Driver function to test above function
#include <stdio.h> NEW_LINE #define bool int NEW_LINE bool isLucky ( int n ) { static int counter = 2 ; int next_position = n ; if ( counter > n ) return 1 ; if ( n % counter == 0 ) return 0 ; next_position -= next_position / counter ; counter ++ ; return isLucky ( next_position ) ; } int main ( ) { int x = 5 ; if ( isLucky ( x ) ) printf ( " % d ▁ is ▁ a ▁ lucky ▁ no . " , x ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ lucky ▁ no . " , x ) ; getchar ( ) ; }
Write you own Power without using multiplication ( * ) and division ( / ) operators | ; Works only if a >= 0 and b >= 0 ; driver program to test above function
#include <stdio.h> NEW_LINE int pow ( int a , int b ) { if ( b == 0 ) return 1 ; int answer = a ; int increment = a ; int i , j ; for ( i = 1 ; i < b ; i ++ ) { for ( j = 1 ; j < a ; j ++ ) { answer += increment ; } increment = answer ; } return answer ; } int main ( ) { printf ( " % d " , pow ( 5 , 3 ) ) ; getchar ( ) ; return 0 ; }
Write you own Power without using multiplication ( * ) and division ( / ) operators | ; A recursive function to get x * y ; A recursive function to get a ^ b Works only if a >= 0 and b >= 0 ; driver program to test above functions
#include <stdio.h> NEW_LINE int multiply ( int x , int y ) { if ( y ) return ( x + multiply ( x , y - 1 ) ) ; else return 0 ; } int pow ( int a , int b ) { if ( b ) return multiply ( a , pow ( a , b - 1 ) ) ; else return 1 ; } int main ( ) { printf ( " % d " , pow ( 5 , 3 ) ) ; getchar ( ) ; return 0 ; }
Count numbers that don 't contain 3 | ; returns count of numbers which are in range from 1 to n and don 't contain 3 as a digit ; Base cases ( Assuming n is not negative ) ; Calculate 10 ^ ( d - 1 ) ( 10 raise to the power d - 1 ) where d is number of digits in n . po will be 100 for n = 578 ; find the most significant digit ( msd is 5 for 578 ) ; For 578 , total will be 4 * count ( 10 ^ 2 - 1 ) + 4 + count ( 78 ) ; For 35 , total will be equal to count ( 29 ) ; Driver program to test above function
#include <stdio.h> NEW_LINE int count ( int n ) { if ( n < 3 ) return n ; if ( n >= 3 && n < 10 ) return n - 1 ; int po = 1 ; while ( n / po > 9 ) po = po * 10 ; int msd = n / po ; if ( msd != 3 ) return count ( msd ) * count ( po - 1 ) + count ( msd ) + count ( n % po ) ; else return count ( msd * po - 1 ) ; } int main ( ) { printf ( " % d ▁ " , count ( 578 ) ) ; return 0 ; }
Lexicographic rank of a string | C program to find lexicographic rank of a string ; A utility function to find factorial of n ; A utility function to count smaller characters on right of arr [ low ] ; A function to find rank of a string in all permutations of characters ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE int fact ( int n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } int findSmallerInRight ( char * str , int low , int high ) { int countRight = 0 , i ; for ( i = low + 1 ; i <= high ; ++ i ) if ( str [ i ] < str [ low ] ) ++ countRight ; return countRight ; } int findRank ( char * str ) { int len = strlen ( str ) ; int mul = fact ( len ) ; int rank = 1 ; int countRight ; int i ; for ( i = 0 ; i < len ; ++ i ) { mul /= len - i ; countRight = findSmallerInRight ( str , i , len - 1 ) ; rank += countRight * mul ; } return rank ; } int main ( ) { char str [ ] = " string " ; printf ( " % d " , findRank ( str ) ) ; return 0 ; }
Lexicographic rank of a string | A O ( n ) solution for finding rank of string ; all elements of count [ ] are initialized with 0 ; A utility function to find factorial of n ; Construct a count array where value at every index contains count of smaller characters in whole string ; Removes a character ch from count [ ] array constructed by populateAndIncreaseCount ( ) ; A function to find rank of a string in all permutations of characters ; Populate the count array such that count [ i ] contains count of characters which are present in str and are smaller than i ; count number of chars smaller than str [ i ] fron str [ i + 1 ] to str [ len - 1 ] ; Reduce count of characters greater than str [ i ] ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define MAX_CHAR 256 NEW_LINE int count [ MAX_CHAR ] = { 0 } ; int fact ( int n ) { return ( n <= 1 ) ? 1 : n * fact ( n - 1 ) ; } void populateAndIncreaseCount ( int * count , char * str ) { int i ; for ( i = 0 ; str [ i ] ; ++ i ) ++ count [ str [ i ] ] ; for ( i = 1 ; i < MAX_CHAR ; ++ i ) count [ i ] += count [ i - 1 ] ; } void updatecount ( int * count , char ch ) { int i ; for ( i = ch ; i < MAX_CHAR ; ++ i ) -- count [ i ] ; } int findRank ( char * str ) { int len = strlen ( str ) ; int mul = fact ( len ) ; int rank = 1 , i ; populateAndIncreaseCount ( count , str ) ; for ( i = 0 ; i < len ; ++ i ) { mul /= len - i ; rank += count [ str [ i ] - 1 ] * mul ; updatecount ( count , str [ i ] ) ; } return rank ; } int main ( ) { char str [ ] = " string " ; printf ( " % d " , findRank ( str ) ) ; return 0 ; }
Print all permutations in sorted ( lexicographic ) order | Program to print all permutations of a string in sorted order . ; Following function is needed for library function qsort ( ) . Refer http : www . cplusplus . com / reference / clibrary / cstdlib / qsort / ; A utility function two swap two characters a and b ; This function finds the index of the smallest character which is greater than ' first ' and is present in str [ l . . h ] ; initialize index of ceiling element ; Now iterate through rest of the elements and find the smallest character greater than ' first ' ; Print all permutations of str in sorted order ; Get size of string ; Sort the string in increasing order ; Print permutations one by one ; print this permutation ; Find the rightmost character which is smaller than its next character . Let us call it ' first ▁ char ' ; If there is no such character , all are sorted in decreasing order , means we just printed the last permutation and we are done . ; Find the ceil of ' first ▁ char ' in right of first character . Ceil of a character is the smallest character greater than it ; Swap first and second characters ; Sort the string on right of ' first ▁ char ' ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE int compare ( const void * a , const void * b ) { return ( * ( char * ) a - * ( char * ) b ) ; } void swap ( char * a , char * b ) { char t = * a ; * a = * b ; * b = t ; } int findCeil ( char str [ ] , char first , int l , int h ) { int ceilIndex = l ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( str [ i ] > first && str [ i ] < str [ ceilIndex ] ) ceilIndex = i ; return ceilIndex ; } void sortedPermutations ( char str [ ] ) { int size = strlen ( str ) ; qsort ( str , size , sizeof ( str [ 0 ] ) , compare ) ; bool isFinished = false ; while ( ! isFinished ) { printf ( " % s ▁ STRNEWLINE " , str ) ; int i ; for ( i = size - 2 ; i >= 0 ; -- i ) if ( str [ i ] < str [ i + 1 ] ) break ; if ( i == -1 ) isFinished = true ; else { int ceilIndex = findCeil ( str , str [ i ] , i + 1 , size - 1 ) ; swap ( & str [ i ] , & str [ ceilIndex ] ) ; qsort ( str + i + 1 , size - i - 1 , sizeof ( str [ 0 ] ) , compare ) ; } } } int main ( ) { char str [ ] = " ABCD " ; sortedPermutations ( str ) ; return 0 ; }
Print all permutations in sorted ( lexicographic ) order | An optimized version that uses reverse instead of sort for finding the next permutation A utility function to reverse a string str [ l . . h ] ; ; ; Print all permutations of str in sorted order ; Get size of string ; Sort the string in increasing order ; Print permutations one by one ; print this permutation ; Find the rightmost character which is smaller than its next character . Let us call it ' first ▁ char ' ; If there is no such character , all are sorted in decreasing order , means we just printed the last permutation and we are done . ; Find the ceil of ' first ▁ char ' in right of first character . Ceil of a character is the smallest character greater than it ; Swap first and second characters ; reverse the string on right of ' first ▁ char '
void reverse ( char str [ ] , int l , int h ) { while ( l < h ) { swap ( & str [ l ] , & str [ h ] ) ; l ++ ; h -- ; } } void swap ( char * a , char * b ) { char t = * a ; * a = * b ; * b = t ; } int compare ( const void * a , const void * b ) { return ( * ( char * ) a - * ( char * ) b ) ; } int findCeil ( char str [ ] , char first , int l , int h ) { int ceilIndex = l ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( str [ i ] > first && str [ i ] < str [ ceilIndex ] ) ceilIndex = i ; return ceilIndex ; } void sortedPermutations ( char str [ ] ) { int size = strlen ( str ) ; qsort ( str , size , sizeof ( str [ 0 ] ) , compare ) ; bool isFinished = false ; while ( ! isFinished ) { printf ( " % s ▁ STRNEWLINE " , str ) ; int i ; for ( i = size - 2 ; i >= 0 ; -- i ) if ( str [ i ] < str [ i + 1 ] ) break ; if ( i == -1 ) isFinished = true ; else { int ceilIndex = findCeil ( str , str [ i ] , i + 1 , size - 1 ) ; swap ( & str [ i ] , & str [ ceilIndex ] ) ; reverse ( str , i + 1 , size - 1 ) ; } } }
Efficient program to calculate e ^ x | C Efficient program to calculate e raise to the power x ; Returns approximate value of e ^ x using sum of first n terms of Taylor Series ; initialize sum of series ; Driver program to test above function
#include <stdio.h> NEW_LINE float exponential ( int n , float x ) { float sum = 1.0f ; for ( int i = n - 1 ; i > 0 ; -- i ) sum = 1 + x * sum / i ; return sum ; } int main ( ) { int n = 10 ; float x = 1.0f ; printf ( " e ^ x ▁ = ▁ % f " , exponential ( n , x ) ) ; return 0 ; }
Random number generator in arbitrary probability distribution fashion | C program to generate random numbers according to given frequency distribution ; Utility function to find ceiling of r in arr [ l . . h ] ; Same as mid = ( l + h ) / 2 ; The main function that returns a random number from arr [ ] according to distribution array defined by freq [ ] . n is size of arrays . ; Create and fill prefix array ; prefix [ n - 1 ] is sum of all frequencies . Generate a random number with value from 1 to this sum ; Find index of ceiling of r in prefix arrat ; Driver program to test above functions ; Use a different seed value for every run . ; Let us generate 10 random numbers accroding to given distribution
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int findCeil ( int arr [ ] , int r , int l , int h ) { int mid ; while ( l < h ) { mid = l + ( ( h - l ) >> 1 ) ; ( r > arr [ mid ] ) ? ( l = mid + 1 ) : ( h = mid ) ; } return ( arr [ l ] >= r ) ? l : -1 ; } int myRand ( int arr [ ] , int freq [ ] , int n ) { int prefix [ n ] , i ; prefix [ 0 ] = freq [ 0 ] ; for ( i = 1 ; i < n ; ++ i ) prefix [ i ] = prefix [ i - 1 ] + freq [ i ] ; int r = ( rand ( ) % prefix [ n - 1 ] ) + 1 ; int indexc = findCeil ( prefix , r , 0 , n - 1 ) ; return arr [ indexc ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int freq [ ] = { 10 , 5 , 20 , 100 } ; int i , n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; srand ( time ( NULL ) ) ; for ( i = 0 ; i < 5 ; i ++ ) printf ( " % d STRNEWLINE " , myRand ( arr , freq , n ) ) ; return 0 ; }
Write a function that generates one of 3 numbers according to given probabilities | This function generates ' x ' with probability px / 100 , ' y ' with probability py / 100 and ' z ' with probability pz / 100 : Assumption : px + py + pz = 100 where px , py and pz lie between 0 to 100 ; Generate a number from 1 to 100 ; r is smaller than px with probability px / 100 ; r is greater than px and smaller than or equal to px + py with probability py / 100 ; r is greater than px + py and smaller than or equal to 100 with probability pz / 100
int random ( int x , int y , int z , int px , int py , int pz ) { int r = rand ( 1 , 100 ) ; if ( r <= px ) return x ; if ( r <= ( px + py ) ) return y ; else return z ; }
Calculate the angle between hour hand and minute hand | C program to find angle between hour and minute hands ; Utility function to find minimum of two integers ; Function to calculate the angle ; validate the input ; Calculate the angles moved by hour and minute hands with reference to 12 : 00 ; Find the difference between two angles ; Return the smaller angle of two possible angles ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int min ( int x , int y ) { return ( x < y ) ? x : y ; } int calcAngle ( double h , double m ) { if ( h < 0 m < 0 h > 12 m > 60 ) printf ( " Wrong ▁ input " ) ; if ( h == 12 ) h = 0 ; if ( m == 60 ) { m = 0 ; h += 1 ; if ( h > 12 ) h = h - 12 ; } int hour_angle = 0.5 * ( h * 60 + m ) ; int minute_angle = 6 * m ; int angle = abs ( hour_angle - minute_angle ) ; angle = min ( 360 - angle , angle ) ; return angle ; } int main ( ) { printf ( " % d ▁ n " , calcAngle ( 9 , 60 ) ) ; printf ( " % d ▁ n " , calcAngle ( 3 , 30 ) ) ; return 0 ; }
Find the element that appears once | C program to find the element that occur only once ; Method to find the element that occur only once ; The expression " one ▁ & ▁ arr [ i ] " gives the bits that are there in both ' ones ' and new element from arr [ ] . We add these bits to ' twos ' using bitwise OR Value of ' twos ' will be set as 0 , 3 , 3 and 1 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; XOR the new bits with previous ' ones ' to get all bits appearing odd number of times Value of ' ones ' will be set as 3 , 0 , 2 and 3 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; The common bits are those bits which appear third time So these bits should not be there in both ' ones ' and ' twos ' . common_bit_mask contains all these bits as 0 , so that the bits can be removed from ' ones ' and ' twos ' Value of ' common _ bit _ mask ' will be set as 00 , 00 , 01 and 10 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; Remove common bits ( the bits that appear third time ) from ' ones ' Value of ' ones ' will be set as 3 , 0 , 0 and 2 after 1 st , 2 nd , 3 rd and 4 th iterations respectively ; Remove common bits ( the bits that appear third time ) from ' twos ' Value of ' twos ' will be set as 0 , 3 , 1 and 0 after 1 st , 2 nd , 3 rd and 4 th itearations respectively ; Driver Code
#include <stdio.h> NEW_LINE int getSingle ( int arr [ ] , int n ) { int ones = 0 , twos = 0 ; int common_bit_mask ; for ( int i = 0 ; i < n ; i ++ ) { twos = twos | ( ones & arr [ i ] ) ; ones = ones ^ arr [ i ] ; common_bit_mask = ~ ( ones & twos ) ; ones &= common_bit_mask ; twos &= common_bit_mask ; } return ones ; } int main ( ) { int arr [ ] = { 3 , 3 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " The ▁ element ▁ with ▁ single ▁ occurrence ▁ is ▁ % d ▁ " , getSingle ( arr , n ) ) ; return 0 ; }
Find the element that appears once | C program to find the element that occur only once ; Initialize result ; Iterate through every bit ; Find sum of set bits at ith position in all array elements ; The bits with sum not multiple of 3 , are the bits of element with single occurrence . ; Driver program to test above function
#include <stdio.h> NEW_LINE #define INT_SIZE 32 NEW_LINE int getSingle ( int arr [ ] , int n ) { int result = 0 ; int x , sum ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) { sum = 0 ; x = ( 1 << i ) ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ j ] & x ) sum ++ ; } if ( ( sum % 3 ) != 0 ) result |= x ; } return result ; } int main ( ) { int arr [ ] = { 12 , 1 , 12 , 3 , 12 , 1 , 1 , 2 , 3 , 2 , 2 , 3 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " The ▁ element ▁ with ▁ single ▁ occurrence ▁ is ▁ % d ▁ " , getSingle ( arr , n ) ) ; return 0 ; }
Count total set bits in all numbers from 1 to n | A O ( Logn ) complexity program to count set bits in all numbers from 1 to n ; Returns position of leftmost set bit . The rightmost position is considered as 0 ; Given the position of previous leftmost set bit in n ( or an upper bound on leftmost position ) returns the new position of leftmost set bit in n ; The main recursive function used by countSetBits ( ) ; Get the position of leftmost set bit in n . This will be used as an upper bound for next set bit function ; Use the position ; Base Case : if n is 0 , then set bit count is 0 ; get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 , i . e . , if n is like 1 , 3 , 7 , 15 , 31 , . . etc , then we are done . Since positions are considered starting from 0 , 1 is added to m ; update n for next recursive call ; Driver program to test above functions
#include <stdio.h> NEW_LINE unsigned int getLeftmostBit ( int n ) { int m = 0 ; while ( n > 1 ) { n = n >> 1 ; m ++ ; } return m ; } unsigned int getNextLeftmostBit ( int n , int m ) { unsigned int temp = 1 << m ; while ( n < temp ) { temp = temp >> 1 ; m -- ; } return m ; } unsigned int _countSetBits ( unsigned int n , int m ) ; unsigned int countSetBits ( unsigned int n ) { int m = getLeftmostBit ( n ) ; return _countSetBits ( n , m ) ; } unsigned int _countSetBits ( unsigned int n , int m ) { if ( n == 0 ) return 0 ; m = getNextLeftmostBit ( n , m ) ; if ( n == ( ( unsigned int ) 1 << ( m + 1 ) ) - 1 ) return ( unsigned int ) ( m + 1 ) * ( 1 << m ) ; n = n - ( 1 << m ) ; return ( n + 1 ) + countSetBits ( n ) + m * ( 1 << ( m - 1 ) ) ; } int main ( ) { int n = 17 ; printf ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ % d " , countSetBits ( n ) ) ; return 0 ; }
Swap bits in a given number | C Program to swap bits in a given number ; Move all bits of first set to rightmost side ; Move all bits of second set to rightmost side ; XOR the two sets ; Put the xor bits back to their original positions ; XOR the ' xor ' with the original number so that the two sets are swapped ; Driver program to test above function
#include <stdio.h> NEW_LINE int swapBits ( unsigned int x , unsigned int p1 , unsigned int p2 , unsigned int n ) { unsigned int set1 = ( x >> p1 ) & ( ( 1U << n ) - 1 ) ; unsigned int set2 = ( x >> p2 ) & ( ( 1U << n ) - 1 ) ; unsigned int xor = ( set1 ^ set2 ) ; xor = ( xor << p1 ) | ( xor << p2 ) ; unsigned int result = x ^ xor ; return result ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 , 2 ) ; printf ( " Result = % d " , res ) ; return 0 ; }
Smallest of three integers without comparison operators | C program to find Smallest of three integers without comparison operators ; Driver code
#include <stdio.h> NEW_LINE int smallest ( int x , int y , int z ) { int c = 0 ; while ( x && y && z ) { x -- ; y -- ; z -- ; c ++ ; } return c ; } int main ( ) { int x = 12 , y = 15 , z = 5 ; printf ( " Minimum ▁ of ▁ 3 ▁ numbers ▁ is ▁ % d " , smallest ( x , y , z ) ) ; return 0 ; }
Smallest of three integers without comparison operators | C implementation of above approach ; Function to find minimum of x and y ; Function to find minimum of 3 numbers x , y and z ; Driver code
#include <stdio.h> NEW_LINE #define CHAR_BIT 8 NEW_LINE int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int smallest ( int x , int y , int z ) { return min ( x , min ( y , z ) ) ; } int main ( ) { int x = 12 , y = 15 , z = 5 ; printf ( " Minimum ▁ of ▁ 3 ▁ numbers ▁ is ▁ % d " , smallest ( x , y , z ) ) ; return 0 ; }
Smallest of three integers without comparison operators | ; Using division operator to find minimum of three numbers ; Same as " if ▁ ( y ▁ < ▁ x ) " ; Driver code
#include <stdio.h> NEW_LINE int smallest ( int x , int y , int z ) { if ( ! ( y / x ) ) return ( ! ( y / z ) ) ? y : z ; return ( ! ( x / z ) ) ? x : z ; } int main ( ) { int x = 78 , y = 88 , z = 68 ; printf ( " Minimum ▁ of ▁ 3 ▁ numbers ▁ is ▁ % d " , smallest ( x , y , z ) ) ; return 0 ; }
A Boolean Array Puzzle | ; Driver code
void changeToZero ( int a [ 2 ] ) { a [ a [ 1 ] ] = a [ ! a [ 1 ] ] ; } int main ( ) { int a [ ] = { 1 , 0 } ; changeToZero ( a ) ; printf ( " ▁ arr [ 0 ] ▁ = ▁ % d ▁ STRNEWLINE " , a [ 0 ] ) ; printf ( " ▁ arr [ 1 ] ▁ = ▁ % d ▁ " , a [ 1 ] ) ; getchar ( ) ; return 0 ; }
Program to count number of set bits in an ( big ) array | ; Size of array 64 K ; GROUP_A - When combined with META_LOOK_UP generates count for 4 x4 elements ; GROUP_B - When combined with META_LOOK_UP generates count for 4 x4x4 elements ; GROUP_C - When combined with META_LOOK_UP generates count for 4 x4x4x4 elements ; Provide appropriate letter to generate the table ; A static table will be much faster to access ; No shifting funda ( for better readability ) ; It is fine , bypass the type system ; Count set bits in individual bytes ; Driver program , generates table of random 64 K numbers ; Seed to the random - number generator ; Generate random numbers .
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE #include <time.h> NEW_LINE #define SIZE (1 << 16) NEW_LINE #define GROUP_A ( x ) x, x + 1, x + 1, x + 2 NEW_LINE #define GROUP_B ( x ) GROUP_A(x), GROUP_A(x+1), GROUP_A(x+1), GROUP_A(x+2) NEW_LINE #define GROUP_C ( x ) GROUP_B(x), GROUP_B(x+1), GROUP_B(x+1), GROUP_B(x+2) NEW_LINE #define META_LOOK_UP ( PARAMETER ) \NEW_LINE GROUP_##PARAMETER(0), \NEW_LINE GROUP_##PARAMETER(1), \NEW_LINE GROUP_##PARAMETER(1), \NEW_LINE GROUP_##PARAMETER(2) \NEW_LINEint countSetBits(int array[], size_t array_size) NEW_LINE { int count = 0 ; static unsigned char const look_up [ ] = { META_LOOK_UP ( C ) } ; unsigned char * pData = NULL ; for ( size_t index = 0 ; index < array_size ; index ++ ) { pData = ( unsigned char * ) & array [ index ] ; count += look_up [ pData [ 0 ] ] ; count += look_up [ pData [ 1 ] ] ; count += look_up [ pData [ 2 ] ] ; count += look_up [ pData [ 3 ] ] ; } return count ; } int main ( ) { int index ; int random [ SIZE ] ; srand ( ( unsigned ) time ( 0 ) ) ; for ( index = 0 ; index < SIZE ; index ++ ) { random [ index ] = rand ( ) ; } printf ( " Total ▁ number ▁ of ▁ bits ▁ = ▁ % d STRNEWLINE " , countSetBits ( random , SIZE ) ) ; return 0 ; }
Add 1 to a given number | C ++ code to add add one to a given number ; Flip all the set bits until we find a 0 ; flip the rightmost 0 bit ; Driver program to test above functions
#include <stdio.h> NEW_LINE int addOne ( int x ) { int m = 1 ; while ( x & m ) { x = x ^ m ; m <<= 1 ; } x = x ^ m ; return x ; } int main ( ) { printf ( " % d " , addOne ( 13 ) ) ; getchar ( ) ; return 0 ; }
Add 1 to a given number | ; Driver program to test above functions
#include <stdio.h> NEW_LINE int addOne ( int x ) { return ( - ( ~ x ) ) ; } int main ( ) { printf ( " % d " , addOne ( 13 ) ) ; getchar ( ) ; return 0 ; }
Turn off the rightmost set bit | ; unsets the rightmost set bit of n and returns the result ; Driver Code
#include <stdio.h> NEW_LINE int fun ( unsigned int n ) { return n & ( n - 1 ) ; } int main ( ) { int n = 7 ; printf ( " The ▁ number ▁ after ▁ unsetting ▁ the " ) ; printf ( " ▁ rightmost ▁ set ▁ bit ▁ % d " , fun ( n ) ) ; return 0 ; }
Find whether a given number is a power of 4 or not | ; Function to check if x is power of 4 ; Driver program to test above function
#include <stdio.h> NEW_LINE #define bool int NEW_LINE bool isPowerOfFour ( int n ) { if ( n == 0 ) return 0 ; while ( n != 1 ) { if ( n % 4 != 0 ) return 0 ; n = n / 4 ; } return 1 ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) printf ( " % d ▁ is ▁ a ▁ power ▁ of ▁ 4" , test_no ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" , test_no ) ; getchar ( ) ; }
Find whether a given number is a power of 4 or not | ; Function to check if x is power of 4 ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is even then return true else false ; If there are more than 1 bit set then n is not a power of 4 ; Driver program to test above function
#include <stdio.h> NEW_LINE #define bool int NEW_LINE bool isPowerOfFour ( unsigned int n ) { int count = 0 ; if ( n && ! ( n & ( n - 1 ) ) ) { while ( n > 1 ) { n >>= 1 ; count += 1 ; } return ( count % 2 == 0 ) ? 1 : 0 ; } return 0 ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) printf ( " % d ▁ is ▁ a ▁ power ▁ of ▁ 4" , test_no ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" , test_no ) ; getchar ( ) ; }
Find whether a given number is a power of 4 or not | C program to check if given number is power of 4 or not ; Driver program to test above function
#include <stdio.h> NEW_LINE #define bool int NEW_LINE bool isPowerOfFour ( unsigned int n ) { return n != 0 && ( ( n & ( n - 1 ) ) == 0 ) && ! ( n & 0xAAAAAAAA ) ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) printf ( " % d ▁ is ▁ a ▁ power ▁ of ▁ 4" , test_no ) ; else printf ( " % d ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" , test_no ) ; getchar ( ) ; }
Compute the minimum or maximum of two integers without branching | C program to Compute the minimum or maximum of two integers without branching ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions
#include <stdio.h> NEW_LINE int min ( int x , int y ) { return y ^ ( ( x ^ y ) & - ( x < y ) ) ; } int max ( int x , int y ) { return x ^ ( ( x ^ y ) & - ( x < y ) ) ; } int main ( ) { int x = 15 ; int y = 6 ; printf ( " Minimum ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ " , x , y ) ; printf ( " % d " , min ( x , y ) ) ; printf ( " Maximum of % d and % d is " printf ( " % d " , max ( x , y ) ) ; getchar ( ) ; }
Compute the minimum or maximum of two integers without branching | ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions
#include <stdio.h> NEW_LINE #define CHAR_BIT 8 NEW_LINE int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int max ( int x , int y ) { return x - ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int main ( ) { int x = 15 ; int y = 6 ; printf ( " Minimum ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ " , x , y ) ; printf ( " % d " , min ( x , y ) ) ; printf ( " Maximum of % d and % d is " printf ( " % d " , max ( x , y ) ) ; getchar ( ) ; }
Check for Integer Overflow | ; Takes pointer to result and two numbers as arguments . If there is no overflow , the function places the resultant = sum a + b in result and returns 0 , otherwise it returns - 1 ; Driver code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int addOvf ( int * result , int a , int b ) { * result = a + b ; if ( a > 0 && b > 0 && * result < 0 ) return -1 ; if ( a < 0 && b < 0 && * result > 0 ) return -1 ; return 0 ; } int main ( ) { int * res = ( int * ) malloc ( sizeof ( int ) ) ; int x = 2147483640 ; int y = 10 ; printf ( " % d " , addOvf ( res , x , y ) ) ; printf ( " % d " , * res ) ; getchar ( ) ; return 0 ; }
Check for Integer Overflow |
#include <stdio.h> NEW_LINE #include <limits.h> NEW_LINE #include <stdlib.h> NEW_LINE int addOvf ( int * result , int a , int b ) { if ( a > INT_MAX - b ) return -1 ; else { * result = a + b ; return 0 ; } } int main ( ) { int * res = ( int * ) malloc ( sizeof ( int ) ) ; int x = 2147483640 ; int y = 10 ; printf ( " % d " , addOvf ( res , x , y ) ) ; printf ( " % d " , * res ) ; getchar ( ) ; return 0 ; }
Little and Big Endian Mystery |
#include <stdio.h> NEW_LINE int main ( ) { unsigned int i = 1 ; char * c = ( char * ) & i ; if ( * c ) printf ( " Little ▁ endian " ) ; else printf ( " Big ▁ endian " ) ; getchar ( ) ; return 0 ; }
Position of rightmost set bit | C program for Position of rightmost set bit ; Driver code
#include <math.h> NEW_LINE #include <stdio.h> NEW_LINE unsigned int getFirstSetBitPos ( int n ) { return log2 ( n & - n ) + 1 ; } int main ( ) { int n = 12 ; printf ( " % u " , getFirstSetBitPos ( n ) ) ; getchar ( ) ; return 0 ; }
Binary representation of a given number | ; bin function ; Driver Code
#include <stdio.h> NEW_LINE void bin ( unsigned n ) { unsigned i ; for ( i = 1 << 31 ; i > 0 ; i = i / 2 ) ( n & i ) ? printf ( "1" ) : printf ( "0" ) ; } int main ( void ) { bin ( 7 ) ; printf ( " STRNEWLINE " ) ; bin ( 4 ) ; }
Swap all odd and even bits | C program to swap even and odd bits of a given number ; Function to swap even and odd bits ; Get all even bits of x ; Get all odd bits of x ; Right shift even bits ; Left shift odd bits ; Combine even and odd bits ; Driver program to test above function ; 00010111 ; Output is 43 ( 00101011 )
#include <stdio.h> NEW_LINE unsigned int swapBits ( unsigned int x ) { unsigned int even_bits = x & 0xAAAAAAAA ; unsigned int odd_bits = x & 0x55555555 ; even_bits >>= 1 ; odd_bits <<= 1 ; return ( even_bits odd_bits ) ; } int main ( ) { unsigned int x = 23 ; printf ( " % u ▁ " , swapBits ( x ) ) ; return 0 ; }
Find position of the only set bit | C program to find position of only set bit in a given number ; A utility function to check whether n is a power of 2 or not . goo . gl / 17 Arj See http : ; Returns position of the only set bit in ' n ' ; Iterate through bits of n till we find a set bit i & n will be non - zero only when ' i ' and ' n ' have a set bit at same position ; Unset current bit and set the next bit in ' i ' ; increment position ; Driver program to test above function
#include <stdio.h> NEW_LINE int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned i = 1 , pos = 1 ; while ( ! ( i & n ) ) { i = i << 1 ; ++ pos ; } return pos ; } int main ( void ) { int n = 16 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; return 0 ; }
Find position of the only set bit | C program to find position of only set bit in a given number ; A utility function to check whether n is power of 2 or not ; Returns position of the only set bit in ' n ' ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; Driver program to test above function
#include <stdio.h> NEW_LINE int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned count = 0 ; while ( n ) { n = n >> 1 ; ++ count ; } return count ; } int main ( void ) { int n = 0 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number STRNEWLINE " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ STRNEWLINE " , n , pos ) ; return 0 ; }
How to swap two numbers without using a temporary variable ? | C Program to swap two numbers without using temporary variable ; Code to swap ' x ' and ' y ' x now becomes 50 ; y becomes 10 ; x becomes 5
#include <stdio.h> NEW_LINE int main ( ) { int x = 10 , y = 5 ; x = x * y ; y = x / y ; x = x / y ; printf ( " After ▁ Swapping : ▁ x ▁ = ▁ % d , ▁ y ▁ = ▁ % d " , x , y ) ; return 0 ; }
How to swap two numbers without using a temporary variable ? | C code to swap using XOR ; Code to swap ' x ' ( 1010 ) and ' y ' ( 0101 ) x now becomes 15 ( 1111 ) ; y becomes 10 ( 1010 ) ; x becomes 5 ( 0101 )
#include <stdio.h> NEW_LINE int main ( ) { int x = 10 , y = 5 ; x = x ^ y ; y = x ^ y ; x = x ^ y ; printf ( " After ▁ Swapping : ▁ x ▁ = ▁ % d , ▁ y ▁ = ▁ % d " , x , y ) ; return 0 ; }
How to swap two numbers without using a temporary variable ? | C program to implement the above approach ; Swap function ; Driver code
#include <stdio.h> NEW_LINE void swap ( int * xp , int * yp ) { * xp = * xp ^ * yp ; * yp = * xp ^ * yp ; * xp = * xp ^ * yp ; } int main ( ) { int x = 10 ; swap ( & x , & x ) ; printf ( " After ▁ swap ( & x , ▁ & x ) : ▁ x ▁ = ▁ % d " , x ) ; return 0 ; }
Replace every element with the greatest element on right side | C Program to replace every element with the greatest element on right side ; Function to replace every element with the next greatest element ; Initialize the next greatest element ; The next greatest element for the rightmost element is always - 1 ; Replace all other elements with the next greatest ; Store the current element ( needed later for updating the next greatest element ) ; Replace current element with the next greatest ; Update the greatest element , if needed ; A utility Function that prints an array ; Driver program to test above function
#include <stdio.h> NEW_LINE void nextGreatest ( int arr [ ] , int size ) { int max_from_right = arr [ size - 1 ] ; arr [ size - 1 ] = -1 ; for ( int i = size - 2 ; i >= 0 ; i -- ) { int temp = arr [ i ] ; arr [ i ] = max_from_right ; if ( max_from_right < temp ) max_from_right = temp ; } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 16 , 17 , 4 , 3 , 5 , 2 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nextGreatest ( arr , size ) ; printf ( " The ▁ modified ▁ array ▁ is : ▁ STRNEWLINE " ) ; printArray ( arr , size ) ; return ( 0 ) ; }
Maximum difference between two elements such that larger element appears after the smaller number | ; The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order . Returns 0 if elements are equal ; Driver program to test above function ; Function calling
#include <stdio.h> NEW_LINE int maxDiff ( int arr [ ] , int arr_size ) { int max_diff = arr [ 1 ] - arr [ 0 ] ; int i , j ; for ( i = 0 ; i < arr_size ; i ++ ) { for ( j = i + 1 ; j < arr_size ; j ++ ) { if ( arr [ j ] - arr [ i ] > max_diff ) max_diff = arr [ j ] - arr [ i ] ; } } return max_diff ; } int main ( ) { int arr [ ] = { 1 , 2 , 90 , 10 , 110 } ; printf ( " Maximum ▁ difference ▁ is ▁ % d " , maxDiff ( arr , 5 ) ) ; getchar ( ) ; return 0 ; }
Find the maximum element in an array which is first increasing and then decreasing | C program to find maximum element ; function to find the maximum element ; Driver program to check above functions
#include <stdio.h> NEW_LINE int findMaximum ( int arr [ ] , int low , int high ) { int max = arr [ low ] ; int i ; for ( i = low + 1 ; i <= high ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; else break ; } return max ; } int main ( ) { int arr [ ] = { 1 , 30 , 40 , 50 , 60 , 70 , 23 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " The ▁ maximum ▁ element ▁ is ▁ % d " , findMaximum ( arr , 0 , n - 1 ) ) ; getchar ( ) ; return 0 ; }
Find the maximum element in an array which is first increasing and then decreasing | ; Base Case : Only one element is present in arr [ low . . high ] ; If there are two elements and first is greater then the first element is maximum ; If there are two elements and second is greater then the second element is maximum ; If we reach a point where arr [ mid ] is greater than both of its adjacent elements arr [ mid - 1 ] and arr [ mid + 1 ] , then arr [ mid ] is the maximum element ; If arr [ mid ] is greater than the next element and smaller than the previous element then maximum lies on left side of mid ; when arr [ mid ] is greater than arr [ mid - 1 ] and smaller than arr [ mid + 1 ] ; Driver program to check above functions
#include <stdio.h> NEW_LINE int findMaximum ( int arr [ ] , int low , int high ) { if ( low == high ) return arr [ low ] ; if ( ( high == low + 1 ) && arr [ low ] >= arr [ high ] ) return arr [ low ] ; if ( ( high == low + 1 ) && arr [ low ] < arr [ high ] ) return arr [ high ] ; int mid = ( low + high ) / 2 ; if ( arr [ mid ] > arr [ mid + 1 ] && arr [ mid ] > arr [ mid - 1 ] ) return arr [ mid ] ; if ( arr [ mid ] > arr [ mid + 1 ] && arr [ mid ] < arr [ mid - 1 ] ) return findMaximum ( arr , low , mid - 1 ) ; else return findMaximum ( arr , mid + 1 , high ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 50 , 10 , 9 , 7 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " The ▁ maximum ▁ element ▁ is ▁ % d " , findMaximum ( arr , 0 , n - 1 ) ) ; getchar ( ) ; return 0 ; }
Count smaller elements on right side | ; initialize all the counts in countSmaller array as 0 ; Utility function that prints out an array on a line ; Driver program to test above functions
void constructLowerArray ( int * arr [ ] , int * countSmaller , int n ) { int i , j ; for ( i = 0 ; i < n ; i ++ ) countSmaller [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] < arr [ i ] ) countSmaller [ i ] ++ ; } } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 12 , 10 , 5 , 4 , 2 , 20 , 6 , 1 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * low = ( int * ) malloc ( sizeof ( int ) * n ) ; constructLowerArray ( arr , low , n ) ; printArray ( low , n ) ; return 0 ; }
Count smaller elements on right side | ; An AVL tree node ; size of the tree rooted with this node ; A utility function to get maximum of two integers ; A utility function to get height of the tree rooted with N ; A utility function to size of the tree of rooted with N ; A utility function to get maximum of two integers ; Helper function that allocates a new node with the given key and NULL left and right pointers . ; new node is initially added at leaf ; A utility function to right rotate subtree rooted with y ; Perform rotation ; Update heights ; Update sizes ; Return new root ; A utility function to left rotate subtree rooted with x ; Perform rotation ; Update heights ; Update sizes ; Return new root ; Get Balance factor of node N ; Inserts a new key to the tree rotted with node . Also , updates * count to contain count of smaller elements for the new key ; 1. Perform the normal BST rotation ; UPDATE COUNT OF SMALLER ELEMENTS FOR KEY ; 2. Update height and size of this ancestor node ; 3. Get the balance factor of this ancestor node to check whether this node became unbalanced ; Left Left Case ; Right Right Case ; Left Right Case ; Right Left Case ; return the ( unchanged ) node pointer ; The following function updates the countSmaller array to contain count of smaller elements on right side . ; initialize all the counts in countSmaller array as 0 ; Starting from rightmost element , insert all elements one by one in an AVL tree and get the count of smaller elements ; Utility function that prints out an array on a line ; Driver program to test above functions
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int key ; struct node * left ; struct node * right ; int height ; int size ; } ; int max ( int a , int b ) ; int height ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> height ; } int size ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> size ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } struct node * newNode ( int key ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> key = key ; node -> left = NULL ; node -> right = NULL ; node -> height = 1 ; node -> size = 1 ; return ( node ) ; } struct node * rightRotate ( struct node * y ) { struct node * x = y -> left ; struct node * T2 = x -> right ; x -> right = y ; y -> left = T2 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> size = size ( y -> left ) + size ( y -> right ) + 1 ; x -> size = size ( x -> left ) + size ( x -> right ) + 1 ; return x ; } struct node * leftRotate ( struct node * x ) { struct node * y = x -> right ; struct node * T2 = y -> left ; y -> left = x ; x -> right = T2 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> size = size ( x -> left ) + size ( x -> right ) + 1 ; y -> size = size ( y -> left ) + size ( y -> right ) + 1 ; return y ; } int getBalance ( struct node * N ) { if ( N == NULL ) return 0 ; return height ( N -> left ) - height ( N -> right ) ; } struct node * insert ( struct node * node , int key , int * count ) { if ( node == NULL ) return ( newNode ( key ) ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key , count ) ; else { node -> right = insert ( node -> right , key , count ) ; * count = * count + size ( node -> left ) + 1 ; } node -> height = max ( height ( node -> left ) , height ( node -> right ) ) + 1 ; node -> size = size ( node -> left ) + size ( node -> right ) + 1 ; int balance = getBalance ( node ) ; if ( balance > 1 && key < node -> left -> key ) return rightRotate ( node ) ; if ( balance < -1 && key > node -> right -> key ) return leftRotate ( node ) ; if ( balance > 1 && key > node -> left -> key ) { node -> left = leftRotate ( node -> left ) ; return rightRotate ( node ) ; } if ( balance < -1 && key < node -> right -> key ) { node -> right = rightRotate ( node -> right ) ; return leftRotate ( node ) ; } return node ; } void constructLowerArray ( int arr [ ] , int countSmaller [ ] , int n ) { int i , j ; struct node * root = NULL ; for ( i = 0 ; i < n ; i ++ ) countSmaller [ i ] = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { root = insert ( root , arr [ i ] , & countSmaller [ i ] ) ; } } void printArray ( int arr [ ] , int size ) { int i ; printf ( " STRNEWLINE " ) ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 10 , 6 , 15 , 20 , 30 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * low = ( int * ) malloc ( sizeof ( int ) * n ) ; constructLowerArray ( arr , low , n ) ; printf ( " Following ▁ is ▁ the ▁ constructed ▁ smaller ▁ count ▁ array " ) ; printArray ( low , n ) ; return 0 ; }