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
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
#define SIZE  50
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 *...


Little and Big Endian Mystery |
How can the above be solved in C?

 #include <stdio.h>
int main ( ) { unsigned int i = 1 ; char * c = ( char * ) & i ; if ( * c ) printf ( " Little ▁ endian " ) ; else printf ( " Big ▁ endian " ) ; getchar ( ) ; return 0 ; }


Logarithm tricks for Competitive Programming | C implementation count the number of digits in a number ; Function to count the number of digits in a number ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
int countDigit ( long long n ) { return ( floor ( log10 ( n ) + 1 ) ) ; } int main ( ) { double N = 80 ; printf ( " % d " , countDigit ( N ) ) ; return 0 ; }


Logarithm tricks for Competitive Programming | C implementation to check if the number is power of K ; Function to check if the number is power of K ; Logarithm function to calculate value ; Compare to the result1 or result2 both are equal ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
_Bool isPower ( int N , int K ) { int res1 = log ( N ) / log ( K ) ; double res2 = log ( N ) / log ( K ) ; return ( res1 == res2 ) ; } int main ( ) { int N = 8 ; int K = 2 ; if ( isPower ( N , K ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } return 0 ; }


Logarithm tricks for Competitive Programming | C implementation to check that a integer is a power of Two ; Function to check if the number is a power of two ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
_Bool isPowerOfTwo ( int n ) { return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } int main ( ) { int N = 8 ; if ( isPowerOfTwo ( N ) ) { printf ( " Yes " ) ; } else { printf ( " No " ) ; } }


Logarithm tricks for Competitive Programming | C implementation to find the previous and next power of K ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
int prevPowerofK ( int n , int k ) { int p = ( int ) ( log ( n ) / log ( k ) ) ; return ( int ) pow ( k , p ) ; } int nextPowerOfK ( int n , int k ) { return prevPowerofK ( n , k ) * k ; } int main ( ) { int N = 7 ; int K = 2 ; printf ( " % d ▁ " , prevPowerofK ( N , K ) ) ; printf ( " % d
 " , nextPowerOfK ( N , K ) ) ; return 0 ; }


Logarithm | C program to find log ( n ) using Recursion ; Driver code
How can the above be solved in C?

 #include <stdio.h>
unsigned int Log2n ( unsigned int n ) { return ( n > 1 ) ? 1 + Log2n ( n / 2 ) : 0 ; } int main ( ) { unsigned int n = 32 ; printf ( " % u " , Log2n ( n ) ) ; getchar ( ) ; return 0 ; }


Longest Arithmetic Progression | DP | The function returns true if there exist three elements in AP Assumption : set [ 0. . n - 1 ] is sorted . The code strictly implements the algorithm provided in the reference . ; One by fix every element as middle element ; Initialize i and k for the current j ; Find if there exist i and k that form AP with j as middle element
How can the above be solved in C?

bool arithmeticThree ( int set [ ] , int n ) { for ( int j = 1 ; j < n - 1 ; j ++ ) { int i = j - 1 , k = j + 1 ; while ( i >= 0 && k <= n - 1 ) { if ( set [ i ] + set [ k ] == 2 * set [ j ] ) return true ; ( set [ i ] + set [ k ] < 2 * set [ j ] ) ? k ++ : i -- ; } } return false ; }


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
How can the above be solved in C?

 #include <bits/stdc++.h>
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
How can the above be solved in C?

 #include <bits/stdc++.h>
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 ; }


Longest Increasing Subsequence | DP | A Naive C recursive implementation of LIS problem ; stores the LIS ; To make use of recursive calls , thisfunction must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
let max_ref ; int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ lis ▁ is ▁ % d " , lis ( arr , n ) ) ; 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
How can the above be solved in C?

 #include <stdio.h>
#include <string.h>
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 ; }


Lowest Common Ancestor in a Binary Search Tree . | A recursive C program to find LCA of two nodes n1 and n2 . ; Function to find LCA of n1 and n2 . The function assumes that both n1 and n2 are present in BST ; If both n1 and n2 are smaller than root , then LCA lies in left ; If both n1 and n2 are greater than root , then LCA lies in right ; Helper function that allocates a new node with the given data . ; Driver program to test lca ( ) ; Let us construct the BST shown in the above figure
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left , * right ; } ; struct node * lca ( struct node * root , int n1 , int n2 ) { while ( root != NULL ) { if ( root -> data > n1 && root -> data > n2 ) root = root -> left ; else if ( root -> data < n1 && root -> data < n2 ) root = root -> right ; else break ; } return root ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 22 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; int n1 = 10 , n2 = 14 ; struct node * t = lca ( root , n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁
 " , n1 , n2 , t -> data ) ; n1 = 14 , n2 = 8 ; t = lca ( root , n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁
 " , n1 , n2 , t -> data ) ; n1 = 10 , n2 = 22 ; t = lca ( root , n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁
 " , n1 , n2 , t -> data ) ; getchar ( ) ; return 0 ; }


Lowest Common Ancestor in a Binary Tree | Set 2 ( Using Parent Pointer ) | C ++ program to find lowest common ancestor using parent pointer ; A Tree Node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in Binary Search Tree ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; return the ( unchanged ) node pointer ; To find LCA of nodes n1 and n2 in Binary Tree ; Creata a map to store ancestors of n1 ; Insert n1 and all its ancestors in map ; Check if n2 or any of its ancestors is in map . ; Driver method to test above functions
How can the above be solved in C?

 #include <bits/stdc++.h>
using namespace std ; struct Node { Node * left , * right , * parent ; int key ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> key = item ; temp -> parent = temp -> left = temp -> right = NULL ; return temp ; } Node * insert ( Node * node , int key ) { if ( node == NULL ) return newNode ( key ) ; if ( key < node -> key ) { node -> left = insert ( node -> left , key ) ; node -> left -> parent = node ; } else if ( key > node -> key ) { node -> right = insert ( node -> right , key ) ; node -> right -> parent = node ; } return node ; } Node * LCA ( Node * n1 , Node * n2 ) { map < Node * , bool > ancestors ; while ( n1 != NULL ) { ancestors [ n1 ] = true ; n1 = n1 -> parent ; } while ( n2 != NULL ) { if ( ancestors . find ( n2 ) != ancestors . end ( ) ) return n2 ; n2 = n2 -> parent ; } return NULL ; } int main ( void ) { Node * root = NULL ; root = insert ( root , 20 ) ; root = insert ( root , 8 ) ; root = insert ( root , 22 ) ; root = insert ( root , 4 ) ; root = insert ( root , 12 ) ; root = insert ( root , 10 ) ; root = insert ( root , 14 ) ; Node * n1 = root -> left -> right -> left ; Node * n2 = root -> left ; Node * lca = LCA ( n1 , n2 ) ; printf ( " LCA ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁
 " , n1 -> key , n2 -> key , lca -> key ) ; 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
How can the above be solved in C?

 #include <stdio.h>
#define bool  int
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 ( ) ; }


Lynch | C implementation for the above approach ; Function to check the divisibility of the number by its digit . ; If the digit divides the number then return true else return false . ; Function to check if all digits of n divide it or not ; Taking the digit of the number into digit var . ; Function to check if N has all distinct digits ; Create an array of size 10 and initialize all elements as false . This array is used to check if a digit is already seen or not . ; Traverse through all digits of given number ; Find the last digit ; If digit is already seen , return false ; Mark this digit as seen ; Remove the last digit from number ; Function to check Lynch - Bell numbers ; Driver Code ; Given number N ; Function call
How can the above be solved in C?

 #include <stdio.h>
int checkDivisibility ( int n , int digit ) { return ( digit != 0 && n % digit == 0 ) ; } int isAllDigitsDivide ( int n ) { int temp = n ; while ( temp > 0 ) { int digit = temp % 10 ; if ( ! ( checkDivisibility ( n , digit ) ) ) return 0 ; temp /= 10 ; } return 1 ; } int isAllDigitsDistinct ( int n ) { int arr [ 10 ] , i , digit ; for ( i = 0 ; i < 10 ; i ++ ) arr [ i ] = 0 ; while ( n > 0 ) { digit = n % 10 ; if ( arr [ digit ] ) return 0 ; arr [ digit ] = 1 ; n = n / 10 ; } return 1 ; } int isLynchBell ( int n ) { return isAllDigitsDivide ( n ) && isAllDigitsDistinct ( n ) ; } int main ( ) { int N = 12 ; if ( isLynchBell ( N ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }


MSD ( Most Significant Digit ) Radix Sort | C program for the implementation of MSD Radix Sort using counting sort ( ) ; A utility function to print an array ; A utility function to get the digit at index d in a integer ; function to sort array using MSD Radix Sort recursively ; recursion break condition ; temp is created to easily swap strings in arr [ ] ; Store occurrences of most significant character from each integer in count [ ] ; Change count [ ] so that count [ ] now contains actual position of this digits in temp [ ] ; Build the temp ; Copy all integer of temp to arr [ ] , so that arr [ ] now contains partially sorted integers ; Recursively MSD_sort ( ) on each partially sorted integers set to sort them by their next digit ; function find the largest integer ; Main function to call MSD_sort ; Find the maximum number to know number of digits ; get the length of the largest integer ; function call ; Driver Code ; Input array ; Size of the array ; Print the unsorted array ; Function Call ; Print the sorted array
How can the above be solved in C?

 #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print ( int * arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { printf ( " % d , ▁ " , arr [ i ] ) ; } printf ( "
 " ) ; } int digit_at ( int x , int d ) { return ( int ) ( x / pow ( 10 , d - 1 ) ) % 10 ; } void MSD_sort ( int * arr , int lo , int hi , int d ) { if ( hi <= lo d < 1 ) { return ; } int count [ 10 + 2 ] = { 0 } ; int temp [ n ] ; for ( int i = lo ; i <= hi ; i ++ ) { int c = digit_at ( arr [ i ] , d ) ; count ++ ; } for ( int r = 0 ; r < 10 + 1 ; r ++ ) count [ r + 1 ] += count [ r ] ; for ( int i = lo ; i <= hi ; i ++ ) { int c = digit_at ( arr [ i ] , d ) ; temp [ count ++ ] = arr [ i ] ; } for ( int i = lo ; i <= hi ; i ++ ) { arr [ i ] = temp [ i - lo ] ; } for ( int r = 0 ; r < 10 ; r ++ ) MSD_sort ( arr , lo + count [ r ] , lo + count [ r + 1 ] - 1 , d - 1 ) ; } int getMax ( int arr [ ] , int n ) { int mx = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > mx ) mx = arr [ i ] ; return mx ; } void radixsort ( int * arr , int n ) { int m = getMax ( arr , n ) ; int d = floor ( log10 ( abs ( m ) ) ) + 1 ; MSD_sort ( arr , 0 , n - 1 , d ) ; } int main ( ) { int arr [ ] = { 9330 , 9950 , 718 , 8977 , 6790 , 95 , 9807 , 741 , 8586 , 5710 } ; n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Unsorted ▁ array ▁ : ▁ " ) ; print ( arr , n ) ; radixsort ( arr , n ) ; printf ( " Sorted ▁ array ▁ : ▁ " ) ; print ( arr , n ) ; return 0 ; }


Make middle node head in a linked list | C program to make middle node as head of linked list . ; Link list node ; Function to get the middle and set at beginning of the linked list ; To traverse list nodes one by one ; To traverse list nodes by skipping one . ; To keep track of previous of middle ; for previous node of middle node ; move one node each time ; move two node each time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; A function to print a given linked list ; Driver function ; Create a list of 5 nodes
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * next ; } ; void setMiddleHead ( struct Node * * head ) { if ( * head == NULL ) return ; struct Node * one_node = ( * head ) ; struct Node * two_node = ( * head ) ; struct Node * prev = NULL ; while ( two_node != NULL && two_node -> next != NULL ) { prev = one_node ; two_node = two_node -> next -> next ; one_node = one_node -> next ; } prev -> next = prev -> next -> next ; one_node -> next = ( * head ) ; ( * head ) = one_node ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * ptr ) { while ( ptr != NULL ) { printf ( " % d ▁ " , ptr -> data ) ; ptr = ptr -> next ; } printf ( "
 " ) ; } int main ( ) { struct Node * head = NULL ; int i ; for ( i = 5 ; i > 0 ; i -- ) push ( & head , i ) ; printf ( " ▁ list ▁ before : ▁ " ) ; printList ( head ) ; setMiddleHead ( & head ) ; printf ( " ▁ list ▁ After : ▁ " ) ; printList ( head ) ; return 0 ; }


Maximum Bitwise AND pair ( X , Y ) from given range such that X and Y can be same | C implementation to find the Maximum Bitwise AND pair ( X , Y ) from given range such that X and Y can be same ; Function to return the maximum bitwise AND ; Driver code
How can the above be solved in C?

 #include <stdio.h>
int maximumAND ( int L , int R ) { return R ; } int main ( ) { int l = 3 ; int r = 7 ; printf ( " % d " , maximumAND ( l , r ) ) ; return 0 ; }


Maximum Length Chain of Pairs | DP |  ; This function assumes that arr [ ] is sorted in increasing order according the first ( or smaller ) values in pairs . ; Initialize MCL ( max chain length ) values for all indexes ; Compute optimized chain length values in bottom up manner ; Pick maximum of all MCL values ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct pair { int a ; int b ; } ; int maxChainLength ( struct pair arr [ ] , int n ) { int i , j , max = 0 ; int * mcl = ( int * ) malloc ( sizeof ( int ) * n ) ; for ( i = 0 ; i < n ; i ++ ) mcl [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] . a > arr [ j ] . b && mcl [ i ] < mcl [ j ] + 1 ) mcl [ i ] = mcl [ j ] + 1 ; for ( i = 0 ; i < n ; i ++ ) if ( max < mcl [ i ] ) max = mcl [ i ] ; free ( mcl ) ; return max ; } int main ( ) { struct pair arr [ ] = { { 5 , 24 } , { 15 , 25 } , { 27 , 40 } , { 50 , 60 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length ▁ of ▁ maximum ▁ size ▁ chain ▁ is ▁ % d
 " , maxChainLength ( arr , n ) ) ; return 0 ; }


Maximum Sum Increasing Subsequence | DP | Dynamic Programming implementation of Maximum Sum Increasing Subsequence ( MSIS ) problem ; maxSumIS ( ) returns the maximum sum of increasing subsequence in arr [ ] of size n ; Initialize msis values for all indexes ; Compute maximum sum values in bottom up manner ; Pick maximum of all msis values ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
int maxSumIS ( int arr [ ] , int n ) { int i , j , max = 0 ; int msis [ n ] ; for ( i = 0 ; i < n ; i ++ ) msis [ i ] = arr [ i ] ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && msis [ i ] < msis [ j ] + arr [ i ] ) msis [ i ] = msis [ j ] + arr [ i ] ; for ( i = 0 ; i < n ; i ++ ) if ( max < msis [ i ] ) max = msis [ i ] ; return max ; } int main ( ) { int arr [ ] = { 1 , 101 , 2 , 3 , 100 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Sum ▁ of ▁ maximum ▁ sum ▁ increasing ▁ " " subsequence ▁ is ▁ % d
 " , maxSumIS ( arr , n ) ) ; return 0 ; }


Maximum and minimum of an array using minimum number of comparisons |  ; structure is used to return two values from minMax ( ) ; If array has even number of elements then initialize the first two elements as minimum and maximum ; set the starting index for loop ; If array has odd number of elements then initialize the first element as minimum and maximum ; set the starting index for loop ; In the while loop , pick elements in pair and compare the pair with max and min so far ; Increment the index by 2 as two elements are processed in loop ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
struct pair { int min ; int max ; } ; struct pair getMinMax ( int arr [ ] , int n ) { struct pair minmax ; int i ; if ( n % 2 == 0 ) { if ( arr [ 0 ] > arr [ 1 ] ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 1 ] ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 1 ] ; } i = 2 ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 0 ] ; i = 1 ; } while ( i < n - 1 ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] > minmax . max ) minmax . max = arr [ i ] ; if ( arr [ i + 1 ] < minmax . min ) minmax . min = arr [ i + 1 ] ; } else { if ( arr [ i + 1 ] > minmax . max ) minmax . max = arr [ i + 1 ] ; if ( arr [ i ] < minmax . min ) minmax . min = arr [ i ] ; } i += 2 ; } return minmax ; } int main ( ) { int arr [ ] = { 1000 , 11 , 445 , 1 , 330 , 3000 } ; int arr_size = 6 ; struct pair minmax = getMinMax ( arr , arr_size ) ; printf ( " nMinimum ▁ element ▁ is ▁ % d " , minmax . min ) ; printf ( " nMaximum ▁ element ▁ is ▁ % d " , minmax . max ) ; getchar ( ) ; }


Maximum and minimum of an array using minimum number of comparisons | structure is used to return two values from minMax ( ) ; If there is only one element then return it as min and max both ; If there are more than one elements , then initialize min and max ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
struct pair { int min ; int max ; } ; struct pair getMinMax ( int arr [ ] , int n ) { struct pair minmax ; int i ; if ( n == 1 ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 0 ] ; return minmax ; } if ( arr [ 0 ] > arr [ 1 ] ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 1 ] ; } else { minmax . max = arr [ 1 ] ; minmax . min = arr [ 0 ] ; } for ( i = 2 ; i < n ; i ++ ) { if ( arr [ i ] > minmax . max ) minmax . max = arr [ i ] ; else if ( arr [ i ] < minmax . min ) minmax . min = arr [ i ] ; } return minmax ; } int main ( ) { int arr [ ] = { 1000 , 11 , 445 , 1 , 330 , 3000 } ; int arr_size = 6 ; struct pair minmax = getMinMax ( arr , arr_size ) ; printf ( " nMinimum ▁ element ▁ is ▁ % d " , minmax . min ) ; printf ( " nMaximum ▁ element ▁ is ▁ % d " , minmax . max ) ; getchar ( ) ; }


Maximum area of quadrilateral | CPP program to find maximum are of a quadrilateral ; Calculating the semi - perimeter of the given quadrilateral ; Applying Brahmagupta 's formula to  get maximum area of quadrilateral ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
double maxArea ( double a , double b , double c , double d ) { double semiperimeter = ( a + b + c + d ) / 2 ; return sqrt ( ( semiperimeter - a ) * ( semiperimeter - b ) * ( semiperimeter - c ) * ( semiperimeter - d ) ) ; } int main ( ) { double a = 1 , b = 2 , c = 1 , d = 2 ; printf ( " % .2f
 " , maxArea ( a , b , c , d ) ) ; 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
How can the above be solved in C?

 #include <stdio.h>
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 ; }


Maximum value of an integer for which factorial can be calculated on a machine | C program to find maximum value of an integer for which factorial can be calculated on your system ; when fact crosses its size , it gives negative value ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
int findMaxValue ( ) { int res = 2 ; long long int fact = 2 ; while ( 1 ) { if ( fact < 0 ) break ; res ++ ; fact = fact * res ; } return res - 1 ; } int main ( ) { printf ( " Maximum ▁ value ▁ of ▁ integer ▁ : ▁ % d
 " , findMaxValue ( ) ) ; return 0 ; }


Maximum width of a binary tree | C program to calculate width of binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; A utility function to get height of a binary tree ; Function to get the maximum width of a binary tree ; Create an array that will store count of nodes at each level ; Fill the count array using preorder traversal ; Return the maximum value from count array ; A function that fills count array with count of nodes at every level of given binary tree ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Return the maximum value from count array ; Driver program to test above functions ; Constructed bunary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; int height ( struct node * node ) ; struct node * newNode ( int data ) ; int getMax ( int arr [ ] , int n ) ; void getMaxWidthRecur ( struct node * root , int count [ ] , int level ) ; int getMaxWidth ( struct node * root ) { int width ; int h = height ( root ) ; int * count = ( int * ) calloc ( sizeof ( int ) , h ) ; int level = 0 ; getMaxWidthRecur ( root , count , level ) ; return getMax ( count , h ) ; } void getMaxWidthRecur ( struct node * root , int count [ ] , int level ) { if ( root ) { count [ level ] ++ ; getMaxWidthRecur ( root -> left , count , level + 1 ) ; getMaxWidthRecur ( root -> right , count , level + 1 ) ; } } int height ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lHeight = height ( node -> left ) ; int rHeight = height ( node -> right ) ; return ( lHeight > rHeight ) ? ( lHeight + 1 ) : ( rHeight + 1 ) ; } } 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 getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } return max ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; printf ( " Maximum ▁ width ▁ is ▁ % d ▁
 " , getMaxWidth ( root ) ) ; getchar ( ) ; return 0 ; }


Maximum width of a binary tree | C program to calculate width of binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function protoypes ; Function to get the maximum width of a binary tree ; Get width of each level and compare the width with maximum width so far ; Get width of a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; Constructed binary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 ; Function call
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; int getWidth ( struct node * root , int level ) ; int height ( struct node * node ) ; struct node * newNode ( int data ) ; int getMaxWidth ( struct node * root ) { int maxWidth = 0 ; int width ; int h = height ( root ) ; int i ; for ( i = 1 ; i <= h ; i ++ ) { width = getWidth ( root , i ) ; if ( width > maxWidth ) maxWidth = width ; } return maxWidth ; } int getWidth ( struct node * root , int level ) { if ( root == NULL ) return 0 ; if ( level == 1 ) return 1 ; else if ( level > 1 ) return getWidth ( root -> left , level - 1 ) + getWidth ( root -> right , level - 1 ) ; } int height ( struct node * node ) { if ( node == NULL ) return 0 ; else { int lHeight = height ( node -> left ) ; int rHeight = height ( node -> right ) ; return ( lHeight > rHeight ) ? ( lHeight + 1 ) : ( rHeight + 1 ) ; } } 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 ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> left = newNode ( 6 ) ; root -> right -> right -> right = newNode ( 7 ) ; printf ( " Maximum ▁ width ▁ is ▁ % d ▁
 " , getMaxWidth ( root ) ) ; getchar ( ) ; 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
How can the above be solved in C?

 #include <stdio.h>
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
How can the above be solved in C?

 #include <bits/stdc++.h>
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 ; }


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
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
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 ( "
 " ) ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Given ▁ array ▁ is ▁
 " ) ; printArray ( arr , arr_size ) ; mergeSort ( arr , 0 , arr_size - 1 ) ; printf ( " Sorted array is " printArray ( arr , arr_size ) ; return 0 ; }


Merge an array of size n into another array of size m + n | C program to Merge an array of size n into another array of size m + n ; Assuming - 1 is filled for the places where element is not available ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current index of N [ ] ; Current index of output mPlusN [ ] ; Take an element from mPlusN [ ] if a ) value of the picked element is smaller and we have not reached end of it b ) We have reached end of N [ ] ; Otherwise take element from N [ ] ; Utility that prints out an array on a line ; Driver code ; Initialize arrays ; Move the m elements at the end of mPlusN ; Merge N [ ] into mPlusN [ ] ; Print the resultant mPlusN
How can the above be solved in C?

 #include <stdio.h>
#define NA  -1
void moveToEnd ( int mPlusN [ ] , int size ) { int i = 0 , j = size - 1 ; for ( i = size - 1 ; i >= 0 ; i -- ) if ( mPlusN [ i ] != NA ) { mPlusN [ j ] = mPlusN [ i ] ; j -- ; } } int merge ( int mPlusN [ ] , int N [ ] , int m , int n ) { int i = n ; int j = 0 ; int k = 0 ; while ( k < ( m + n ) ) { if ( ( j == n ) || ( i < ( m + n ) && mPlusN [ i ] <= N [ j ] ) ) { mPlusN [ k ] = mPlusN [ i ] ; k ++ ; i ++ ; } else { mPlusN [ k ] = N [ j ] ; k ++ ; j ++ ; } } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( "
 " ) ; } int main ( ) { int mPlusN [ ] = { 2 , 8 , NA , NA , NA , 13 , NA , 15 , 20 } ; int N [ ] = { 5 , 7 , 9 , 25 } ; int n = sizeof ( N ) / sizeof ( N [ 0 ] ) ; int m = sizeof ( mPlusN ) / sizeof ( mPlusN [ 0 ] ) - n ; moveToEnd ( mPlusN , m + n ) ; merge ( mPlusN , N , m , n ) ; printArray ( mPlusN , m + n ) ; return 0 ; }


Merge two sorted linked lists |  ; point to the last result pointer ; tricky : advance to point to the next " . next " field
How can the above be solved in C?

struct Node * SortedMerge ( struct Node * a , struct Node * b ) { struct Node * result = NULL ; struct Node * * lastPtrRef = & result ; while ( 1 ) { if ( a == NULL ) { * lastPtrRef = b ; break ; } else if ( b == NULL ) { * lastPtrRef = a ; break ; } if ( a -> data <= b -> data ) { MoveNode ( lastPtrRef , & a ) ; } else { MoveNode ( lastPtrRef , & b ) ; } lastPtrRef = & ( ( * lastPtrRef ) -> next ) ; } return ( result ) ; }


Midpoint ellipse drawing algorithm | C program for implementing Mid - Point Ellipse Drawing Algorithm ; Initial decision parameter of region 1 ; For region 1 ; Print points based on 4 - way symmetry ; Checking and updating value of decision parameter based on algorithm ; Decision parameter of region 2 ; Plotting points of region 2 ; printing points based on 4 - way symmetry ; Checking and updating parameter value based on algorithm ; Driver code ; To draw a ellipse of major and minor radius 15 , 10 centred at ( 50 , 50 )
How can the above be solved in C?

 #include <stdio.h>
void midptellipse ( int rx , int ry , int xc , int yc ) { float dx , dy , d1 , d2 , x , y ; x = 0 ; y = ry ; d1 = ( ry * ry ) - ( rx * rx * ry ) + ( 0.25 * rx * rx ) ; dx = 2 * ry * ry * x ; dy = 2 * rx * rx * y ; while ( dx < dy ) { printf ( " ( % f , ▁ % f )
 " , x + xc , y + yc ) ; printf ( " ( % f , ▁ % f )
 " , - x + xc , y + yc ) ; printf ( " ( % f , ▁ % f )
 " , x + xc , - y + yc ) ; printf ( " ( % f , ▁ % f )
 " , - x + xc , - y + yc ) ; if ( d1 < 0 ) { x ++ ; dx = dx + ( 2 * ry * ry ) ; d1 = d1 + dx + ( ry * ry ) ; } else { x ++ ; y -- ; dx = dx + ( 2 * ry * ry ) ; dy = dy - ( 2 * rx * rx ) ; d1 = d1 + dx - dy + ( ry * ry ) ; } } d2 = ( ( ry * ry ) * ( ( x + 0.5 ) * ( x + 0.5 ) ) ) + ( ( rx * rx ) * ( ( y - 1 ) * ( y - 1 ) ) ) - ( rx * rx * ry * ry ) ; while ( y >= 0 ) { printf ( " ( % f , ▁ % f )
 " , x + xc , y + yc ) ; printf ( " ( % f , ▁ % f )
 " , - x + xc , y + yc ) ; printf ( " ( % f , ▁ % f )
 " , x + xc , - y + yc ) ; printf ( " ( % f , ▁ % f )
 " , - x + xc , - y + yc ) ; if ( d2 > 0 ) { y -- ; dy = dy - ( 2 * rx * rx ) ; d2 = d2 + ( rx * rx ) - dy ; } else { y -- ; x ++ ; dx = dx + ( 2 * ry * ry ) ; dy = dy - ( 2 * rx * rx ) ; d2 = d2 + dx - dy + ( rx * rx ) ; } } } int main ( ) { midptellipse ( 10 , 15 , 50 , 50 ) ; 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
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
#define R  3
#define C  3
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
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
#define R  3
#define C  3
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 ; }


Minimum distance between two occurrences of maximum | C program to find Min distance of maximum element ; function to return min distance ; case a ; case b ; case c ; driver program
How can the above be solved in C?

 #include <bits/stdc++.h>
using namespace std ; int minDistance ( int arr [ ] , int n ) { int maximum_element = arr [ 0 ] ; int min_dis = n ; int index = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( maximum_element == arr [ i ] ) { min_dis = min ( min_dis , ( i - index ) ) ; index = i ; } else if ( maximum_element < arr [ i ] ) { maximum_element = arr [ i ] ; min_dis = n ; index = i ; } else continue ; } return min_dis ; } int main ( ) { int arr [ ] = { 6 , 3 , 1 , 3 , 6 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ distance ▁ = ▁ " << minDistance ( arr , n ) ; return 0 ; }


Minimum insertions to form a palindrome | DP | A Dynamic Programming based program to find minimum number insertions needed to make a string palindrome ; A utility function to find minimum of two integers ; A DP function to find minimum number of insertions ; Create a table of size n * n . table [ i ] [ j ] will store minimum number of insertions needed to convert str [ i . . j ] to a palindrome . ; Fill the table ; Return minimum number of insertions for str [ 0. . n - 1 ] ; Driver program to test above function .
How can the above be solved in C?

 #include <stdio.h>
#include <string.h>
int min ( int a , int b ) { return a < b ? a : b ; } int findMinInsertionsDP ( char str [ ] , int n ) { int table [ n ] [ n ] , l , h , gap ; memset ( table , 0 , sizeof ( table ) ) ; for ( gap = 1 ; gap < n ; ++ gap ) for ( l = 0 , h = gap ; h < n ; ++ l , ++ h ) table [ l ] [ h ] = ( str [ l ] == str [ h ] ) ? table [ l + 1 ] [ h - 1 ] : ( min ( table [ l ] [ h - 1 ] , table [ l + 1 ] [ h ] ) + 1 ) ; return table [ 0 ] [ n - 1 ] ; } int main ( ) { char str [ ] = " geeks " ; printf ( " % d " , findMinInsertionsDP ( str , strlen ( str ) ) ) ; return 0 ; }


Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; A utility function to find minimum of two numbers ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
#include <string.h>
int min ( int a , int b ) { return a < b ? a : b ; } int findMinInsertions ( char str [ ] , int l , int h ) { if ( l > h ) return INT_MAX ; if ( l == h ) return 0 ; if ( l == h - 1 ) return ( str [ l ] == str [ h ] ) ? 0 : 1 ; return ( str [ l ] == str [ h ] ) ? findMinInsertions ( str , l + 1 , h - 1 ) : ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) ; } int main ( ) { char str [ ] = " geeks " ; printf ( " % d " , findMinInsertions ( str , 0 , strlen ( str ) - 1 ) ) ; return 0 ; }


Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver program to test above functions
How can the above be solved in C?


Minimum number of coins having value equal to powers of 2 required to obtain N | C program for above approach ; Function to count of set bit in N ; Stores count of set bit in N ; Iterate over the range [ 0 , 31 ] ; If current bit is set ; Update result ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void count_setbit ( int N ) { int result = 0 ; for ( int i = 0 ; i < 32 ; i ++ ) { if ( ( 1 << i ) & N ) { result ++ ; } } printf ( " % d
 " , result ) ; } int main ( ) { int N = 43 ; count_setbit ( N ) ; return 0 ; }


Minimum number of jumps to reach end | C program to find Minimum number of jumps to reach end ; Returns minimum number of jumps to reach arr [ h ] from arr [ l ] ; Base case : when source and destination are same ; When nothing is reachable from the given source ; Traverse through all the points reachable from arr [ l ] . Recursively get the minimum number of jumps needed to reach arr [ h ] from these reachable points . ; Driver program to test above function
How can the above be solved in C?

 #include <limits.h>
#include <stdio.h>
int minJumps ( int arr [ ] , int l , int h ) { if ( h == l ) return 0 ; if ( arr [ l ] == 0 ) return INT_MAX ; int min = INT_MAX ; for ( int i = l + 1 ; i <= h && i <= l + arr [ l ] ; i ++ ) { int jumps = minJumps ( arr , i , h ) ; if ( jumps != INT_MAX && jumps + 1 < min ) min = jumps + 1 ; } return min ; } int main ( ) { int arr [ ] = { 1 , 3 , 6 , 3 , 2 , 3 , 6 , 8 , 9 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Minimum ▁ number ▁ of ▁ jumps ▁ to ▁ reach ▁ end ▁ is ▁ % d ▁ " , minJumps ( arr , 0 , n - 1 ) ) ; return 0 ; }


Mirror of a point through a 3 D plane | C program to find Mirror of a point through a 3 D plane ; Function to mirror image ; Driver Code ; function call
How can the above be solved in C?

 #include <stdio.h>
void mirror_point ( float a , float b , float c , float d , float x1 , float y1 , float z1 ) { float k = ( - a * x1 - b * y1 - c * z1 - d ) / ( float ) ( a * a + b * b + c * c ) ; float x2 = a * k + x1 ; float y2 = b * k + y1 ; float z2 = c * k + z1 ; float x3 = 2 * x2 - x1 ; float y3 = 2 * y2 - y1 ; float z3 = 2 * z2 - z1 ; printf ( " x3 ▁ = ▁ % .1f ▁ " , x3 ) ; printf ( " y3 ▁ = ▁ % .1f ▁ " , y3 ) ; printf ( " z3 ▁ = ▁ % .1f ▁ " , z3 ) ; } int main ( ) { float a = 1 ; float b = -2 ; float c = 0 ; float d = 0 ; float x1 = -1 ; float y1 = 3 ; float z1 = 4 ; mirror_point ( a , b , c , d , x1 , y1 , z1 ) ; }


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
How can the above be solved in C?

 #include <stdio.h>
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 ▁...


Modify given array to make sum of odd and even indexed elements same | C ++ program for the above approach ; Function to modify array to make sum of odd and even indexed elements equal ; Stores the count of 0 s , 1 s ; Stores sum of odd and even indexed elements respectively ; Count 0 s ; Count 1 s ; Calculate odd_sum and even_sum ; If both are equal ; Print the original array ; Otherwise ; Print all the 0 s ; For checking even or odd ; Update total count of 1 s ; Print all 1 s ; Driver Code ; Given array arr [ ] ; Function Call
How can the above be solved in C?

 #include <stdio.h>
void makeArraySumEqual ( int a [ ] , int N ) { int count_0 = 0 , count_1 = 0 ; int odd_sum = 0 , even_sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( a [ i ] == 0 ) count_0 ++ ; else count_1 ++ ; if ( ( i + 1 ) % 2 == 0 ) even_sum += a [ i ] ; else if ( ( i + 1 ) % 2 > 0 ) odd_sum += a [ i ] ; } if ( odd_sum == even_sum ) { for ( int i = 0 ; i < N ; i ++ ) printf ( " % d ▁ " , a [ i ] ) ; } else { if ( count_0 >= N / 2 ) { for ( int i = 0 ; i < count_0 ; i ++ ) printf ( "0 ▁ " ) ; } else { int is_Odd = count_1 % 2 ; count_1 -= is_Odd ; for ( int i = 0 ; i < count_1 ; i ++ ) printf ( "1 ▁ " ) ; } } } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; makeArraySumEqual ( arr , N ) ; return 0 ; }


Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Change x to x ^ 2
How can the above be solved in C?

int power ( int x , unsigned int y ) { int res = 1 ; while ( y > 0 ) { if ( y & 1 ) res = res * x ; y = y >> 1 ; x = x * x ; } return res ; }


Modular exponentiation ( Recursive ) | Recursive C program to compute modular power ; Base cases ; If B is even ; If B is odd ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
int exponentMod ( int A , int B , int C ) { if ( A == 0 ) return 0 ; if ( B == 0 ) return 1 ; long y ; if ( B % 2 == 0 ) { y = exponentMod ( A , B / 2 , C ) ; y = ( y * y ) % C ; } else { y = A % C ; y = ( y * exponentMod ( A , B - 1 , C ) % C ) % C ; } return ( int ) ( ( y + C ) % C ) ; } int main ( ) { int A = 2 , B = 5 , C = 13 ; printf ( " Power ▁ is ▁ % d " , exponentMod ( A , B , C ) ) ; return 0 ; }


Modular multiplicative inverse | Iterative C program to find modular inverse using extended Euclid algorithm ; Returns modulo inverse of a with respect to m using extended Euclid Algorithm Assumption : a and m are coprimes , i . e . , gcd ( a , m ) = 1 ; q is quotient ; m is remainder now , process same as Euclid 's algo ; Update y and x ; Make x positive ; Driver Code ; Function call
How can the above be solved in C?

 #include <stdio.h>
int modInverse ( int a , int m ) { int m0 = m ; int y = 0 , x = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { int q = a / m ; int t = m ; m = a % m , a = t ; t = y ; y = x - q * y ; x = t ; } if ( x < 0 ) x += m0 ; return x ; } int main ( ) { int a = 3 , m = 11 ; printf ( " Modular ▁ multiplicative ▁ inverse ▁ is ▁ % d
 " , modInverse ( a , m ) ) ; return 0 ; }


Modulo Operator ( % ) in C / C ++ with Examples | Program to illustrate the working of the modulo operator ; To store two integer values ; To store the result of the modulo expression
How can the above be solved in C?

 #include <stdio.h>
int main ( void ) { int x , y ; int result ; x = -3 ; y = 4 ; result = x % y ; printf ( " % d " , result ) ; x = 4 ; y = -2 ; result = x % y ; printf ( " % d " , result ) ; x = -3 ; y = -4 ; result = x % y ; printf ( " % d " , result ) ; return 0 ; }


Morris traversal for Preorder | C program for Morris Preorder traversal ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Preorder traversal without recursion and without stack ; If left child is null , print the current node data . Move to right child . ; Find inorder predecessor ; If the right child of inorder predecessor already points to this node ; If right child doesn 't point to this node, then print this  node and make right child point to this node ; Function for sStandard preorder traversal ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void morrisTraversalPreorder ( struct node * root ) { while ( root ) { if ( root -> left == NULL ) { printf ( " % d ▁ " , root -> data ) ; root = root -> right ; } else { struct node * current = root -> left ; while ( current -> right && current -> right != root ) current = current -> right ; if ( current -> right == root ) { current -> right = NULL ; root = root -> right ; } else { printf ( " % d ▁ " , root -> data ) ; current -> right = root ; root = root -> left ; } } } } void preorder ( struct node * root ) { if ( root ) { printf ( " % d ▁ " , root -> data ) ; preorder ( root -> left ) ; preorder ( root -> right ) ; } } int main ( ) { struct node * root = NULL ; root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; morrisTraversalPreorder ( root ) ; printf ( "
 " ) ; preorder ( root ) ; return 0 ; }


Multiply large integers under large modulo | C program of finding modulo multiplication ; Returns ( a * b ) % mod ; Update a if it is more than or equal to mod ; If b is odd , add a with result ; Here we assume that doing 2 * a doesn 't cause overflow ; b >>= 1 ; b = b / 2 ; Driver program
How can the above be solved in C?

 #include <stdio.h>
long long moduloMultiplication ( long long a , long long b , long long mod ) { a %= mod ; while ( b ) { if ( b & 1 ) res = ( res + a ) % mod ; a = ( 2 * a ) % mod ; } return res ; } int main ( ) { long long a = 10123465234878998 ; long long b = 65746311545646431 ; long long m = 10005412336548794 ; printf ( " % lld " , moduloMultiplication ( a , b , m ) ) ; 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
How can the above be solved in C?

 #include <stdio.h>
#include <string.h>
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 ▁
 " , i ) ; } } int main ( ) { char txt [ ] = " AABAACAADAABAAABAA " ; char pat [ ] = " AABA " ; search ( pat , txt ) ; return 0 ; }


Next Greater Element | Simple C program to print next greater elements in a given array ; prints element and NGE pair for all elements of arr [ ] of size n ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void printNGE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = -1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] ) { next = arr [ j ] ; break ; } } printf ( " % d ▁ - - ▁ % dn " , arr [ i ] , next ) ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNGE ( arr , n ) ; return 0 ; }


Next Smaller Element | Simple C program to print next smaller elements in a given array ; prints element and NSE pair for all elements of arr [ ] of size n ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void printNSE ( int arr [ ] , int n ) { int next , i , j ; for ( i = 0 ; i < n ; i ++ ) { next = -1 ; for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] > arr [ j ] ) { next = arr [ j ] ; break ; } } printf ( " % d ▁ - - ▁ % d
 " , arr [ i ] , next ) ; } } int main ( ) { int arr [ ] = { 11 , 13 , 21 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printNSE ( arr , n ) ; return 0 ; }


Number of substrings with count of each character as k |
How can the above be solved in C?

 #include <stdbool.h>
#include <stdio.h>
#include <string.h>
int min ( int a , int b ) { return a < b ? a : b ; } bool have_same_frequency ( int freq [ ] , int k ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] != 0 && freq [ i ] != k ) { return false ; } } return true ; } int count_substrings ( char * s , int n , int k ) { int count = 0 ; int distinct = 0 ; bool have [ 26 ] = { false } ; for ( int i = 0 ; i < n ; i ++ ) { have [ s [ i ] - ' a ' ] = true ; } for ( int i = 0 ; i < 26 ; i ++ ) { if ( have [ i ] ) { distinct ++ ; } } for ( int length = 1 ; length <= distinct ; length ++ ) { int window_length = length * k ; int freq [ 26 ] = { 0 } ; int window_start = 0 ; int window_end = window_start + window_length - 1 ; for ( int i = window_start ; i <= min ( window_end , n - 1 ) ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; } while ( window_end < n ) { if ( have_same_frequency ( freq , k ) ) { count ++ ; } freq [ s [ window_start ] - ' a ' ] -- ; window_start ++ ; window_end ++ ; if ( window_end < n ) { freq [ s [ window_end ] - ' a ' ] ++ ; } } } return count ; } int main ( ) { char * s = " aabbcc " ; int k = 2 ; printf ( " % d
 " , count_substrings ( s , 6 , k ) ) ; s = " aabbc " ; k = 2 ; printf ( " % d
 " , count_substrings ( s , 5 , k ) ) ; return 0 ; }


Octacontagon Number | C program for above approach ; Finding the nth octacontagon Number ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
int octacontagonNum ( int n ) { return ( 78 * n * n - 76 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ octacontagon ▁ Number ▁ is ▁ = ▁ % d " , octacontagonNum ( n ) ) ; return 0 ; }


Operators in C | Set 2 ( Relational and Logical Operators ) |
How can the above be solved in C?

 #include <stdbool.h>
#include <stdio.h>
int main ( ) { int a = 10 , b = 4 ; bool res = ( ( a != b ) || printf ( " GeeksQuiz " ) ) ; return 0 ; }


Operators in C | Set 2 ( Relational and Logical Operators ) | C program to demonstrate working of logical operators ; logical AND example ; logical OR example ; logical NOT example
How can the above be solved in C?

 #include <stdio.h>
int main ( ) { int a = 10 , b = 4 , c = 10 , d = 20 ; if ( a > b && c == d ) printf ( " a ▁ is ▁ greater ▁ than ▁ b ▁ AND ▁ c ▁ is ▁ equal ▁ to ▁ d
 " ) ; else printf ( " AND ▁ condition ▁ not ▁ satisfied
 " ) ; if ( a > b c == d ) printf ( " a ▁ is ▁ greater ▁ than ▁ b ▁ OR ▁ c ▁ is ▁ equal ▁ to ▁ d
 " ) ; else printf ( " Neither ▁ a ▁ is ▁ greater ▁ than ▁ b ▁ nor ▁ c ▁ is ▁ equal ▁ " " ▁ to ▁ d
 " ) ; if ( ! a ) printf ( " a ▁ is ▁ zero
 " ) ; else printf ( " a ▁ is ▁ not ▁ zero " ) ; return 0 ; }


Operators in C | Set 2 ( Relational and Logical Operators ) | C program to demonstrate working of relational operators ; greater than example ; greater than equal to ; less than example ; lesser than equal to ; equal to ; not equal to
How can the above be solved in C?

 #include <stdio.h>
int main ( ) { int a = 10 , b = 4 ; if ( a > b ) printf ( " a ▁ is ▁ greater ▁ than ▁ b
 " ) ; else printf ( " a ▁ is ▁ less ▁ than ▁ or ▁ equal ▁ to ▁ b
 " ) ; if ( a >= b ) printf ( " a ▁ is ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ b
 " ) ; else printf ( " a ▁ is ▁ lesser ▁ than ▁ b
 " ) ; if ( a < b ) printf ( " a ▁ is ▁ less ▁ than ▁ b
 " ) ; else printf ( " a ▁ is ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ b
 " ) ; if ( a <= b ) printf ( " a ▁ is ▁ lesser ▁ than ▁ or ▁ equal ▁ to ▁ b
 " ) ; else printf ( " a ▁ is ▁ greater ▁ than ▁ b
 " ) ; if ( a == b ) printf ( " a ▁ is ▁ equal ▁ to ▁ b
 " ) ; else printf ( " a ▁ and ▁ b ▁ are ▁ not ▁ equal
 " ) ; if ( a != b ) printf ( " a ▁ is ▁ not ▁ equal ▁ to ▁ b
 " ) ; else printf ( " a ▁ is ▁ equal ▁ b
 " ) ; return 0 ; }


Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A recursive function to calculate cost of optimal binary search tree ; Base cases if ( j < i ) 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 . ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
int optCost ( int freq [ ] , int i , int j ) { 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 sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } 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 | 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
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
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
How can the above be solved in C?

 #include <stdio.h>
#include <limits.h>
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 ; }


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 Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if ( j == M ) if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <string.h>
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 ; { printf ( " Pattern ▁ found ▁ at ▁ index ▁ % d ▁
 " , 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 ; }


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
How can the above be solved in C?

 #include <stdio.h>
#include <string.h>
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 ▁
 " , 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 ; }


Overlapping Subproblems Property in Dynamic Programming | DP | a simple recursive program for Fibonacci numbers
How can the above be solved in C?

int fib ( int n ) { if ( n <= 1 ) return n ; return fib ( n - 1 ) + fib ( n - 2 ) ; }


Pairwise swap elements of a given linked list | Recursive function to pairwise swap elements of a linked list ; There must be at - least two nodes in the list ; Swap the node 's data with data of next node  ; Call pairWiseSwap ( ) for rest of the list
How can the above be solved in C?

void pairWiseSwap ( struct node * head ) { if ( head != NULL && head -> next != NULL ) { swap ( & head -> data , & head -> next -> data ) ; pairWiseSwap ( head -> next -> next ) ; } }


Palindrome Partitioning | DP | Dynamic Programming Solution for Palindrome Partitioning Problem ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum number of cuts needed for palindrome partitioning of substring str [ i . . j ] P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false Note that C [ i ] [ j ] is 0 if P [ i ] [ j ] is true ; different looping variables ; Every substring of length 1 is a palindrome ; L is substring length . Build the solution in bottom up manner by considering all substrings of length starting from 2 to n . The loop structure is same as Matrix Chain Multiplication problem ( See https : www . geeksforgeeks . org / matrix - chain - multiplication - dp - 8 / ) ; For substring of length L , set different possible starting indexes ; Set ending index ; If L is 2 , then we just need to compare two characters . Else need to check two corner characters and value of P [ i + 1 ] [ j - 1 ] ; IF str [ i . . j ] is palindrome , then C [ i ] [ j ] is 0 ; Make a cut at every possible location starting from i to j , and get the minimum cost cut . ; Return the min cut value for complete string . i . e . , str [ 0. . n - 1 ] ; Driver program to test above function
How can the above be solved in C?

 #include <limits.h>
#include <stdio.h>
#include <string.h>
int min ( int a , int b ) { return ( a < b ) ? a : b ; } int minPalPartion ( char * str ) { int n = strlen ( str ) ; int C [ n ] [ n ] ; bool P [ n ] [ n ] ; int i , j , k , L ; for ( i = 0 ; i < n ; i ++ ) { P [ i ] [ i ] = true ; C [ i ] [ i ] = 0 ; } for ( L = 2 ; L <= n ; L ++ ) { for ( i = 0 ; i < n - L + 1 ; i ++ ) { j = i + L - 1 ; if ( L == 2 ) P [ i ] [ j ] = ( str [ i ] == str [ j ] ) ; else P [ i ] [ j ] = ( str [ i ] == str [ j ] ) && P [ i + 1 ] [ j - 1 ] ; if ( P [ i ] [ j ] == true ) C [ i ] [ j ] = 0 ; else { C [ i ] [ j ] = INT_MAX ; for ( k = i ; k <= j - 1 ; k ++ ) C [ i ] [ j ] = min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) ; } } } return C [ 0 ] [ n - 1 ] ; } int main ( ) { char str [ ] = " ababbbabbababa " ; printf ( " Min ▁ cuts ▁ needed ▁ for ▁ Palindrome ▁ Partitioning ▁ is ▁ % d " , minPalPartion ( str ) ) ; return 0 ; }


Pancake sorting | C program to sort array using pancake sort ; Reverses arr [ 0. . i ] ; Returns index of the maximum element in arr [ 0. . n - 1 ] ; The main function that sorts given array using flip operations ; Start from the complete array and one by one reduce current size by one ; Find index of the maximum element in arr [ 0. . curr_size - 1 ] ; Move the maximum element to end of current array if it 's not already  at the end ; To move at the end , first move maximum number to beginning ; Now move the maximum number to end by reversing current array ; A utility function to print n array of size n ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
void flip ( int arr [ ] , int i ) { int temp , start = 0 ; while ( start < i ) { temp = arr [ start ] ; arr [ start ] = arr [ i ] ; arr [ i ] = temp ; start ++ ; i -- ; } } int findMax ( int arr [ ] , int n ) { int mi , i ; for ( mi = 0 , i = 0 ; i < n ; ++ i ) if ( arr [ i ] > arr [ mi ] ) mi = i ; return mi ; } void pancakeSort ( int * arr , int n ) { for ( int curr_size = n ; curr_size > 1 ; -- curr_size ) { int mi = findMax ( arr , curr_size ) ; if ( mi != curr_size - 1 ) { flip ( arr , mi ) ; flip ( arr , curr_size - 1 ) ; } } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 23 , 10 , 20 , 11 , 12 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pancakeSort ( arr , n ) ; puts ( " Sorted ▁ Array ▁ " ) ; printArray ( arr , n ) ; return 0 ; }


Pentacontagon number | C program for above approach ; Finding the nth pentacontagon Number ; Driver program to test above function
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
int pentacontagonNum ( int n ) { return ( 48 * n * n - 46 * n ) / 2 ; } int main ( ) { int n = 3 ; printf ( "3rd ▁ pentacontagon ▁ Number ▁ is ▁ = ▁ % d " , pentacontagonNum ( n ) ) ; return 0 ; }


Perimeter and Area of Varignon 's Parallelogram | C program to find the perimeter and area ; Function to find the perimeter ; Function to find the area ; Driver code
How can the above be solved in C?

 #include <stdio.h>
float per ( float a , float b ) { return ( a + b ) ; } float area ( float s ) { return ( s / 2 ) ; } int main ( ) { float a = 7 , b = 8 , s = 10 ; printf ( " % f
 " , per ( a , b ) ) ; printf ( " % f " , area ( s ) ) ; return 0 ; }


Perpendicular distance between a point and a Line in 2 D | C program to find the distance between a given point and a given line in 2 D . ; Function to find distance ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
#include <math.h>
void shortest_distance ( float x1 , float y1 , float a , float b , float c ) { float d = fabs ( ( a * x1 + b * y1 + c ) ) / ( sqrt ( a * a + b * b ) ) ; printf ( " Perpendicular ▁ distance ▁ is ▁ % f
 " , d ) ; return ; } int main ( ) { float x1 = 5 ; float y1 = 6 ; float a = -2 ; float b = 3 ; float c = 4 ; shortest_distance ( x1 , y1 , a , b , c ) ; return 0 ; }


Populate Inorder Successor for all nodes | C # program to populate inorder traversal of all nodes ; An implementation that doesn 't use static variable A wrapper over populateNextRecur ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; Set next of all descendants of p by traversing them in reverse Inorder ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in right subtree
How can the above be solved in C?

struct node { int data ; struct node * left ; struct node * right ; struct node * next ; } void populateNext ( struct node * root ) { struct node * next = NULL ; populateNextRecur ( root , & next ) ; } void populateNextRecur ( struct node * p , struct node * * next_ref ) { if ( p ) { populateNextRecur ( p -> right , next_ref ) ; p -> next = * next_ref ; * next_ref = p ; populateNextRecur ( p -> left , next_ref ) ; } }


Position of rightmost set bit | C program for Position of rightmost set bit ; Driver code
How can the above be solved in C?

 #include <math.h>
#include <stdio.h>
unsigned int getFirstSetBitPos ( int n ) { return log2 ( n & - n ) + 1 ; } int main ( ) { int n = 12 ; printf ( " % u " , getFirstSetBitPos ( n ) ) ; getchar ( ) ; return 0 ; }


Practice questions for Linked List and Recursion |
How can the above be solved in C?

struct Node { int data ; struct Node * next ; } ;


void fun1 ( struct Node * head ) { if ( head == NULL ) return ; fun1 ( head -> next ) ; printf ( " % d ▁ " , head -> data ) ; }


void fun2 ( struct Node * head ) { if ( head == NULL ) return ; printf ( " % d ▁ " , head -> data ) ; if ( head -> next != NULL ) fun2 ( head -> next -> next ) ; printf ( " % d ▁ " , head -> data ) ; }


Practice questions for Linked List and Recursion |  ; A linked list node ; Prints a linked list in reverse manner ; prints alternate nodes of a Linked List , first from head to end , and then from end to head . ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver program to test above functions ; Start with the empty list ; Using push ( ) to construct below list 1 -> 2 -> 3 -> 4 -> 5
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * next ; } ; void fun1 ( struct Node * head ) { if ( head == NULL ) return ; fun1 ( head -> next ) ; printf ( " % d ▁ " , head -> data ) ; } void fun2 ( struct Node * start ) { if ( start == NULL ) return ; printf ( " % d ▁ " , start -> data ) ; if ( start -> next != NULL ) fun2 ( start -> next -> next ) ; printf ( " % d ▁ " , start -> data ) ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * head = NULL ; push ( & head , 5 ) ; push ( & head , 4 ) ; push ( & head , 3 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; printf ( " Output ▁ of ▁ fun1 ( ) ▁ for ▁ list ▁ 1 - > 2 - > 3 - > 4 - > 5 ▁
 " ) ; fun1 ( head ) ; printf ( " Output of fun2 ( ) for list 1 -> 2 -> 3 -> 4 -> 5 " fun2 ( head ) ; getchar ( ) ; return 0 ; }


Print Binary Tree in 2 | Program to print binary tree in 2D ; A binary tree node ; Helper function to allocates a new node ; Function to print binary tree in 2D It does reverse inorder traversal ; Base case ; Increase distance between levels ; Process right child first ; Print current node after space count ; Process left child ; Wrapper over print2DUtil ( ) ; Pass initial space count as 0 ; Driver program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <malloc.h>
#define COUNT  10
struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = malloc ( sizeof ( struct Node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void print2DUtil ( struct Node * root , int space ) { if ( root == NULL ) return ; space += COUNT ; print2DUtil ( root -> right , space ) ; printf ( "
 " ) ; for ( int i = COUNT ; i < space ; i ++ ) printf ( " ▁ " ) ; printf ( " % d
 " , root -> data ) ; print2DUtil ( root -> left , space ) ; } void print2D ( struct Node * root ) { print2DUtil ( root , 0 ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> left -> left = newNode ( 12 ) ; root -> right -> left -> right = newNode ( 13 ) ; root -> right -> right -> left = newNode ( 14 ) ; root -> right -> right -> right = newNode ( 15 ) ; print2D ( root ) ; return 0 ; }


Print Left View of a Binary Tree | C program to print left view of Binary Tree ; A utility function to create a new Binary Tree node ; Recursive function to print left view of a binary tree . ; Base Case ; If this is the first node of its level ; Recur for left and right subtrees ; A wrapper over leftViewUtil ( ) ; Driver code
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int item ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } void leftViewUtil ( struct node * root , int level , int * max_level ) { if ( root == NULL ) return ; if ( * max_level < level ) { printf ( " % d 	 " , root -> data ) ; * max_level = level ; } leftViewUtil ( root -> left , level + 1 , max_level ) ; leftViewUtil ( root -> right , level + 1 , max_level ) ; } void leftView ( struct node * root ) { int max_level = 0 ; leftViewUtil ( root , 1 , & max_level ) ; } int main ( ) { struct node * root = newNode ( 12 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 30 ) ; root -> right -> left = newNode ( 25 ) ; root -> right -> right = newNode ( 40 ) ; leftView ( root ) ; 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 '
How can the above be solved in C?

 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 ▁
 " , 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 ) ; } } }


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
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
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 ▁
 " , 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 sequences of given length | C ++ program of above approach ; A utility function that prints a given arr [ ] of length size ; The core function that recursively generates and prints all sequences of length k ; A function that uses printSequencesRecur ( ) to prints all sequences from 1 , 1 , . .1 to n , n , . . n ; Driver Program to test above functions
How can the above be solved in C?

 #include <stdio.h>
void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; printf ( "
 " ) ; return ; } void printSequencesRecur ( int arr [ ] , int n , int k , int index ) { int i ; if ( k == 0 ) { printArray ( arr , index ) ; } if ( k > 0 ) { for ( i = 1 ; i <= n ; ++ i ) { arr [ index ] = i ; printSequencesRecur ( arr , n , k - 1 , index + 1 ) ; } } } void printSequences ( int n , int k ) { int * arr = new int [ k ] ; printSequencesRecur ( arr , n , k , 0 ) ; return ; } int main ( ) { int n = 3 ; int k = 2 ; printSequences ( n , k ) ; return 0 ; }


Print alternate elements of an array | C program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; If currIndex stores even index or odd position ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void printAlter ( int arr [ ] , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex ++ ) { if ( currIndex % 2 == 0 ) { printf ( " % d ▁ " , arr [ currIndex ] ) ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAlter ( arr , N ) ; }


Print alternate elements of an array | C program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; Print elements of array ; Driver Code
How can the above be solved in C?

 #include <stdio.h>
void printAlter ( int arr [ ] , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex += 2 ) { printf ( " % d ▁ " , arr [ currIndex ] ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAlter ( arr , N ) ; }


Print cousins of a given node in Binary Tree | C program to print cousins of a node ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; It returns level of the node if it is present in tree , otherwise returns 0. ; base cases ; If node is present in left subtree ; If node is not present in left subtree ; Print nodes at a given level such that sibling of node is not printed if it exists ; Base cases ; If current node is parent of a node with given level ; Recur for left and right subtrees ; This function prints cousins of a given node ; Get level of given node ; Print nodes of given level . ; Driver Program to test above functions
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } int getLevel ( Node * root , Node * node , int level ) { if ( root == NULL ) return 0 ; if ( root == node ) return level ; int downlevel = getLevel ( root -> left , node , level + 1 ) ; if ( downlevel != 0 ) return downlevel ; return getLevel ( root -> right , node , level + 1 ) ; } void printGivenLevel ( Node * root , Node * node , int level ) { if ( root == NULL level < 2 ) return ; if ( level == 2 ) { if ( root -> left == node root -> right == node ) return ; if ( root -> left ) printf ( " % d ▁ " , root -> left -> data ) ; if ( root -> right ) printf ( " % d ▁ " , root -> right -> data ) ; } else if ( level > 2 ) { printGivenLevel ( root -> left , node , level - 1 ) ; printGivenLevel ( root -> right , node , level - 1 ) ; } } void printCousins ( Node * root , Node * node ) { int level = getLevel ( root , node , 1 ) ; printGivenLevel ( root , node , level ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> left -> right -> right = newNode ( 15 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; printCousins ( root , root -> left -> right ) ; return 0 ; }


Print list items containing all characters of a given word | C program to print all strings that contain all characters of a word ; prints list items having all characters of word ; Since calloc is used , map [ ] is initialized as 0 ; Set the values in map ; Get the length of given word ; Check each item of list if has all characters of word ; unset the bit so that strings like sss not printed ; Set the values in map for next item ; Driver program to test to pront printDups
How can the above be solved in C?

 # include <stdio.h>
# include <stdlib.h>
# include <string.h>
# define NO_OF_CHARS  256
void print ( char * list [ ] , char * word , int list_size ) { int * map = ( int * ) calloc ( sizeof ( int ) , NO_OF_CHARS ) ; int i , j , count , word_size ; for ( i = 0 ; * ( word + i ) ; i ++ ) map [ * ( word + i ) ] = 1 ; word_size = strlen ( word ) ; for ( i = 0 ; i < list_size ; i ++ ) { for ( j = 0 , count = 0 ; * ( list [ i ] + j ) ; j ++ ) { if ( map [ * ( list [ i ] + j ) ] ) { count ++ ; map [ * ( list [ i ] + j ) ] = 0 ; } } if ( count == word_size ) printf ( " % s " , list [ i ] ) ; for ( j = 0 ; * ( word + j ) ; j ++ ) map [ * ( word + j ) ] = 1 ; } } int main ( ) { char str [ ] = " sun " ; char * list [ ] = { " geeksforgeeks " , " unsorted " , " sunday " , " just " , " sss " } ; print ( list , str , 5 ) ; getchar ( ) ; return 0 ; }


Print nodes at k distance from root |  ; A binary tree node has data , pointer to left child and a pointer to 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 ; Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8
How can the above be solved in C?

 #include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; void printKDistant ( struct node * root , int k ) { if ( root == NULL k < 0 ) return ; if ( k == 0 ) { printf ( " % d ▁ " , root -> data ) ; return ; } printKDistant ( root -> left , k - 1 ) ; printKDistant ( root -> right , k - 1 ) ; } 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 ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 8 ) ; printKDistant ( root , 2 ) ; getchar ( ) ; return 0 ; }