text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Count pairs in array whose sum is divisible by 4 | C ++ Program to count pairs whose sum divisible by '4' ; Program to count pairs whose sum divisible by '4' ; Create a frequency array to count occurrences of all remainders when divided by 4 ; Count occurrences of all remainders ; If both pairs are divisible by '4' ; If both pairs are 2 modulo 4 ; If one of them is equal to 1 modulo 4 and the other is equal to 3 modulo 4 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count4Divisibiles ( int arr [ ] , int n ) { int freq [ 4 ] = { 0 , 0 , 0 , 0 } ; for ( int i = 0 ; i < n ; i ++ ) ++ freq [ arr [ i ] % 4 ] ; int ans = freq [ 0 ] * ( freq [ 0 ] - 1 ) / 2 ; ans += freq [ 2 ] * ( freq [ 2 ] - 1 ) / 2 ; ans += freq [ 1 ] * freq [ 3 ] ; return ans ; } int main ( ) { int arr [ ] = { 2 , 2 , 1 , 7 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << count4Divisibiles ( arr , n ) ; return 0 ; }
Find Sum of all unique sub | C ++ for finding sum of all unique subarray sum ; function for finding grandSum ; calculate cumulative sum of array cArray [ 0 ] will store sum of zero elements ; store all subarray sum in vector ; sort the vector ; mark all duplicate sub - array sum to zero ; calculate total sum ; return totalSum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int findSubarraySum ( int arr [ ] , int n ) { int i , j ; long long int cArray [ n + 1 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) cArray [ i + 1 ] = cArray [ i ] + arr [ i ] ; vector < long long int > subArrSum ; for ( i = 1 ; i <= n ; i ++ ) for ( j = i ; j <= n ; j ++ ) subArrSum . push_back ( cArray [ j ] - cArray [ i - 1 ] ) ; sort ( subArrSum . begin ( ) , subArrSum . end ( ) ) ; long long totalSum = 0 ; for ( i = 0 ; i < subArrSum . size ( ) - 1 ; i ++ ) { if ( subArrSum [ i ] == subArrSum [ i + 1 ] ) { j = i + 1 ; while ( subArrSum [ j ] == subArrSum [ i ] && j < subArrSum . size ( ) ) { subArrSum [ j ] = 0 ; j ++ ; } subArrSum [ i ] = 0 ; } } for ( i = 0 ; i < subArrSum . size ( ) ; i ++ ) totalSum += subArrSum [ i ] ; return totalSum ; } int main ( ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubarraySum ( arr , n ) ; return 0 ; }
Smallest number whose set bits are maximum in a given range | C ++ program to find number whose set bits are maximum among ' l ' and ' r ' ; Returns smallest number whose set bits are maximum in given range . ; Initialize the maximum count and final answer as ' num ' ; Traverse for every bit of ' i ' number ; If count is greater than previous calculated max_count , update it ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxSetBits ( int left , int right ) { int max_count = -1 , num ; for ( int i = left ; i <= right ; ++ i ) { int temp = i , cnt = 0 ; while ( temp ) { if ( temp & 1 ) ++ cnt ; temp >>= 1 ; } if ( cnt > max_count ) { max_count = cnt ; num = i ; } } return num ; } int main ( ) { int l = 1 , r = 5 ; cout << countMaxSetBits ( l , r ) << " STRNEWLINE " ; l = 1 , r = 10 ; cout << countMaxSetBits ( l , r ) ; return 0 ; }
Find Sum of all unique sub | C ++ for finding sum of all unique subarray sum ; function for finding grandSum ; Go through all subarrays , compute sums and count occurrences of sums . ; Print all those sums that appear once . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int findSubarraySum ( int arr [ ] , int n ) { int res = 0 ; unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { sum += arr [ j ] ; m [ sum ] ++ ; } } for ( auto x : m ) if ( x . second == 1 ) res += x . first ; return res ; } int main ( ) { int arr [ ] = { 3 , 2 , 3 , 1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSubarraySum ( arr , n ) ; return 0 ; }
Quickselect Algorithm | CPP program for implementation of QuickSelect ; Standard partition process of QuickSort ( ) . It considers the last element as pivot and moves all smaller element to left of it and greater elements to right ; This function returns k 'th smallest element in arr[l..r] using QuickSort based method. ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT ; If k is smaller than number of elements in array ; Partition the array around last element and get position of pivot element in sorted array ; If position is same as k ; If position is more , recur for left subarray ; Else recur for right subarray ; If k is more than number of elements in array ; Driver program to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int partition ( int arr [ ] , int l , int r ) { int x = arr [ r ] , i = l ; for ( int j = l ; j <= r - 1 ; j ++ ) { if ( arr [ j ] <= x ) { swap ( arr [ i ] , arr [ j ] ) ; i ++ ; } } swap ( arr [ i ] , arr [ r ] ) ; return i ; } int kthSmallest ( int arr [ ] , int l , int r , int k ) { if ( k > 0 && k <= r - l + 1 ) { int index = partition ( arr , l , r ) ; if ( index - l == k - 1 ) return arr [ index ] ; if ( index - l > k - 1 ) return kthSmallest ( arr , l , index - 1 , k ) ; return kthSmallest ( arr , index + 1 , r , k - index + l - 1 ) ; } return INT_MAX ; } int main ( ) { int arr [ ] = { 10 , 4 , 5 , 8 , 6 , 11 , 26 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << " K - th ▁ smallest ▁ element ▁ is ▁ " << kthSmallest ( arr , 0 , n - 1 , k ) ; return 0 ; }
Recaman 's sequence | C ++ program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Create an array to store terms ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int recaman ( int n ) { int arr [ n ] ; arr [ 0 ] = 0 ; printf ( " % d , ▁ " , arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { int curr = arr [ i - 1 ] - i ; int j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == curr ) curr < 0 ) { curr = arr [ i - 1 ] + i ; break ; } } arr [ i ] = curr ; printf ( " % d , ▁ " , arr [ i ] ) ; } } int main ( ) { int n = 17 ; recaman ( n ) ; return 0 ; }
Print the longest leaf to leaf path in a Binary tree | C ++ program to print the longest leaf to leaf path ; Tree node structure used in the program ; Function to find height of a tree ; update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; save the root , this will help us finding the left and the right part of the diameter ; save the height of left & right subtree as well . ; prints the root to leaf path ; print left part of the path in reverse order ; this function finds out all the root to leaf paths ; append this node to the path array ; If it 's a leaf, so print the path that led to here ; print only one path which is equal to the height of the tree . ; otherwise try both subtrees ; Computes the diameter of a binary tree with given root . ; lh will store height of left subtree rh will store height of right subtree ; f is a flag whose value helps in printing left & right part of the diameter only once ; print the left part of the diameter ; print the right part of the diameter ; Driver code ; Enter the binary tree ... 1 / \ 2 3 / \ 4 5 \ / \ 8 6 7 / 9
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int height ( Node * root , int & ans , Node * ( & k ) , int & lh , int & rh , int & f ) { if ( root == NULL ) return 0 ; int left_height = height ( root -> left , ans , k , lh , rh , f ) ; int right_height = height ( root -> right , ans , k , lh , rh , f ) ; if ( ans < 1 + left_height + right_height ) { ans = 1 + left_height + right_height ; k = root ; lh = left_height ; rh = right_height ; } return 1 + max ( left_height , right_height ) ; } void printArray ( int ints [ ] , int len , int f ) { int i ; if ( f == 0 ) { for ( i = len - 1 ; i >= 0 ; i -- ) { printf ( " % d ▁ " , ints [ i ] ) ; } } else if ( f == 1 ) { for ( i = 0 ; i < len ; i ++ ) { printf ( " % d ▁ " , ints [ i ] ) ; } } } void printPathsRecur ( Node * node , int path [ ] , int pathLen , int max , int & f ) { if ( node == NULL ) return ; path [ pathLen ] = node -> data ; pathLen ++ ; if ( node -> left == NULL && node -> right == NULL ) { if ( pathLen == max && ( f == 0 f == 1 ) ) { printArray ( path , pathLen , f ) ; f = 2 ; } } else { printPathsRecur ( node -> left , path , pathLen , max , f ) ; printPathsRecur ( node -> right , path , pathLen , max , f ) ; } } void diameter ( Node * root ) { if ( root == NULL ) return ; int ans = INT_MIN , lh = 0 , rh = 0 ; int f = 0 ; Node * k ; int height_of_tree = height ( root , ans , k , lh , rh , f ) ; int lPath [ 100 ] , pathlen = 0 ; printPathsRecur ( k -> left , lPath , pathlen , lh , f ) ; printf ( " % d ▁ " , k -> data ) ; int rPath [ 100 ] ; f = 1 ; printPathsRecur ( k -> right , rPath , pathlen , rh , f ) ; } 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 -> left -> right -> left = newNode ( 6 ) ; root -> left -> right -> right = newNode ( 7 ) ; root -> left -> left -> right = newNode ( 8 ) ; root -> left -> left -> right -> left = newNode ( 9 ) ; diameter ( root ) ; return 0 ; }
Recaman 's sequence | C ++ program to print n - th number in Recaman 's sequence ; Prints first n terms of Recaman sequence ; Print first term and store it in a hash ; Print remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void recaman ( int n ) { if ( n <= 0 ) return ; printf ( " % d , ▁ " , 0 ) ; unordered_set < int > s ; s . insert ( 0 ) ; int prev = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int curr = prev - i ; if ( curr < 0 || s . find ( curr ) != s . end ( ) ) curr = prev + i ; s . insert ( curr ) ; printf ( " % d , ▁ " , curr ) ; prev = curr ; } } int main ( ) { int n = 17 ; recaman ( n ) ; return 0 ; }
Find index of an extra element present in one sorted array | C ++ code for above approach ; function return sum of array elements ; function return index of given element ; Function to find Index ; Calculating extra element ; returns index of extra element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int arr [ ] , int n ) { int summ = 0 ; for ( int i = 0 ; i < n ; i ++ ) { summ += arr [ i ] ; } return summ ; } int indexOf ( int arr [ ] , int element , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == element ) { return i ; } } return -1 ; } int find_extra_element_index ( int arrA [ ] , int arrB [ ] , int n , int m ) { int extra_element = sum ( arrA , n ) - sum ( arrB , m ) ; return indexOf ( arrA , extra_element , n ) ; } int main ( ) { int arrA [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int arrB [ ] = { 2 , 4 , 6 , 8 , 10 , 12 } ; int n = sizeof ( arrA ) / sizeof ( arrA [ 0 ] ) ; int m = sizeof ( arrB ) / sizeof ( arrB [ 0 ] ) ; cout << find_extra_element_index ( arrA , arrB , n , m ) ; }
Largest subset whose all elements are Fibonacci numbers | C ++ program to find largest Fibonacci subset ; Prints largest subset of an array whose all elements are fibonacci numbers ; Find maximum element in arr [ ] ; Generate all Fibonacci numbers till max and store them in hash . ; Npw iterate through all numbers and quickly check for Fibonacci using hash . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findFibSubset ( int arr [ ] , int n ) { int max = * std :: max_element ( arr , arr + n ) ; int a = 0 , b = 1 ; unordered_set < int > hash ; hash . insert ( a ) ; hash . insert ( b ) ; while ( b < max ) { int c = a + b ; a = b ; b = c ; hash . insert ( b ) ; } for ( int i = 0 ; i < n ; i ++ ) if ( hash . find ( arr [ i ] ) != hash . end ( ) ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 8 , 5 , 20 , 1 , 40 , 13 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findFibSubset ( arr , n ) ; return 0 ; }
Pairs of Amicable Numbers | Efficient C ++ program to count Amicable pairs in an array . ; Calculate the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; Check if pair is amicable ; This function prints count of amicable pairs present in the input array ; Map to store the numbers ; Iterate through each number , and find the sum of proper divisors and check if it 's also present in the array ; It 's sum of proper divisors ; As the pairs are counted twice , thus divide by 2 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDiv ( int x ) { int sum = 1 ; for ( int i = 2 ; i <= sqrt ( x ) ; i ++ ) { if ( x % i == 0 ) { sum += i ; if ( x / i != i ) sum += x / i ; } } return sum ; } bool isAmicable ( int a , int b ) { return ( sumOfDiv ( a ) == b && sumOfDiv ( b ) == a ) ; } int countPairs ( int arr [ ] , int n ) { unordered_set < int > s ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . find ( sumOfDiv ( arr [ i ] ) ) != s . end ( ) ) { int sum = sumOfDiv ( arr [ i ] ) ; if ( isAmicable ( arr [ i ] , sum ) ) count ++ ; } } return count / 2 ; } int main ( ) { int arr1 [ ] = { 220 , 284 , 1184 , 1210 , 2 , 5 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << countPairs ( arr1 , n1 ) << endl ; int arr2 [ ] = { 2620 , 2924 , 5020 , 5564 , 6232 , 6368 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << countPairs ( arr2 , n2 ) << endl ; return 0 ; }
Minimum number of characters required to be removed such that every character occurs same number of times | C ++ program for the above approach ; Function to find minimum number of character removals required to make frequency of all distinct characters the same ; Stores the frequency of each character ; Traverse the string ; Stores the frequency of each charachter in sorted order ; Traverse the Map ; Insert the frequency in multiset ; Stores the count of elements required to be removed ; Stores the size of multiset ; Traverse the multiset ; Update the ans ; Increment i by 1 ; Return ; Driver Code ; Input
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumDeletion ( string s , int n ) { map < char , int > countMap ; for ( int i = 0 ; i < n ; i ++ ) { countMap [ s [ i ] ] ++ ; } multiset < int > countMultiset ; for ( auto it : countMap ) { countMultiset . insert ( it . second ) ; } int ans = INT_MAX ; int i = 0 ; int m = countMultiset . size ( ) ; for ( auto j : countMultiset ) { ans = min ( ans , n - ( m - i ) * j ) ; i ++ ; } return ans ; } int main ( ) { string S = " geeksforgeeks " ; int N = S . length ( ) ; cout << minimumDeletion ( S , N ) ; return 0 ; }
Minimum number of distinct elements present in a K | C ++ program for the above approach ; Function to count the minimum number of distinct elements present in any subsequence of length K of the given array ; Stores the frequency of each array element ; Traverse the array ; Update frequency of array elements ; Store the required result ; Store the length of the required subsequence ; Store the frequencies in decreasing order ; Traverse the map ; Push the frequencies into the HashMap ; Sort the array in decreasing order ; Add the elements into the subsequence starting from one with highest frequency ; If length of subsequence is >= k ; Print the result ; Driver Code ; Store the size of the array ; Function Call to count minimum number of distinct elmeents present in a K - length subsequence
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinimumDistinct ( int A [ ] , int N , int K ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) mp [ A [ i ] ] ++ ; int count = 0 ; int len = 0 ; vector < int > counts ; for ( auto i : mp ) counts . push_back ( i . second ) ; sort ( counts . begin ( ) , counts . end ( ) , greater < int > ( ) ) ; for ( int i = 0 ; i < counts . size ( ) ; i ++ ) { if ( len >= K ) break ; len += counts [ i ] ; count ++ ; } cout << count ; } int main ( ) { int A [ ] = { 3 , 1 , 3 , 2 , 3 , 4 , 5 , 4 } ; int K = 4 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findMinimumDistinct ( A , N , K ) ; return 0 ; }
Calculate cost of visiting all array elements in increasing order | C ++ implementation of the above approach ; Function to calculate total cost of visiting array elements in increasing order ; Stores the pair of element and their positions ; Traverse the array arr [ ] ; Push the pair { arr [ i ] , i } in v ; Sort the vector in ascending order . ; Stores the total cost ; Stores the index of last element visited ; Traverse the vector v ; Increment ans ; Assign ; Return ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateDistance ( int arr [ ] , int N ) { vector < pair < int , int > > v ; for ( int i = 0 ; i < N ; i ++ ) v . push_back ( { arr [ i ] , i } ) ; sort ( v . begin ( ) , v . end ( ) ) ; int ans = 0 ; int last = 0 ; for ( auto j : v ) { ans += abs ( j . second - last ) ; last = j . second ; } return ans ; } int main ( ) { int arr [ ] = { 4 , 3 , 2 , 5 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << calculateDistance ( arr , N ) ; }
Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | C ++ program of the above approach ; Function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; Traverse the array of strings ; Convert the current array element to a string ; Sort each string in descending order ; Convert the string to equivalent integer ; Calculate square root of current array element ; Calculate perfect square ; Find the nearest perfect square ; Sort the array in ascending order ; Print the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortArr ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { string s = to_string ( arr [ i ] ) ; sort ( s . begin ( ) , s . end ( ) , greater < char > ( ) ) ; arr [ i ] = stoi ( s ) ; int sr = sqrt ( arr [ i ] ) ; int a = sr * sr ; int b = ( sr + 1 ) * ( sr + 1 ) ; if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) arr [ i ] = a ; else arr [ i ] = b ; } sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 29 , 43 , 28 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , N ) ; return 0 ; }
Minimize cost required to make all array elements greater than or equal to zero | C ++ program for the above approach ; Function to find the minimum cost to make all array elements greater than or equal to 0 ; Sort the array in ascending order ; Stores the cost to make current array element >= 0 ; Stores the cost to make all array elements >= 0 ; Traverse the array and insert all the elements which are < 0 ; If current array element is negative ; Cost to make all array elements >= 0 ; Update curr if ans is minimum ; Print the minimum cost ; Driver Code ; Given array ; Size of the array ; Given value of X ; Function call to find minimum cost to make all array elements >= 0
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minCost ( int arr [ ] , int N , int X ) { sort ( arr , arr + N ) ; int sum = 0 ; int cost = 0 ; int min_cost = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cost = abs ( arr [ i ] ) * X + ( sum - abs ( arr [ i ] ) * i ) ; sum += abs ( arr [ i ] ) ; min_cost = min ( min_cost , cost ) ; } } cout << min_cost ; } int main ( ) { int arr [ ] = { -1 , -3 , -2 , 4 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 2 ; minCost ( arr , N , X ) ; return 0 ; }
Count arrays having at least K elements exceeding XOR of all given array elements by X given operations | C ++ program for the above approach ; Stores the final answer ; Utility function to count arrays having at least K elements exceeding XOR of all given array elements ; If no operations are left ; Stores the count of possible arrays ; Count array elements are greater than XOR ; Stores first element ; Delete first element ; Recursive call ; Insert first element into vector ; Stores the last element ; Remove last element from vector ; Recursive call ; Push last element into vector ; Increment first element ; Recursive call ; Decrement first element ; Increment last element ; Recursive call ; Decrement last element ; Function to find the count of arrays having atleast K elements greater than XOR of array ; Stores the XOR value of original array ; Traverse the vector ; Print the answer ; Driver Code ; Given vector ; Given value of X & K
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 ; void countArraysUtil ( vector < int > & arr , int X , int K , int xorVal ) { if ( X == 0 ) { int cnt = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( arr [ i ] > xorVal ) cnt ++ ; } if ( cnt >= K ) ans ++ ; return ; } int temp = arr [ 0 ] ; arr . erase ( arr . begin ( ) ) ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr . insert ( arr . begin ( ) , temp ) ; temp = arr . back ( ) ; arr . pop_back ( ) ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr . push_back ( temp ) ; arr [ 0 ] ++ ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr [ 0 ] -- ; arr [ arr . size ( ) - 1 ] ++ ; countArraysUtil ( arr , X - 1 , K , xorVal ) ; arr [ arr . size ( ) - 1 ] -- ; } void countArrays ( vector < int > & arr , int X , int K ) { int xorVal = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) xorVal = xorVal ^ arr [ i ] ; countArraysUtil ( arr , X , K , xorVal ) ; cout << ans ; } int main ( ) { vector < int > arr = { 10 , 2 , 10 , 5 } ; int X = 3 , K = 3 ; countArrays ( arr , X , K ) ; return 0 ; }
Difference between maximum and minimum of a set of anagrams from an array | C ++ program for the above approach ; Utility function to find the hash value for each element of the given array ; Initialize an array with first 10 prime numbers ; Iterate over digits of N ; Update Hash Value ; Update N ; Function to find the set of anagrams in the array and print the difference between the maximum and minimum of these numbers ; Map to store the hash value and the array elements having that hash value ; Find the hash value for each arr [ i ] by calling hash function ; Iterate over the map ; If size of vector at m [ i ] greater than 1 then it must contain the anagrams ; Find the minimum and maximum element of this anagrams vector ; Display the difference ; If the end of Map is reached , then no anagrams are present ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hashFunction ( int N ) { int prime [ 10 ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 } ; int value = 1 , r ; while ( N != 0 ) { r = N % 10 ; value = value * prime [ r ] ; N = N / 10 ; } return value ; } void findDiff ( int arr [ ] , int n ) { map < int , vector < int > > m ; int h , min , max ; for ( int i = 0 ; i < n ; i ++ ) { h = hashFunction ( arr [ i ] ) ; m [ h ] . push_back ( arr [ i ] ) ; } for ( auto i = 0 ; i != m . size ( ) ; i ++ ) { if ( m [ i ] . size ( ) > 1 ) { min = * min_element ( m [ i ] . begin ( ) , m [ i ] . end ( ) ) ; max = * max_element ( m [ i ] . begin ( ) , m [ i ] . end ( ) ) ; cout << max - min ; break ; } else if ( i == m . size ( ) - 1 ) cout << -1 ; } } int main ( ) { int arr [ ] = { 121 , 312 , 234 , 211 , 112 , 102 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findDiff ( arr , N ) ; return 0 ; }
Maximum number of apples that can be eaten by a person | C ++ program of the above approach ; Function to find the maximum number of apples a person can eat such that the person eat at most one apple in a day . ; Stores count of apples and number of days those apples are edible ; Store count of apples and number of days those apples are edible ; Stores indices of the array ; Stores count of days ; Stores maximum count of edible apples ; Traverse both the arrays ; If top element of the apple is not already expired ; Insert count of apples and their expiration date ; Remove outdated apples ; Insert all the apples produces by tree on current day ; Stores top element of pq ; Remove top element of pq ; If count of apples in curr is greater than 0 ; Insert count of apples and their expiration date ; Update total_apples ; Update index ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntMaxApples ( vector < int > apples , vector < int > days ) { typedef pair < int , int > P ; priority_queue < P , vector < p > , greater < p > > pq ; int i = 0 ; int n = apples . size ( ) ; int total_apples = 0 ; while ( i < n || ! pq . empty ( ) ) { if ( i < n && apples [ i ] != 0 ) { pq . push ( { i + days [ i ] - 1 , apples [ i ] } ) ; } while ( ! pq . empty ( ) && pq . top ( ) . first < i ) { pq . pop ( ) ; } if ( ! pq . empty ( ) ) { auto curr = pq . top ( ) ; pq . pop ( ) ; if ( curr . second > 1 ) { pq . push ( { curr . first , curr . second - 1 } ) ; } ++ total_apples ; } ++ i ; } return total_apples ; } int main ( ) { vector < int > apples = { 1 , 2 , 3 , 5 , 2 } ; vector < int > days = { 3 , 2 , 1 , 4 , 2 } ; cout << cntMaxApples ( apples , days ) ; return 0 ; }
Maximum area rectangle by picking four sides from array | CPP program for finding maximum area possible of a rectangle ; function for finding max area ; sort array in non - increasing order ; Initialize two sides of rectangle ; traverse through array ; if any element occurs twice store that as dimension ; return the product of dimensions ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findArea ( int arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; int dimension [ 2 ] = { 0 , 0 } ; for ( int i = 0 , j = 0 ; i < n - 1 && j < 2 ; i ++ ) if ( arr [ i ] == arr [ i + 1 ] ) dimension [ j ++ ] = arr [ i ++ ] ; return ( dimension [ 0 ] * dimension [ 1 ] ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 1 , 4 , 6 , 6 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findArea ( arr , n ) ; return 0 ; }
Maximum of sum of length of rectangles and squares formed by given sticks | ; Function to find the maximum of sum of lengths of rectangles and squares formed using given set of sticks ; Stores the count of frequencies of all the array elements ; Stores frequencies which are at least 2 ; Convert all frequencies to nearest smaller even values . ; Sum of elements up to index of multiples of 4 ; Print the sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSumLength ( vector < int > arr , int n ) { map < int , int > freq ; for ( int i : arr ) freq [ i ] += 1 ; map < int , int > freq_2 ; for ( auto i : freq ) { if ( freq [ i . first ] >= 2 ) freq_2 [ i . first ] = freq [ i . first ] ; } vector < int > arr1 ; for ( auto i : freq_2 ) arr1 . push_back ( ( i . first ) * ( freq_2 [ ( i . first ) ] / 2 ) * 2 ) ; sort ( arr1 . begin ( ) , arr1 . end ( ) ) ; int summ = 0 ; for ( int i : arr1 ) summ += i ; cout << summ ; } int main ( ) { vector < int > arr = { 5 , 3 , 2 , 3 , 6 , 4 , 4 , 4 , 5 , 5 , 5 } ; int n = arr . size ( ) ; findSumLength ( arr , n ) ; return 0 ; }
Maximum area rectangle by picking four sides from array | CPP program for finding maximum area possible of a rectangle ; function for finding max area ; traverse through array ; If this is first occurrence of arr [ i ] , simply insert and continue ; If this is second ( or more ) occurrence , update first and second maximum values . ; return the product of dimensions ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findArea ( int arr [ ] , int n ) { unordered_set < int > s ; int first = 0 , second = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . find ( arr [ i ] ) == s . end ( ) ) { s . insert ( arr [ i ] ) ; continue ; } if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second ) second = arr [ i ] ; } return ( first * second ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 1 , 4 , 6 , 6 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findArea ( arr , n ) ; return 0 ; }
Print root to leaf paths without using recursion | C ++ program to Print root to leaf path WITHOUT using recursion ; A binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Function to print root to leaf path for a leaf using parent nodes stored in map ; start from leaf node and keep on pushing nodes into stack till root node is reached ; Start popping nodes from stack and print them ; An iterative function to do preorder traversal of binary tree and print root to leaf path without using recursion ; Corner Case ; Create an empty stack and push root to it ; Create a map to store parent pointers of binary tree nodes ; parent of root is NULL ; Pop all items one by one . Do following for every popped item a ) push its right child and set its parent pointer b ) push its left child and set its parent pointer Note that right child is pushed first so that left is processed first ; Pop the top item from stack ; If leaf node encountered , print Top To Bottom path ; Push right & left children of the popped node to stack . Also set their parent pointer in the map ; Driver program to test above functions ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } void printTopToBottomPath ( Node * curr , map < Node * , Node * > parent ) { stack < Node * > stk ; while ( curr ) { stk . push ( curr ) ; curr = parent [ curr ] ; } while ( ! stk . empty ( ) ) { curr = stk . top ( ) ; stk . pop ( ) ; cout << curr -> data << " ▁ " ; } cout << endl ; } void printRootToLeaf ( Node * root ) { if ( root == NULL ) return ; stack < Node * > nodeStack ; nodeStack . push ( root ) ; map < Node * , Node * > parent ; parent [ root ] = NULL ; while ( ! nodeStack . empty ( ) ) { Node * current = nodeStack . top ( ) ; nodeStack . pop ( ) ; if ( ! ( current -> left ) && ! ( current -> right ) ) printTopToBottomPath ( current , parent ) ; if ( current -> right ) { parent [ current -> right ] = current ; nodeStack . push ( current -> right ) ; } if ( current -> left ) { parent [ current -> left ] = current ; nodeStack . push ( current -> left ) ; } } } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 2 ) ; printRootToLeaf ( root ) ; return 0 ; }
Game of replacing array elements | CPP program for Game of Replacement ; Function return which player win the game ; Create hash that will stores all distinct element ; Traverse an array element ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int playGame ( int arr [ ] , int n ) { unordered_set < int > hash ; for ( int i = 0 ; i < n ; i ++ ) hash . insert ( arr [ i ] ) ; return ( hash . size ( ) % 2 == 0 ? 1 : 2 ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Player ▁ " << playGame ( arr , n ) << " ▁ Wins " << endl ; return 0 ; }
Length of longest strict bitonic subsequence | C ++ implementation to find length of longest strict bitonic subsequence ; function to find length of longest strict bitonic subsequence ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last / first element of that subsequence ; arrays to store the length of increasing and decreasing subsequences which end at them or start from them ; to store the length of longest strict bitonic subsequence ; traverse the array elements from left to right ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' inc ' ; update arr [ i ] subsequence length in ' inc ' and in len_inc [ ] ; traverse the array elements from right to left ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' dcr ' ; update arr [ i ] subsequence length in ' dcr ' and in len_dcr [ ] ; calculating the length of all the strict bitonic subsequence ; required longest length strict bitonic subsequence ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longLenStrictBitonicSub ( int arr [ ] , int n ) { unordered_map < int , int > inc , dcr ; int len_inc [ n ] , len_dcr [ n ] ; int longLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int len = 0 ; if ( inc . find ( arr [ i ] - 1 ) != inc . end ( ) ) len = inc [ arr [ i ] - 1 ] ; inc [ arr [ i ] ] = len_inc [ i ] = len + 1 ; } for ( int i = n - 1 ; i >= 0 ; i -- ) { int len = 0 ; if ( dcr . find ( arr [ i ] - 1 ) != dcr . end ( ) ) len = dcr [ arr [ i ] - 1 ] ; dcr [ arr [ i ] ] = len_dcr [ i ] = len + 1 ; } for ( int i = 0 ; i < n ; i ++ ) if ( longLen < ( len_inc [ i ] + len_dcr [ i ] - 1 ) ) longLen = len_inc [ i ] + len_dcr [ i ] - 1 ; return longLen ; } int main ( ) { int arr [ ] = { 1 , 5 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Longest ▁ length ▁ strict ▁ bitonic ▁ subsequence ▁ = ▁ " << longLenStrictBitonicSub ( arr , n ) ; return 0 ; }
Selection Sort VS Bubble Sort | ; Driver code
#include <iostream> NEW_LINE using namespace std ; void Selection_Sort ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; ++ i ) { int min_index = i ; for ( int j = i + 1 ; j < n ; ++ j ) { if ( arr [ j ] < arr [ min_index ] ) min_index = j ; } swap ( arr [ i ] , arr [ min_index ] ) ; } } int main ( ) { int n = 5 ; int arr [ 5 ] = { 2 , 0 , 1 , 4 , 3 } ; Selection_Sort ( arr , n ) ; cout << " The ▁ Sorted ▁ Array ▁ by ▁ using ▁ Selection ▁ Sort ▁ is ▁ : ▁ " ; for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Last seen array element ( last appearance is earliest ) | C ++ program to find last seen element in an array . ; Returns last seen element in arr [ ] ; Store last occurrence index of every element ; Find an element in hash with minimum index value ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lastSeenElement ( int a [ ] , int n ) { unordered_map < int , int > hash ; for ( int i = 0 ; i < n ; i ++ ) hash [ a [ i ] ] = i ; int res_ind = INT_MAX , res ; for ( auto x : hash ) { if ( x . second < res_ind ) { res_ind = x . second ; res = x . first ; } } return res ; } int main ( ) { int a [ ] = { 2 , 1 , 2 , 2 , 4 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << lastSeenElement ( a , n ) ; return 0 ; }
Selection Sort VS Bubble Sort | ; Driver code
#include <iostream> NEW_LINE using namespace std ; void Bubble_Sort ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; ++ i ) { for ( int j = 0 ; j <= ( n - i - 1 ) ; ++ j ) { if ( arr [ j ] > arr [ j + 1 ] ) swap ( arr [ j ] , arr [ j + 1 ] ) ; } } } int main ( ) { int n = 5 ; int arr [ 5 ] = { 2 , 0 , 1 , 4 , 3 } ; Bubble_Sort ( arr , n ) ; cout << " The ▁ Sorted ▁ Array ▁ by ▁ using ▁ Bubble ▁ Sort ▁ is ▁ : ▁ " ; for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Introduction to Arrays | ; Creating an integer array named arr of size 10. ; accessing element at 0 index and setting its value to 5. ; access and print value at 0 index we get the output as 5.
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int arr [ 10 ] ; arr [ 0 ] = 5 ; cout << arr [ 0 ] ; return 0 ; }
Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times | C ++ implementation of the above approach ; Function to find the minimum sum of array elements by given operations ; Base case ; Return 0 ; Base case ; Stores all the array elements in sorted order ; Traverse the array ; Insert current element into multiset ; Perform each operation ; Stores smallest element of ms ; Stores the largest element of ms ; Stores updated value of smallest element of ms by given operations ; Stores updated value of largest element of ms by given operations ; If the value of a + b less than the sum of smallest and largest array element ; Erase the smallest element ; Erase the largest element ; Insert the updated value of the smallest element ; Insert the updated value of the smallest element ; Stores sum of array elements ; Traverse the multiset ; Update ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimum_possible_sum ( int arr [ ] , int n , int k ) { if ( n == 0 ) { return 0 ; } if ( n == 1 ) { return arr [ 0 ] ; } multiset < int > ms ; for ( int i = 0 ; i < n ; i ++ ) { ms . insert ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; i ++ ) { int smallest_element = * ms . begin ( ) ; int largest_element = * ms . rbegin ( ) ; int a = smallest_element * 2 ; int b = largest_element / 2 ; if ( a + b < smallest_element + largest_element ) { ms . erase ( ms . begin ( ) ) ; ms . erase ( prev ( ms . end ( ) ) ) ; ms . insert ( a ) ; ms . insert ( b ) ; } } int ans = 0 ; for ( int x : ms ) { ans += x ; } return ans ; } int main ( ) { int arr [ ] = { 50 , 1 , 100 , 100 , 1 } ; int K = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimum_possible_sum ( arr , n , K ) ; return 0 ; }
Minimum cost required to connect all houses in a city | C ++ program for the above approach ; Utility function to find set of an element v using path compression technique ; If v is the parent ; Otherwise , recursively find its parent ; Function to perform union of the sets a and b ; Find parent of a and b ; If parent are different ; Swap Operation ; Update parent of b as a ; Otherwise , return 0 ; Function to create a Minimum Cost Spanning tree for given houses ; Stores adjacency list of graph ; Traverse each coordinate ; Find the Manhattan distance ; Add the edges ; Sort all the edges ; Initialize parent [ ] and size [ ] ; / Stores the minimum cost ; Finding the minimum cost ; Perform the unioun operation ; Print the minimum cost ; Driver Code ; Given houses ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > parent , size ; int find_set ( int v ) { if ( v == parent [ v ] ) return v ; return parent [ v ] = find_set ( parent [ v ] ) ; } int union_sets ( int a , int b ) { a = find_set ( a ) ; b = find_set ( b ) ; if ( a != b ) { if ( size [ a ] < size [ b ] ) swap ( a , b ) ; parent [ b ] = a ; size [ a ] += size [ b ] ; return 1 ; } return 0 ; } void MST ( int houses [ ] [ 2 ] , int n ) { vector < pair < int , pair < int , int > > > v ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int p = abs ( houses [ i ] [ 0 ] - houses [ j ] [ 0 ] ) ; p += abs ( houses [ i ] [ 1 ] - houses [ j ] [ 1 ] ) ; v . push_back ( { p , { i , j } } ) ; } } parent . resize ( n ) ; size . resize ( n ) ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { parent [ i ] = i , size [ i ] = 1 ; } int ans = 0 ; for ( auto x : v ) { if ( union_sets ( x . second . first , x . second . second ) ) { ans += x . first ; } } cout << ans ; } int main ( ) { int houses [ ] [ 2 ] = { { 0 , 0 } , { 2 , 2 } , { 3 , 10 } , { 5 , 2 } , { 7 , 0 } } ; int N = sizeof ( houses ) / sizeof ( houses [ 0 ] ) ; MST ( houses , N ) ; return 0 ; }
Lexicographically smallest subsequence possible by removing a character from given string | C ++ program for the above approach ; Function to find the lexicographically smallest subsequence of length N - 1 ; Store index of character to be deleted ; Traverse the string ; If ith character > ( i + 1 ) th character then store it ; If any character found in non alphabetical order then remove it ; Otherwise remove last character ; Print the resultant subsequence ; Driver Code ; Given string S ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void firstSubsequence ( string s ) { int isMax = -1 ; for ( int i = 0 ; i < s . length ( ) - 1 ; i ++ ) { if ( s [ i ] > s [ i + 1 ] ) { isMax = i ; break ; } } if ( isMax >= 0 ) { s . erase ( isMax , 1 ) ; } else { s . erase ( s . length ( ) - 1 , 1 ) ; } cout << s ; } int main ( ) { string S = " geeksforgeeks " ; firstSubsequence ( S ) ; return 0 ; }
Maximize product of array by replacing array elements with its sum or product with element from another array | C ++ program for the above approach ; Function to find the largest product of array A [ ] ; Base Case ; Store all the elements of the array A [ ] ; Sort the Array B [ ] ; Traverse the array B [ ] ; Pop minimum element ; Check which operation is producing maximum element ; Insert resultant element into the priority queue ; Evaluate the product of the elements of A [ ] ; Return the maximum product ; Driver Code ; Given arrays ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largeProduct ( vector < int > A , vector < int > B , int N ) { if ( N == 0 ) return 0 ; priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 0 ; i < N ; i ++ ) pq . push ( A [ i ] ) ; sort ( B . begin ( ) , B . end ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { int minn = pq . top ( ) ; pq . pop ( ) ; int maximized_element = max ( minn * B [ i ] , minn + B [ i ] ) ; pq . push ( maximized_element ) ; } int max_product = 1 ; while ( pq . size ( ) > 0 ) { max_product *= pq . top ( ) ; pq . pop ( ) ; } return max_product ; } int main ( ) { vector < int > A = { 1 , 1 , 10 } ; vector < int > B = { 1 , 1 , 1 } ; int N = 3 ; cout << largeProduct ( A , B , N ) ; }
Print all root to leaf paths with there relative positions | C ++ program to print all root to leaf paths with there relative position ; tree structure ; function create new node ; store path information ; Prints given root to leaf path with underscores ; Find the minimum horizontal distance value in current root to leaf path ; find minimum horizontal distance ; print the root to leaf path with " _ " that indicate the related position ; current tree node ; print underscore ; print current key ; a utility function print all path from root to leaf working of this function is similar to function of " Print _ vertical _ order " : Print paths of binary tree in vertical order www . geeksforgeeks . org / print - binary - tree - vertical - order - set - 2 / https : ; base case ; leaf node ; add leaf node and then print path ; store current path information ; call left sub_tree ; call left sub_tree ; base case ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_PATH_SIZE 1000 NEW_LINE struct Node { char data ; Node * left , * right ; } ; Node * newNode ( char data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } struct PATH { int Hd ; char key ; } ; void printPath ( vector < PATH > path , int size ) { int minimum_Hd = INT_MAX ; PATH p ; for ( int it = 0 ; it < size ; it ++ ) { p = path [ it ] ; minimum_Hd = min ( minimum_Hd , p . Hd ) ; } for ( int it = 0 ; it < size ; it ++ ) { p = path [ it ] ; int noOfUnderScores = abs ( p . Hd - minimum_Hd ) ; for ( int i = 0 ; i < noOfUnderScores ; i ++ ) cout << " _ ▁ " ; cout << p . key << endl ; } cout << " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " << endl ; } void printAllPathsUtil ( Node * root , vector < PATH > & AllPath , int HD , int order ) { if ( root == NULL ) return ; if ( root -> left == NULL && root -> right == NULL ) { AllPath [ order ] = ( PATH { HD , root -> data } ) ; printPath ( AllPath , order + 1 ) ; return ; } AllPath [ order ] = ( PATH { HD , root -> data } ) ; printAllPathsUtil ( root -> left , AllPath , HD - 1 , order + 1 ) ; printAllPathsUtil ( root -> right , AllPath , HD + 1 , order + 1 ) ; } void printAllPaths ( Node * root ) { if ( root == NULL ) return ; vector < PATH > Allpaths ( MAX_PATH_SIZE ) ; printAllPathsUtil ( root , Allpaths , 0 , 0 ) ; } int main ( ) { Node * root = newNode ( ' A ' ) ; root -> left = newNode ( ' B ' ) ; root -> right = newNode ( ' C ' ) ; root -> left -> left = newNode ( ' D ' ) ; root -> left -> right = newNode ( ' E ' ) ; root -> right -> left = newNode ( ' F ' ) ; root -> right -> right = newNode ( ' G ' ) ; printAllPaths ( root ) ; return 0 ; }
Minimum steps required to rearrange given array to a power sequence of 2 | C ++ program to implement the above approach ; Function to calculate the minimum steps required to convert given array into a power sequence of 2 ; Sort the array in ascending order ; Calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minsteps ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += abs ( arr [ i ] - pow ( 2 , i ) ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 8 , 2 , 10 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minsteps ( arr , n ) << endl ; return 0 ; }
Block swap algorithm for array rotation | ; Prototype for utility functions ; Return If number of elements to be rotated is zero or equal to array size ; If number of elements to be rotated is exactly half of array size ; If A is shorter ; If B is shorter ; function to print an array ; This function swaps d elements starting at index fi with d elements starting at index si ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArray ( int arr [ ] , int size ) ; void swap ( int arr [ ] , int fi , int si , int d ) ; void leftRotate ( int arr [ ] , int d , int n ) { if ( d == 0 d == n ) return ; if ( n - d == d ) { swap ( arr , 0 , n - d , d ) ; return ; } if ( d < n - d ) { swap ( arr , 0 , n - d , d ) ; leftRotate ( arr , d , n - d ) ; } else { swap ( arr , 0 , d , n - d ) ; leftRotate ( arr + n - d , 2 * d - n , d ) ; } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } void swap ( int arr [ ] , int fi , int si , int d ) { int i , temp ; for ( i = 0 ; i < d ; i ++ ) { temp = arr [ fi + i ] ; arr [ fi + i ] = arr [ si + i ] ; arr [ si + i ] = temp ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; leftRotate ( arr , 2 , 7 ) ; printArray ( arr , 7 ) ; return 0 ; }
Cost required to empty a given array by repeated removal of maximum obtained by given operations | C ++ program for the above approach ; Function to find the total cost of removing all array elements ; Sort the array in descending order ; Stores the total cost ; Contribution of i - th greatest element to the cost ; Remove the element ; If negative ; Add to the final cost ; Return the cost ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCost ( int * a , int n ) { sort ( a , a + n , greater < int > ( ) ) ; int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int p = a [ j ] - j ; a [ j ] = 0 ; if ( p < 0 ) { p = 0 ; continue ; } count += p ; } return count ; } int main ( ) { int arr [ ] = { 1 , 6 , 7 , 4 , 2 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCost ( arr , N ) ; return 0 ; }
Block swap algorithm for array rotation | C ++ code for above implementation ; A is shorter ; B is shorter ; Finally , block swap A and B
void leftRotate ( int arr [ ] , int d , int n ) { int i , j ; if ( d == 0 d == n ) return ; i = d ; j = n - d ; while ( i != j ) { if ( i < j ) { swap ( arr , d - i , d + j - i , i ) ; j -= i ; } else { swap ( arr , d - i , d , j ) ; i -= j ; } } swap ( arr , d - i , d , i ) ; }
Count of index pairs with equal elements in an array | Set 2 | C ++ program for the above approach ; Function that count the pairs having same elements in the array arr [ ] ; Hash map to keep track of occurences of elements ; Traverse the array arr [ ] ; Check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; Return the result ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int ans = 0 ; unordered_map < int , int > count ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ arr [ i ] ] != 0 ) ans += count [ arr [ i ] ] ; count [ arr [ i ] ] ++ ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }
Maximize shortest path between given vertices by adding a single edge | C ++ program for the above approach ; To store graph as adjacency list ; To store the shortest path ; Function that performs BFS Traversal ; Fill initially each distance as INF ; Perform BFS ; Traverse the current edges ; Update the distance ; Insert in queue ; Function that maximizes the shortest path between source and destination vertex by adding a single edge between given selected nodes ; To update the shortest distance between node 1 to other vertices ; To update the shortest distance between node N to other vertices ; Store the values x [ i ] - y [ i ] ; Sort all the vectors of pairs ; Traverse data [ ] ; Maximize x [ a ] - y [ b ] ; Print minimum cost ; Driver Code ; Given nodes and edges ; Sort the selected nodes ; Given edges ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int INF = 1e9 + 7 ; int N , M ; vector < int > edges [ 200005 ] ; int dist [ 2 ] [ 200000 ] ; void bfs ( int * dist , int s ) { int q [ 200000 ] ; fill ( dist , dist + N , INF ) ; int qh = 0 , qt = 0 ; q [ qh ++ ] = s ; dist [ s ] = 0 ; while ( qt < qh ) { int x = q [ qt ++ ] ; for ( int y : edges [ x ] ) { if ( dist [ y ] == INF ) { dist [ y ] = dist [ x ] + 1 ; q [ qh ++ ] = y ; } } } } void shortestPathCost ( int selected [ ] , int K ) { vector < pair < int , int > > data ; bfs ( dist [ 0 ] , 0 ) ; bfs ( dist [ 1 ] , N - 1 ) ; for ( int i = 0 ; i < K ; i ++ ) { data . emplace_back ( dist [ 0 ] [ selected [ i ] ] - dist [ 1 ] [ selected [ i ] ] , selected [ i ] ) ; } sort ( data . begin ( ) , data . end ( ) ) ; int best = 0 ; int MAX = - INF ; for ( auto it : data ) { int a = it . second ; best = max ( best , MAX + dist [ 1 ] [ a ] ) ; MAX = max ( MAX , dist [ 0 ] [ a ] ) ; } printf ( " % d STRNEWLINE " , min ( dist [ 0 ] [ N - 1 ] , best + 1 ) ) ; } int main ( ) { N = 5 , M = 4 ; int K = 2 ; int selected [ ] = { 1 , 3 } ; sort ( selected , selected + K ) ; edges [ 0 ] . push_back ( 1 ) ; edges [ 1 ] . push_back ( 0 ) ; edges [ 1 ] . push_back ( 2 ) ; edges [ 2 ] . push_back ( 1 ) ; edges [ 2 ] . push_back ( 3 ) ; edges [ 3 ] . push_back ( 2 ) ; edges [ 3 ] . push_back ( 4 ) ; edges [ 4 ] . push_back ( 3 ) ; shortestPathCost ( selected , K ) ; return 0 ; }
Program to cyclically rotate an array by one | ; i and j pointing to first and last element respectively ; Driver code
#include <iostream> NEW_LINE using namespace std ; void rotate ( int arr [ ] , int n ) { int i = 0 , j = n - 1 ; while ( i != j ) { swap ( arr [ i ] , arr [ j ] ) ; i ++ ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } , i ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given ▁ array ▁ is ▁ STRNEWLINE " ; for ( i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; rotate ( arr , n ) ; cout << " Rotated array is " ; for ( i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Minimum cost to empty Array where cost of removing an element is 2 ^ ( removed_count ) * arr [ i ] | C ++ implementation to find the minimum cost of removing all elements from the array ; Function to find the minimum cost of removing elements from the array ; Sorting in Increasing order ; Loop to find the minimum cost of removing elements ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int removeElements ( ll arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; ll ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += arr [ i ] * pow ( 2 , i ) ; } return ans ; } int main ( ) { int n = 4 ; ll arr [ n ] = { 3 , 1 , 2 , 3 } ; cout << removeElements ( arr , n ) ; }
Sorting boundary elements of a matrix | C ++ program for the above approach ; Appending border elements ; Sorting the list ; Printing first row with first N elements from A ; Printing N - 2 rows ; Print elements from last ; Print middle elements from original matrix ; Print elements from front ; Printing last row ; Driver Code ; Dimensions of a Matrix ; Given Matrix ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMatrix ( int grid [ ] [ 5 ] , int m , int n ) { vector < int > A ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( j == n - 1 || ( i == m - 1 ) j == 0 i == 0 ) A . push_back ( grid [ i ] [ j ] ) ; } } sort ( A . begin ( ) , A . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) cout << A [ i ] << " ▁ " ; cout << endl ; for ( int i = 0 ; i < m - 2 ; i ++ ) { cout << A [ A . size ( ) - i - 1 ] << " ▁ " ; for ( int j = 1 ; j < n - 1 ; j ++ ) cout << grid [ i + 1 ] [ j ] << " ▁ " ; cout << ( A [ n + i ] ) << endl ; } reverse ( A . begin ( ) + n + m - 2 , A . begin ( ) + n + m + n - 2 ) ; for ( int i = n + m - 2 ; i < n + m - 2 + n ; i ++ ) cout << A [ i ] << " ▁ " ; [ n + m - 2 : n + m - 2 + n ] << endl ; } int main ( ) { int m = 4 , n = 5 ; int grid [ ] [ 5 ] = { { 1 , 2 , 3 , 4 , 0 } , { 1 , 1 , 1 , 1 , 2 } , { 1 , 2 , 2 , 2 , 4 } , { 1 , 9 , 3 , 1 , 7 } } ; printMatrix ( grid , m , n ) ; return 0 ; }
Flattening a linked list | Set 2 | C ++ program for Flattening a linked list using Heaps ; Structure of given Linked list ; Function to print the linked list ; Function that compares the value pointed by node and returns true if first data is greater ; Function which returns the root of the flattened linked list ; Min Heap which will return smallest element currently present in heap ; Push the head nodes of each downward linked list ; This loop will execute till the map becomes empty ; Pop out the node that contains element currently in heap ; Push the next node pointed by the current node into heap if it is not null ; Create new linked list that is to be returned ; Pointer to head node in the linked list ; Create and push new nodes ; Driver Code ; Given Linked List ; Flatten the list ; Print the flattened linked list
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * right ; struct Node * down ; Node ( int x ) { data = x ; right = NULL ; down = NULL ; } } ; void printList ( Node * Node ) { while ( Node != NULL ) { printf ( " % d ▁ " , Node -> data ) ; Node = Node -> down ; } } struct compare { bool operator() ( Node * a , Node * b ) { return a -> data > b -> data ; } } ; Node * flatten ( Node * root ) { Node * ptr = root ; Node * head = NULL ; priority_queue < Node * , vector < Node * > , compare > pq ; while ( ptr != NULL ) { pq . push ( ptr ) ; ptr = ptr -> right ; } while ( ! pq . empty ( ) ) { Node * temp = pq . top ( ) ; pq . pop ( ) ; if ( temp -> down != NULL ) { pq . push ( temp -> down ) ; } if ( head == NULL ) { head = temp ; ptr = temp ; ptr -> right = NULL ; } else { ptr -> down = temp ; ptr = temp ; ptr -> right = NULL ; } } return head ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = ( Node * ) malloc ( sizeof ( Node ) ) ; new_node -> right = NULL ; new_node -> data = new_data ; new_node -> down = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { Node * root = NULL ; push ( & root , 30 ) ; push ( & root , 8 ) ; push ( & root , 7 ) ; push ( & root , 5 ) ; push ( & ( root -> right ) , 20 ) ; push ( & ( root -> right ) , 10 ) ; push ( & ( root -> right -> right ) , 50 ) ; push ( & ( root -> right -> right ) , 22 ) ; push ( & ( root -> right -> right ) , 19 ) ; push ( & ( root -> right -> right -> right ) , 45 ) ; push ( & ( root -> right -> right -> right ) , 40 ) ; push ( & ( root -> right -> right -> right ) , 35 ) ; push ( & ( root -> right -> right -> right ) , 20 ) ; root = flatten ( root ) ; printList ( root ) ; return 0 ; }
Lexicographically largest string possible in one swap | C ++ implementation to find the lexicographically largest string by atmost at most one swap ; Function to return the lexicographically largest string possible by swapping at most one character ; Stores last occurrence of every character ; Initialize with - 1 for every character ; Keep updating the last occurrence of each character ; If a previously unvisited character occurs ; Stores the sorted string ; Character to replace ; Find the last occurrence of this character ; Swap this with the last occurrence ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findLargest ( string s ) { int len = s . size ( ) ; int loccur [ 26 ] ; memset ( loccur , -1 , sizeof ( loccur ) ) ; for ( int i = len - 1 ; i >= 0 ; -- i ) { int chI = s [ i ] - ' a ' ; if ( loccur [ chI ] == -1 ) { loccur [ chI ] = i ; } } string sorted_s = s ; sort ( sorted_s . begin ( ) , sorted_s . end ( ) , greater < int > ( ) ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( s [ i ] != sorted_s [ i ] ) { int chI = sorted_s [ i ] - ' a ' ; int last_occ = loccur [ chI ] ; swap ( s [ i ] , s [ last_occ ] ) ; break ; } } return s ; } int main ( ) { string s = " yrstvw " ; cout << findLargest ( s ) ; return 0 ; }
Given a sorted and rotated array , find if there is a pair with a given sum | C ++ program to find a pair with a given sum in a sorted and rotated array ; This function returns true if arr [ 0. . n - 1 ] has a pair with sum equals to x . ; Find the pivot element ; l is now index of smallest element ; r is now index of largest element ; Keep moving either l or r till they meet ; If we find a pair with sum x , we return true ; If current pair sum is less , move to the higher sum ; Move to the lower sum side ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; bool pairInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) return true ; if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return false ; } int main ( ) { int arr [ ] = { 11 , 15 , 6 , 8 , 9 , 10 } ; int sum = 16 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( pairInSortedRotated ( arr , n , sum ) ) cout << " Array ▁ has ▁ two ▁ elements ▁ with ▁ sum ▁ 16" ; else cout << " Array ▁ doesn ' t ▁ have ▁ two ▁ elements ▁ with ▁ sum ▁ 16 ▁ " ; return 0 ; }
Given a sorted and rotated array , find if there is a pair with a given sum | C ++ program to find number of pairs with a given sum in a sorted and rotated array . ; This function returns count of number of pairs with sum equals to x . ; Find the pivot element . Pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; Variable to store count of number of pairs . ; Find sum of pair formed by arr [ l ] and and arr [ r ] and update l , r and cnt accordingly . ; If we find a pair with sum x , then increment cnt , move l and r to next element . ; This condition is required to be checked , otherwise l and r will cross each other and loop will never terminate . ; If current pair sum is less , move to the higher sum side . ; If current pair sum is greater , move to the lower sum side . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pairsInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; int cnt = 0 ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) { cnt ++ ; if ( l == ( r - 1 + n ) % n ) { return cnt ; } l = ( l + 1 ) % n ; r = ( r - 1 + n ) % n ; } else if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return cnt ; } int main ( ) { int arr [ ] = { 11 , 15 , 6 , 7 , 9 , 10 } ; int sum = 16 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << pairsInSortedRotated ( arr , n , sum ) ; return 0 ; }
Find maximum value of Sum ( i * arr [ i ] ) with only rotations on given array allowed | C ++ program to find max value of i * arr [ i ] ; Returns max possible value of i * arr [ i ] ; Find array sum and i * arr [ i ] with no rotation Stores sum of arr [ i ] ; Stores sum of i * arr [ i ] ; Initialize result as 0 rotation sum ; Try all rotations one by one and find the maximum rotation sum . ; Return result ; Driver program
#include <iostream> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n ) { int arrSum = 0 ; int currVal = 0 ; for ( int i = 0 ; i < n ; i ++ ) { arrSum = arrSum + arr [ i ] ; currVal = currVal + ( i * arr [ i ] ) ; } int maxVal = currVal ; for ( int j = 1 ; j < n ; j ++ ) { currVal = currVal + arrSum - n * arr [ n - j ] ; if ( currVal > maxVal ) maxVal = currVal ; } return maxVal ; } int main ( void ) { int arr [ ] = { 10 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Max sum is " return 0 ; }
Print the nodes at odd levels of a tree | Recursive C ++ program to print odd level nodes ; If empty tree ; If current node is of odd level ; Recur for children with isOdd switched . ; Utility method to create a node ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; void printOddNodes ( Node * root , bool isOdd = true ) { if ( root == NULL ) return ; if ( isOdd ) cout << root -> data << " ▁ " ; printOddNodes ( root -> left , ! isOdd ) ; printOddNodes ( root -> right , ! isOdd ) ; } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = 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 ) ; printOddNodes ( root ) ; return 0 ; }
Maximum sum of i * arr [ i ] among all rotations of a given array | A Naive C ++ program to find maximum sum rotation ; Returns maximum value of i * arr [ i ] ; Initialize result ; Consider rotation beginning with i for all possible values of i . ; Initialize sum of current rotation ; Compute sum of all values . We don 't acutally rotation the array, but compute sum by finding ndexes when arr[i] is first element ; Update result if required ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n ) { int res = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { int curr_sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int index = ( i + j ) % n ; curr_sum += j * arr [ index ] ; } res = max ( res , curr_sum ) ; } return res ; } int main ( ) { int arr [ ] = { 8 , 3 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) << endl ; return 0 ; }
Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient C ++ program to compute maximum sum of i * arr [ i ] ; Compute sum of all array elements ; Compute sum of i * arr [ i ] for initial configuration . ; Initialize result ; Compute values for other iterations ; Compute next value using previous value in O ( 1 ) time ; Update current value ; Update result if required ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n ) { int cum_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) cum_sum += arr [ i ] ; int curr_val = 0 ; for ( int i = 0 ; i < n ; i ++ ) curr_val += i * arr [ i ] ; int res = curr_val ; for ( int i = 1 ; i < n ; i ++ ) { int next_val = curr_val - ( cum_sum - arr [ i - 1 ] ) + arr [ i - 1 ] * ( n - 1 ) ; curr_val = next_val ; res = max ( res , next_val ) ; } return res ; } int main ( ) { int arr [ ] = { 8 , 3 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) << endl ; return 0 ; }
Minimum time required to cover a Binary Array | CPP implementation to find the Minimum time required to cover a Binary Array ; function to calculate the time ; Map to mark or store the binary values ; Firstly fill the boolean array with all zeroes ; Mark the 1 s ; Number of 0 s until first '1' occurs ; Maximum Number of 0 s in between 2 '1' s . ; Number of 0 s from right until first '1' occurs ; Return maximum from left and right segment ; check if count is odd ; check ifcount is even ; return the time ; driver code ; initialise N ; array initialisation
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( vector < int > arr , int n ) { int k = arr . size ( ) ; bool mp [ n + 2 ] ; for ( int i = 0 ; i <= n ; i ++ ) { mp [ i ] = 0 ; } for ( int i = 0 ; i < k ; i ++ ) { mp [ arr [ i ] ] = 1 ; } int leftSegment = arr [ 0 ] - 1 ; for ( int i = 1 ; i < k ; i ++ ) { leftSegment = max ( leftSegment , arr [ i ] - arr [ i - 1 ] - 1 ) ; } int rightSegment = n - arr [ k - 1 ] ; int maxSegment = max ( leftSegment , rightSegment ) ; int tim ; if ( maxSegment & 1 ) tim = ( maxSegment / 2 ) + 1 ; else tim = maxSegment / 2 ; return tim ; } int main ( ) { int N = 5 ; vector < int > arr = { 1 , 4 } ; cout << solve ( arr , N ) ; }
Find the Rotation Count in Rotated Sorted array | C ++ program to find number of rotations in a sorted and rotated array . ; Returns count of rotations for an array which is first sorted in ascending order , then rotated ; We basically find index of minimum element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotations ( int arr [ ] , int n ) { int min = arr [ 0 ] , min_index ; for ( int i = 0 ; i < n ; i ++ ) { if ( min > arr [ i ] ) { min = arr [ i ] ; min_index = i ; } } return min_index ; } int main ( ) { int arr [ ] = { 15 , 18 , 2 , 3 , 6 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countRotations ( arr , n ) ; return 0 ; }
Find the Rotation Count in Rotated Sorted array | Binary Search based C ++ program to find number of rotations in a sorted and rotated array . ; Returns count of rotations for an array which is first sorted in ascending order , then rotated ; This condition is needed to handle the case when the array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum element . Consider the cases like { 3 , 4 , 5 , 1 , 2 } ; Check if mid itself is minimum element ; Decide whether we need to go to left half or right half ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotations ( int arr [ ] , int low , int high ) { if ( high < low ) return 0 ; if ( high == low ) return low ; int mid = low + ( high - low ) / 2 ; if ( mid < high && arr [ mid + 1 ] < arr [ mid ] ) return ( mid + 1 ) ; if ( mid > low && arr [ mid ] < arr [ mid - 1 ] ) return mid ; if ( arr [ high ] > arr [ mid ] ) return countRotations ( arr , low , mid - 1 ) ; return countRotations ( arr , mid + 1 , high ) ; } int main ( ) { int arr [ ] = { 15 , 18 , 2 , 3 , 6 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countRotations ( arr , 0 , n - 1 ) ; return 0 ; }
Quickly find multiple left rotations of an array | Set 1 | CPP implementation of left rotation of an array K number of times ; Fills temp [ ] with two copies of arr [ ] ; Store arr [ ] elements at i and i + n ; Function to left rotate an array k times ; Starting position of array after k rotations in temp [ ] will be k % n ; Print array after k rotations ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void preprocess ( int arr [ ] , int n , int temp [ ] ) { for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = temp [ i + n ] = arr [ i ] ; } void leftRotate ( int arr [ ] , int n , int k , int temp [ ] ) { int start = k % n ; for ( int i = start ; i < start + n ; i ++ ) cout << temp [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int temp [ 2 * n ] ; preprocess ( arr , n , temp ) ; int k = 2 ; leftRotate ( arr , n , k , temp ) ; k = 3 ; leftRotate ( arr , n , k , temp ) ; k = 4 ; leftRotate ( arr , n , k , temp ) ; return 0 ; }
Arrange the array such that upon performing given operations an increasing order is obtained | C ++ program to find the desired output after performing given operations ; Function to arrange array in such a way that after performing given operation We get increasing sorted array ; Size of given array ; Sort the given array ; Start erasing last element and place it at ith index ; While we reach at starting ; Store last element ; Shift all elements by 1 position in right ; insert last element at ith position ; print desired Array ; Driver Code ; Given Array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Desired_Array ( vector < int > & v ) { int n = v . size ( ) ; sort ( v . begin ( ) , v . end ( ) ) ; int i = n - 1 ; while ( i > 0 ) { int p = v [ n - 1 ] ; for ( int j = n - 1 ; j >= i ; j -- ) { v [ j + 1 ] = v [ j ] ; } v [ i ] = p ; i -- ; } for ( auto x : v ) cout << x << " ▁ " ; cout << " STRNEWLINE " ; } int main ( ) { vector < int > v = { 1 , 2 , 3 , 4 , 5 } ; Desired_Array ( v ) ; vector < int > v1 = { 1 , 12 , 2 , 10 , 4 , 16 , 6 } ; Desired_Array ( v1 ) ; return 0 ; }
Quickly find multiple left rotations of an array | Set 1 | CPP implementation of left rotation of an array K number of times ; Function to left rotate an array k times ; Print array after k rotations ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void leftRotate ( int arr [ ] , int n , int k ) { for ( int i = k ; i < k + n ; i ++ ) cout << arr [ i % n ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; leftRotate ( arr , n , k ) ; cout << endl ; k = 3 ; leftRotate ( arr , n , k ) ; cout << endl ; k = 4 ; leftRotate ( arr , n , k ) ; cout << endl ; return 0 ; }
How to sort an array in a single loop ? | C ++ code to sort an array of integers with the help of single loop ; Function for Sorting the array using a single loop ; Sorting using a single loop ; Checking the condition for two simultaneous elements of the array ; Swapping the elements . ; updating the value of j = - 1 so after getting updated for j ++ in the loop it becomes 0 and the loop begins from the start . ; Driver code ; Declaring an integer array of size 11. ; Printing the original Array . ; Sorting the array using a single loop ; Printing the sorted array .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int * sortArrays ( int arr [ ] , int length ) { for ( int j = 0 ; j < length - 1 ; j ++ ) { if ( arr [ j ] > arr [ j + 1 ] ) { int temp = arr [ j ] ; arr [ j ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; j = -1 ; } } return arr ; } int main ( ) { int arr [ ] = { 1 , 2 , 99 , 9 , 8 , 7 , 6 , 0 , 5 , 4 , 3 } ; int length = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string str ; for ( int i : arr ) { str += to_string ( i ) + " ▁ " ; } cout << " Original ▁ array : ▁ [ " << str << " ] " << endl ; int * arr1 ; arr1 = sortArrays ( arr , length ) ; string str1 ; for ( int i = 0 ; i < length ; i ++ ) { str1 += to_string ( arr1 [ i ] ) + " ▁ " ; } cout << " Sorted ▁ array : ▁ [ " << ( str1 ) << " ] " ; }
How to sort an array in a single loop ? | C ++ code to sort an array of Strings with the help of single loop ; Function for Sorting the array using a single loop ; Sorting using a single loop ; Type Conversion of char to int . ; Comparing the ascii code . ; Swapping of the characters ; Driver code ; Declaring a String ; declaring character array ; copying the contents of the string to char array ; Printing the original Array . ; Sorting the array using a single loop ; Printing the sorted array .
#include <bits/stdc++.h> NEW_LINE using namespace std ; char * sortArrays ( char arr [ ] , int length ) { for ( int j = 0 ; j < length - 1 ; j ++ ) { int d1 = arr [ j ] ; int d2 = arr [ j + 1 ] ; if ( d1 > d2 ) { char temp = arr [ j ] ; arr [ j ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; j = -1 ; } } return arr ; } int main ( ) { string geeks = " GEEKSFORGEEKS " ; int n = geeks . length ( ) ; char arr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = geeks [ i ] ; } cout << " Original ▁ array : ▁ [ " ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] ; if ( i + 1 != n ) cout << " , ▁ " ; } cout << " ] " << endl ; char * ansarr ; ansarr = sortArrays ( arr , n ) ; cout << " Sorted ▁ array : ▁ [ " ; for ( int i = 0 ; i < n ; i ++ ) { cout << ansarr [ i ] ; if ( i + 1 != n ) cout << " , ▁ " ; } cout << " ] " << endl ; }
Check if value exists in level | C ++ implementation of the approach ; Class containing left and right child of current node and key value ; Function to locate which level to check for the existence of key . ; If the key is less than the root , it will certainly not exist in the tree because tree is level - order sorted ; If the key is equal to the root then simply return 0 ( zero 'th level) ; If the key is found in any leftmost element then simply return true No need for any extra searching ; If key lies between the root data and the left child 's data OR if key is greater than root data and there is no level underneath it, return the current level ; Function to traverse a binary encoded path and return the value encountered after traversal . ; Go left ; Incomplete path ; Go right ; Incomplete path ; Return the data at the node ; Function to generate gray code of corresponding binary number of integer i ; Create new arraylist to store the gray code ; Reverse the encoding till here ; Leftmost digits are filled with 0 ; Function to search the key in a particular level of the tree . ; Find the middle index ; Encode path from root to this index in the form of 0 s and 1 s where 0 means LEFT and 1 means RIGHT ; Traverse the path in the tree and check if the key is found ; If path is incomplete ; Check the left part of the level ; Check the right part of the level ; Check the left part of the level ; Key not found in that level ; Function that returns true if the key is found in the tree ; Find the level where the key may lie ; If level is - 1 then return false ; If level is - 2 i . e . key was found in any leftmost element then simply return true ; Apply binary search on the elements of that level ; Driver code ; Consider the following level - order sorted tree 5 / \ 8 10 / \ / \ 13 23 25 30 / \ / 32 40 50 ; Keys to be searched
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left , * right ; Node ( int item ) { data = item ; left = right = NULL ; } } ; int findLevel ( Node * root , int data ) { if ( data < root -> data ) return -1 ; if ( data == root -> data ) return 0 ; int cur_level = 0 ; while ( true ) { cur_level ++ ; root = root -> left ; if ( root -> data == data ) return -2 ; if ( root -> data < data && ( root -> left == NULL root -> left -> data > data ) ) { break ; } } return cur_level ; } int traversePath ( Node * root , vector < int > path ) { for ( int i = 0 ; i < path . size ( ) ; i ++ ) { int direction = path [ i ] ; if ( direction == 0 ) { if ( root -> left == NULL ) return -1 ; root = root -> left ; } else { if ( root -> right == NULL ) return -1 ; root = root -> right ; } } return root -> data ; } vector < int > generateGray ( int n , int x ) { vector < int > gray ; int i = 0 ; while ( x > 0 ) { gray . push_back ( x % 2 ) ; x = x / 2 ; i ++ ; } reverse ( gray . begin ( ) , gray . end ( ) ) ; for ( int j = 0 ; j < n - i ; j ++ ) gray . insert ( gray . begin ( ) , 0 ) ; return gray ; } bool binarySearch ( Node * root , int start , int end , int data , int level ) { if ( end >= start ) { int mid = ( start + end ) / 2 ; vector < int > encoding = generateGray ( level , mid ) ; int element_found = traversePath ( root , encoding ) ; if ( element_found == -1 ) return binarySearch ( root , start , mid - 1 , data , level ) ; if ( element_found == data ) return true ; if ( element_found < data ) return binarySearch ( root , mid + 1 , end , data , level ) ; else return binarySearch ( root , start , mid - 1 , data , level ) ; } return false ; } bool findKey ( Node * root , int data ) { int level = findLevel ( root , data ) ; if ( level == -1 ) return false ; if ( level == -2 ) return true ; return binarySearch ( root , 0 , ( int ) pow ( 2 , level ) - 1 , data , level ) ; } int main ( ) { Node * root = new Node ( 5 ) ; root -> left = new Node ( 8 ) ; root -> right = new Node ( 10 ) ; root -> left -> left = new Node ( 13 ) ; root -> left -> right = new Node ( 23 ) ; root -> right -> left = new Node ( 25 ) ; root -> right -> right = new Node ( 30 ) ; root -> left -> left -> left = new Node ( 32 ) ; root -> left -> left -> right = new Node ( 40 ) ; root -> left -> right -> left = new Node ( 50 ) ; int arr [ ] = { 5 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( findKey ( root , arr [ i ] ) ) cout << ( " Yes " ) << endl ; else cout << ( " No " ) << endl ; } }
Reversal algorithm for right rotation of an array | C ++ program for right rotation of an array ( Reversal Algorithm ) ; Function to reverse arr [ ] from index start to end ; Function to right rotate arr [ ] of size n by d ; function to print an array ; driver code
#include <bits/stdc++.h> NEW_LINE void reverseArray ( int arr [ ] , int start , int end ) { while ( start < end ) { std :: swap ( arr [ start ] , arr [ end ] ) ; start ++ ; end -- ; } } void rightRotate ( int arr [ ] , int d , int n ) { reverseArray ( arr , 0 , n - 1 ) ; reverseArray ( arr , 0 , d - 1 ) ; reverseArray ( arr , d , n - 1 ) ; } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) std :: cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; rightRotate ( arr , k , n ) ; printArray ( arr , n ) ; return 0 ; }
Print the nodes at odd levels of a tree | Iterative C ++ program to print odd level nodes ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue root and initialize level as odd ; nodeCount ( queue size ) indicates number of nodes at current level . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Utility method to create a node ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; void printOddNodes ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; bool isOdd = true ; while ( 1 ) { int nodeCount = q . size ( ) ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { Node * node = q . front ( ) ; if ( isOdd ) cout << node -> data << " ▁ " ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; nodeCount -- ; } isOdd = ! isOdd ; } } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = 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 ) ; printOddNodes ( root ) ; return 0 ; }
Find a rotation with maximum hamming distance | C ++ program to Find another array such that the hamming distance from the original array is maximum ; Return the maximum hamming distance of a rotation ; arr [ ] to brr [ ] two times so that we can traverse through all rotations . ; We know hamming distance with 0 rotation would be 0. ; We try other rotations one by one and compute Hamming distance of every rotation ; We can never get more than n . ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxHamming ( int arr [ ] , int n ) { int brr [ 2 * n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ n + i ] = arr [ i ] ; int maxHam = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int currHam = 0 ; for ( int j = i , k = 0 ; j < ( i + n ) ; j ++ , k ++ ) if ( brr [ j ] != arr [ k ] ) currHam ++ ; if ( currHam == n ) return n ; maxHam = max ( maxHam , currHam ) ; } return maxHam ; } int main ( ) { int arr [ ] = { 2 , 4 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxHamming ( arr , n ) ; return 0 ; }
Print left rotation of array in O ( n ) time and O ( 1 ) space | C ++ implementation of left rotation of an array K number of times ; Function to leftRotate array multiple times ; To get the starting point of rotated array ; Prints the rotated array from start position ; Driver Code ; Function Call ; Function Call ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void leftRotate ( int arr [ ] , int n , int k ) { int mod = k % n ; for ( int i = 0 ; i < n ; i ++ ) cout << ( arr [ ( mod + i ) % n ] ) << " ▁ " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; leftRotate ( arr , n , k ) ; k = 3 ; leftRotate ( arr , n , k ) ; k = 4 ; leftRotate ( arr , n , k ) ; return 0 ; }
Minimum Circles needed to be removed so that all remaining circles are non intersecting | C ++ implementation of the above approach ; Comparison function modified according to the end value ; Function to return the count of non intersecting circles ; structure with start and end of diameter of circles ; sorting with smallest finish time first ; count stores number of circles to be removed ; cur stores ending of first circle ; non intersecting circles ; intersecting circles ; Driver Code ; centers of circles ; radius of circles ; number of circles
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; struct circle { int start , end ; } ; bool comp ( circle a , circle b ) { if ( a . end == b . end ) return a . start < b . start ; return a . end < b . end ; } void CountCircles ( int c [ ] , int r [ ] , int n ) { circle diameter [ n ] ; for ( int i = 0 ; i < n ; ++ i ) { diameter [ i ] . start = c [ i ] - r [ i ] ; diameter [ i ] . end = c [ i ] + r [ i ] ; } sort ( diameter , diameter + n , comp ) ; int count = 0 ; int cur = diameter [ 0 ] . end ; for ( int i = 1 ; i < n ; ++ i ) { if ( diameter [ i ] . start > cur ) { cur = diameter [ i ] . end ; } else count ++ ; } cout << count << " STRNEWLINE " ; } int main ( ) { int c [ ] = { 1 , 2 , 3 , 4 } ; int r [ ] = { 1 , 1 , 1 , 1 } ; int n = sizeof ( c ) / sizeof ( int ) ; CountCircles ( c , r , n ) ; return 0 ; }
Print left rotation of array in O ( n ) time and O ( 1 ) space | C ++ Implementation For Print Left Rotation Of Any Array K Times ; Function For The k Times Left Rotation ; Stl function rotates takes three parameters - the beginning , the position by which it should be rotated , the end address of the array The below function will be rotating the array left in linear time ( k % arraySize ) times ; Print the rotated array from start position ; Driver program ; Function Call
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void leftRotate ( int arr [ ] , int k , int n ) { rotate ( arr , arr + ( k % n ) , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; leftRotate ( arr , k , n ) ; return 0 ; }
Find element at given index after a number of rotations | CPP code to rotate an array and answer the index query ; Function to compute the element at given index ; Range [ left ... right ] ; Rotation will not have any effect ; Returning new element ; Driver ; No . of rotations ; Ranges according to 0 - based indexing
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findElement ( int arr [ ] , int ranges [ ] [ 2 ] , int rotations , int index ) { for ( int i = rotations - 1 ; i >= 0 ; i -- ) { int left = ranges [ i ] [ 0 ] ; int right = ranges [ i ] [ 1 ] ; if ( left <= index && right >= index ) { if ( index == left ) index = right ; else index -- ; } } return arr [ index ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int rotations = 2 ; int ranges [ rotations ] [ 2 ] = { { 0 , 2 } , { 0 , 3 } } ; int index = 1 ; cout << findElement ( arr , ranges , rotations , index ) ; return 0 ; }
Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged | C ++ implementation of the approach ; Function that returns the string s in sorted form such that the positions of alphabets and numeric digits remain unchanged ; String to character array ; Sort the array ; Count of alphabets and numbers ; Get the index from where the alphabets start ; Now replace the string with sorted string ; If the position was occupied by an alphabet then replace it with alphabet ; Else replace it with a number ; Return the sorted string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string sort ( string s ) { char c [ s . length ( ) + 1 ] ; strcpy ( c , s . c_str ( ) ) ; sort ( c , c + s . length ( ) ) ; int al_c = 0 , nu_c = 0 ; while ( c [ al_c ] < 97 ) al_c ++ ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] < 97 ) s [ i ] = c [ nu_c ++ ] ; else s [ i ] = c [ al_c ++ ] ; } return s ; } int main ( ) { string s = " d4c3b2a1" ; cout << sort ( s ) ; return 0 ; }
Split the array and add the first part to the end | CPP program to split array and move first part to end . ; Rotate array by 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void splitArr ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < k ; i ++ ) { int x = arr [ 0 ] ; for ( int j = 0 ; j < n - 1 ; ++ j ) arr [ j ] = arr [ j + 1 ] ; arr [ n - 1 ] = x ; } } int main ( ) { int arr [ ] = { 12 , 10 , 5 , 6 , 52 , 36 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int position = 2 ; splitArr ( arr , 6 , position ) ; for ( int i = 0 ; i < n ; ++ i ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Split the array and add the first part to the end | CPP program to split array and move first part to end . ; Function to spilt array and move first part to end ; make a temporary array with double the size ; copy array element in to new array twice ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void splitArr ( int arr [ ] , int length , int rotation ) { int tmp [ length * 2 ] = { 0 } ; for ( int i = 0 ; i < length ; i ++ ) { tmp [ i ] = arr [ i ] ; tmp [ i + length ] = arr [ i ] ; } for ( int i = rotation ; i < rotation + length ; i ++ ) { arr [ i - rotation ] = tmp [ i ] ; } } int main ( ) { int arr [ ] = { 12 , 10 , 5 , 6 , 52 , 36 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int position = 2 ; splitArr ( arr , n , position ) ; for ( int i = 0 ; i < n ; ++ i ) printf ( " % d ▁ " , arr [ i ] ) ; return 0 ; }
Shell | C ++ implementation of Shell - Metzner Sort ; Function to swap two elements ; Function to sort arr [ ] using Shell Metzner sort ; Declare variables ; Set initial step size to the size of the array ; Step size decreases by half each time ; k is the upper limit for j ; j is the starting point ; i equals to smaller value ; l equals to larger value ; Compare and swap arr [ i ] with arr [ l ] ; Decrease smaller value by step size ; Increment the lower limit of i ; Function to print the contents of an array ; Driver code ; Sort the array using Shell Metzner Sort ; Print the sorted array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int & a , int & b ) { int temp = a ; a = b ; b = temp ; } void sort_shell_metzner ( int arr [ ] , int n ) { int i , j , k , l , m , temp ; m = n ; while ( m > 0 ) { m /= 2 ; k = n - m ; j = 0 ; do { i = j ; do { l = i + m ; if ( arr [ i ] > arr [ l ] ) { swap ( arr [ i ] , arr [ l ] ) ; i -= m ; } else break ; } while ( i >= 0 ) ; j ++ ; } while ( j <= k ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 0 , -2 , 8 , 5 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort_shell_metzner ( arr , n ) ; printArray ( arr , n ) ; return 0 ; }
Rearrange an array such that arr [ i ] = i | C ++ program for above approach ; Function to tranform the array ; Iterate over the array ; Checf is any ar [ j ] exists such that ar [ j ] is equal to i ; Iterate over array ; If not present ; Print the output ; Driver Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; void fixArray ( int ar [ ] , int n ) { int i , j , temp ; for ( i = 0 ; i < n ; i ++ ) { for ( j = 0 ; j < n ; j ++ ) { if ( ar [ j ] == i ) { temp = ar [ j ] ; ar [ j ] = ar [ i ] ; ar [ i ] = temp ; break ; } } } for ( i = 0 ; i < n ; i ++ ) { if ( ar [ i ] != i ) { ar [ i ] = -1 ; } } cout << " Array ▁ after ▁ Rearranging " << endl ; for ( i = 0 ; i < n ; i ++ ) { cout << ar [ i ] << " ▁ " ; } } int main ( ) { int n , ar [ ] = { -1 , -1 , 6 , 1 , 9 , 3 , 2 , -1 , 4 , -1 } ; n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; fixArray ( ar , n ) ; }
Perform K of Q queries to maximize the sum of the array elements | C ++ implementation of the approach ; Function to perform K queries out of Q to maximize the final sum ; Get the initial sum of the array ; Stores the contriution of every query ; Sort the contribution of queries in descending order ; Get the K most contributions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getFinalSum ( int a [ ] , int n , pair < int , int > queries [ ] , int q , int k ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) answer += a [ i ] ; vector < int > contribution ; for ( int i = 0 ; i < q ; i ++ ) { contribution . push_back ( queries [ i ] . second - queries [ i ] . first + 1 ) ; } sort ( contribution . begin ( ) , contribution . end ( ) , greater < int > ( ) ) ; int i = 0 ; while ( i < k ) { answer += contribution [ i ] ; i ++ ; } return answer ; } int main ( ) { int a [ ] = { 1 , 1 , 2 , 2 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; pair < int , int > queries [ ] = { { 0 , 4 } , { 1 , 2 } , { 2 , 5 } , { 2 , 3 } , { 2 , 4 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; int k = 3 ; cout << getFinalSum ( a , n , queries , q , k ) ; return 0 ; }
Queries to return the absolute difference between L | C ++ implementation of the approach ; Function to return the result for a particular query ; Get the difference between the indices of L - th and the R - th smallest element ; Return the answer ; Function that performs all the queries ; Store the array numbers and their indices ; Sort the array elements ; Answer all the queries ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int answerQuery ( pair < int , int > arr [ ] , int l , int r ) { int answer = abs ( arr [ l - 1 ] . second - arr [ r - 1 ] . second ) ; return answer ; } void solveQueries ( int a [ ] , int n , int q [ ] [ 2 ] , int m ) { pair < int , int > arr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] . first = a [ i ] ; arr [ i ] . second = i ; } sort ( arr , arr + n ) ; for ( int i = 0 ; i < m ; i ++ ) cout << answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) << endl ; } int main ( ) { int a [ ] = { 1 , 5 , 4 , 2 , 8 , 6 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int q [ ] [ 2 ] = { { 2 , 5 } , { 1 , 3 } , { 1 , 5 } , { 3 , 6 } } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; solveQueries ( a , n , q , m ) ; return 0 ; }
Print all full nodes in a Binary Tree | A C ++ program to find the all full nodes in a given binary tree ; A binary tree node ; utility that allocates a newNode with the given key ; Traverses given tree in Inorder fashion and prints all nodes that have both children as non - empty . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void findFullNode ( Node * root ) { if ( root != NULL ) { findFullNode ( root -> left ) ; if ( root -> left != NULL && root -> right != NULL ) cout << root -> data << " ▁ " ; findFullNode ( root -> right ) ; } } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 8 ) ; root -> right -> left -> right -> left = newNode ( 9 ) ; findFullNode ( root ) ; return 0 ; }
Find the k largest numbers after deleting the given elements | ; Find k maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the largestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it largestElement ; Print top k elements in the heap ; Pop the top element ; Driver code
#include " iostream " NEW_LINE #include " queue " NEW_LINE #include " unordered _ map " NEW_LINE using namespace std ; void findElementsAfterDel ( int arr [ ] , int m , int del [ ] , int n , int k ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; ++ i ) { mp [ del [ i ] ] ++ ; } priority_queue < int > heap ; for ( int i = 0 ; i < m ; ++ i ) { if ( mp . find ( arr [ i ] ) != mp . end ( ) ) { mp [ arr [ i ] ] -- ; if ( mp [ arr [ i ] ] == 0 ) mp . erase ( arr [ i ] ) ; } else heap . push ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; ++ i ) { cout << heap . top ( ) << " ▁ " ; heap . pop ( ) ; } } int main ( ) { int array [ ] = { 5 , 12 , 33 , 4 , 56 , 12 , 20 } ; int m = sizeof ( array ) / sizeof ( array [ 0 ] ) ; int del [ ] = { 12 , 56 , 5 } ; int n = sizeof ( del ) / sizeof ( del [ 0 ] ) ; int k = 3 ; findElementsAfterDel ( array , m , del , n , k ) ; return 0 ; }
K | C ++ implementation of the above approach ; Set to store the unique substring ; String to create each substring ; Adding to set ; Converting set into a list ; Sorting the strings int the list into lexicographical order ; Printing kth substring ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void kThLexString ( string st , int k , int n ) { set < string > z ; for ( int i = 0 ; i < n ; i ++ ) { string pp ; for ( int j = i ; j < i + k ; j ++ ) { if ( j >= n ) break ; pp += st [ j ] ; z . insert ( pp ) ; } } vector < string > fin ( z . begin ( ) , z . end ( ) ) ; sort ( fin . begin ( ) , fin . end ( ) ) ; cout << fin [ k - 1 ] ; } int main ( ) { string s = " geeksforgeeks " ; int k = 5 ; int n = s . length ( ) ; kThLexString ( s , k , n ) ; }
Rearrange array such that arr [ i ] >= arr [ j ] if i is even and arr [ i ] <= arr [ j ] if i is odd and j < i | C ++ program to rearrange the array as per the given condition ; function to rearrange the array ; total even positions ; total odd positions ; copy original array in an auxiliary array ; sort the auxiliary array ; fill up odd position in original array ; fill up even positions in original array ; display array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeArr ( int arr [ ] , int n ) { int evenPos = n / 2 ; int oddPos = n - evenPos ; int tempArr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) tempArr [ i ] = arr [ i ] ; sort ( tempArr , tempArr + n ) ; int j = oddPos - 1 ; for ( int i = 0 ; i < n ; i += 2 ) { arr [ i ] = tempArr [ j ] ; j -- ; } j = oddPos ; for ( int i = 1 ; i < n ; i += 2 ) { arr [ i ] = tempArr [ j ] ; j ++ ; } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrangeArr ( arr , size ) ; return 0 ; }
Count triplets in a sorted doubly linked list whose product is equal to a given value x | C ++ implementation to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; structure of node of doubly linked list ; function to count triplets in a sorted doubly linked list whose product is equal to a given value ' x ' ; generate all possible triplets ; if elements in the current triplet product up to ' x ' ; increment count ; required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; Driver program to test above ; start with an empty doubly linked list ; insert values in sorted order
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next , * prev ; } ; int countTriplets ( struct Node * head , int x ) { struct Node * ptr1 , * ptr2 , * ptr3 ; int count = 0 ; for ( ptr1 = head ; ptr1 != NULL ; ptr1 = ptr1 -> next ) for ( ptr2 = ptr1 -> next ; ptr2 != NULL ; ptr2 = ptr2 -> next ) for ( ptr3 = ptr2 -> next ; ptr3 != NULL ; ptr3 = ptr3 -> next ) if ( ( ptr1 -> data * ptr2 -> data * ptr3 -> data ) == x ) count ++ ; return count ; } void insert ( struct Node * * head , int data ) { struct Node * temp = new Node ( ) ; temp -> data = data ; temp -> next = temp -> prev = NULL ; if ( ( * head ) == NULL ) ( * head ) = temp ; else { temp -> next = * head ; ( * head ) -> prev = temp ; ( * head ) = temp ; } } int main ( ) { struct Node * head = NULL ; insert ( & head , 9 ) ; insert ( & head , 8 ) ; insert ( & head , 6 ) ; insert ( & head , 5 ) ; insert ( & head , 4 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; int x = 8 ; cout << " Count ▁ = ▁ " << countTriplets ( head , x ) ; return 0 ; }
Sort only non | C ++ program to sort only non primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print the array such that only non primes are sorted ; vector v will store all non prime numbers ; If not prime , insert into vector ; sorting vector of non primes ; print the required array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100005 ] ; void SieveOfEratosthenes ( int n ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } void sortedArray ( int arr [ ] , int n ) { SieveOfEratosthenes ( 100005 ) ; std :: vector < int > v ; for ( int i = 0 ; i < n ; ++ i ) { if ( prime [ arr [ i ] ] == 0 ) v . push_back ( arr [ i ] ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( prime [ arr [ i ] ] == true ) cout << arr [ i ] << " ▁ " ; else { cout << v [ j ] << " ▁ " ; j ++ ; } } } int main ( ) { int n = 6 ; int arr [ ] = { 100 , 11 , 500 , 2 , 17 , 1 } ; sortedArray ( arr , n ) ; return 0 ; }
Sum of all nodes in a binary tree | Program to print sum of all the elements of a binary tree ; utility that allocates a new Node with the given key ; Function to find sum of all the elements ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * node = new Node ; node -> key = key ; node -> left = node -> right = NULL ; return ( node ) ; } int addBT ( Node * root ) { if ( root == NULL ) return 0 ; return ( root -> key + addBT ( root -> left ) + addBT ( root -> right ) ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; int sum = addBT ( root ) ; cout << " Sum ▁ of ▁ all ▁ the ▁ elements ▁ is : ▁ " << sum << endl ; return 0 ; }
Maximum sum of absolute difference of any permutation | CPP implementation of above algorithm ; final sequence stored in the vector ; sort the original array so that we can retrieve the large elements from the end of array elements ; In this loop first we will insert one smallest element not entered till that time in final sequence and then enter a highest element ( not entered till that time ) in final sequence so that we have large difference value . This process is repeated till all array has completely entered in sequence . Here , we have loop till n / 2 because we are inserting two elements at a time in loop . ; If there are odd elements , push the middle element at the end . ; variable to store the maximum sum of absolute difference ; In this loop absolute difference of elements for the final sequence is calculated . ; absolute difference of last element and 1 st element ; return the value ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxSumDifference ( int a [ ] , int n ) { vector < int > finalSequence ; sort ( a , a + n ) ; for ( int i = 0 ; i < n / 2 ; ++ i ) { finalSequence . push_back ( a [ i ] ) ; finalSequence . push_back ( a [ n - i - 1 ] ) ; } if ( n % 2 != 0 ) finalSequence . push_back ( a [ n / 2 ] ) ; int MaximumSum = 0 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { MaximumSum = MaximumSum + abs ( finalSequence [ i ] - finalSequence [ i + 1 ] ) ; } MaximumSum = MaximumSum + abs ( finalSequence [ n - 1 ] - finalSequence [ 0 ] ) ; return MaximumSum ; } int main ( ) { int a [ ] = { 1 , 2 , 4 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MaxSumDifference ( a , n ) << endl ; }
Minimum swaps required to bring all elements less than or equal to k together | C ++ program to find minimum swaps required to club all elements less than or equals to k together ; Utility function to find minimum swaps required to club all elements less than or equals to k together ; Find count of elements which are less than equals to k ; Find unwanted elements in current window of size ' count ' ; Initialize answer with ' bad ' value of current window ; Decrement count of previous window ; Increment count of current window ; Update ans if count of ' bad ' is less in current window ; Driver code
#include <iostream> NEW_LINE using namespace std ; int minSwap ( int * arr , int n , int k ) { int count = 0 ; for ( int i = 0 ; i < n ; ++ i ) if ( arr [ i ] <= k ) ++ count ; int bad = 0 ; for ( int i = 0 ; i < count ; ++ i ) if ( arr [ i ] > k ) ++ bad ; int ans = bad ; for ( int i = 0 , j = count ; j < n ; ++ i , ++ j ) { if ( arr [ i ] > k ) -- bad ; if ( arr [ j ] > k ) ++ bad ; ans = min ( ans , bad ) ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 6 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << minSwap ( arr , n , k ) << " STRNEWLINE " ; int arr1 [ ] = { 2 , 7 , 9 , 5 , 8 , 7 , 4 } ; n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; k = 5 ; cout << minSwap ( arr1 , n , k ) ; return 0 ; }
Rearrange positive and negative numbers using inbuilt sort function | C ++ implementation of the above approach ; Rearrange the array with all negative integers on left and positive integers on right use recursion to split the array with first element as one half and the rest array as another and then merge it with head of the array in each step ; exit condition ; rearrange the array except the first element in each recursive call ; If the first element of the array is positive , then right - rotate the array by one place first and then reverse the merged array . ; Driver code
#include <iostream> NEW_LINE void printArray ( int array [ ] , int length ) { std :: cout << " [ " ; for ( int i = 0 ; i < length ; i ++ ) { std :: cout << array [ i ] ; if ( i < ( length - 1 ) ) std :: cout << " , ▁ " ; else std :: cout << " ] " << std :: endl ; } } void reverse ( int array [ ] , int start , int end ) { while ( start < end ) { int temp = array [ start ] ; array [ start ] = array [ end ] ; array [ end ] = temp ; start ++ ; end -- ; } } void rearrange ( int array [ ] , int start , int end ) { if ( start == end ) return ; rearrange ( array , ( start + 1 ) , end ) ; if ( array [ start ] >= 0 ) { reverse ( array , ( start + 1 ) , end ) ; reverse ( array , start , end ) ; } } int main ( ) { int array [ ] = { -12 , -11 , -13 , -5 , -6 , 7 , 5 , 3 , 6 } ; int length = ( sizeof ( array ) / sizeof ( array [ 0 ] ) ) ; int countNegative = 0 ; for ( int i = 0 ; i < length ; i ++ ) { if ( array [ i ] < 0 ) countNegative ++ ; } std :: cout << " array : ▁ " ; printArray ( array , length ) ; rearrange ( array , 0 , ( length - 1 ) ) ; reverse ( array , countNegative , ( length - 1 ) ) ; std :: cout << " rearranged ▁ array : ▁ " ; printArray ( array , length ) ; return 0 ; }
Efficiently merging two sorted arrays with O ( 1 ) extra space | ; Now traverse the array1 and if arr2 first element is less than arr1 then swap ; Swap ; We will store the firstElement of array2 and left shift all the element and store the firstElement in arr2 [ k - 1 ] ; Read the arr1 ; Read the arr2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void mergeArray ( int arr1 [ ] , int arr2 [ ] , int n , int m ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr1 [ i ] > arr2 [ 0 ] ) { int temp = arr1 [ i ] ; arr1 [ i ] = arr2 [ 0 ] ; arr2 [ 0 ] = temp ; int firstElement = arr2 [ 0 ] ; int k ; for ( k = 1 ; k < m && arr2 [ k ] < firstElement ; k ++ ) { arr2 [ k - 1 ] = arr2 [ k ] ; } arr2 [ k - 1 ] = firstElement ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << arr1 [ i ] << " ▁ " ; } cout << endl ; for ( int i = 0 ; i < m ; i ++ ) { cout << arr2 [ i ] << " ▁ " ; } } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int arr2 [ ] = { 0 , 2 , 6 , 8 , 9 } ; int n = arr1 . length , m = arr2 . length ; mergeArray ( arr1 , arr2 , n , m ) ; }
Sorting array of strings ( or words ) using Trie | C ++ program to sort an array of strings using Trie ; index is set when node is a leaf node , otherwise - 1 ; ; to make new trie ; function to insert in trie ; taking ascii value to find index of child node ; making new path if not already ; go to next node ; Mark leaf ( end of word ) and store index of word in arr [ ] ; function for preorder traversal ; if leaf node then print key ; insert all keys of dictionary into trie ; print keys in lexicographic order ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; struct Trie { int index ; Trie * child [ MAX_CHAR ] ; Trie ( ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) child [ i ] = NULL ; index = -1 ; } } ; void insert ( Trie * root , string str , int index ) { Trie * node = root ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { char ind = str [ i ] - ' a ' ; if ( ! node -> child [ ind ] ) node -> child [ ind ] = new Trie ( ) ; node = node -> child [ ind ] ; } node -> index = index ; } bool preorder ( Trie * node , string arr [ ] ) { if ( node == NULL ) return false ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( node -> child [ i ] != NULL ) { if ( node -> child [ i ] -> index != -1 ) cout << arr [ node -> child [ i ] -> index ] << endl ; preorder ( node -> child [ i ] , arr ) ; } } } void printSorted ( string arr [ ] , int n ) { Trie * root = new Trie ( ) ; for ( int i = 0 ; i < n ; i ++ ) insert ( root , arr [ i ] , i ) ; preorder ( root , arr ) ; } int main ( ) { string arr [ ] = { " abc " , " xy " , " bcd " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSorted ( arr , n ) ; return 0 ; }
Maximum product of subsequence of size k | C ++ code to find maximum possible product of sub - sequence of size k from given array of n integers # include < algorithm > for sorting ; Required function ; sorting given input array ; variable to store final product of all element of sub - sequence of size k ; CASE I If max element is 0 and k is odd then max product will be 0 ; CASE II If all elements are negative and k is odd then max product will be product of rightmost - subarray of size k ; else i is current left pointer index ; j is current right pointer index ; CASE III if k is odd and rightmost element in sorted array is positive then it must come in subsequence Multiplying A [ j ] with product and correspondingly changing j ; CASE IV Now k is even Now we deal with pairs Each time a pair is multiplied to product ie . . two elements are added to subsequence each time Effectively k becomes half Hence , k >>= 1 means k /= 2 ; Now finding k corresponding pairs to get maximum possible value of product ; product from left pointers ; product from right pointers ; Taking the max product from two choices Correspondingly changing the pointer 's position ; Finally return product ; Driver Code to test above function
#include <iostream> NEW_LINE using namespace std ; int maxProductSubarrayOfSizeK ( int A [ ] , int n , int k ) { sort ( A , A + n ) ; int product = 1 ; if ( A [ n - 1 ] == 0 && ( k & 1 ) ) return 0 ; if ( A [ n - 1 ] <= 0 && ( k & 1 ) ) { for ( int i = n - 1 ; i >= n - k ; i -- ) product *= A [ i ] ; return product ; } int i = 0 ; int j = n - 1 ; if ( k & 1 ) { product *= A [ j ] ; j -- ; k -- ; } k >>= 1 ; for ( int itr = 0 ; itr < k ; itr ++ ) { int left_product = A [ i ] * A [ i + 1 ] ; int right_product = A [ j ] * A [ j - 1 ] ; if ( left_product > right_product ) { product *= left_product ; i += 2 ; } else { product *= right_product ; j -= 2 ; } } return product ; } int main ( ) { int A [ ] = { 1 , 2 , -1 , -3 , -6 , 4 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int k = 4 ; cout << maxProductSubarrayOfSizeK ( A , n , k ) ; return 0 ; }
Reorder an array according to given indexes | C ++ program to sort an array according to given indexes ; Function to reorder elements of arr [ ] according to index [ ] ; arr [ i ] should be present at index [ i ] index ; Copy temp [ ] to arr [ ] ; Driver program
#include <iostream> NEW_LINE using namespace std ; void reorder ( int arr [ ] , int index [ ] , int n ) { int temp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) temp [ index [ i ] ] = arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] = temp [ i ] ; index [ i ] = i ; } } int main ( ) { int arr [ ] = { 50 , 40 , 70 , 60 , 90 } ; int index [ ] = { 3 , 0 , 4 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; reorder ( arr , index , n ) ; cout << " Reordered ▁ array ▁ is : ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << " Modified Index array is : " for ( int i = 0 ; i < n ; i ++ ) cout << index [ i ] << " ▁ " ; return 0 ; }
Program to sort an array of strings using Selection Sort | C ++ program to implement selection sort for array of strings . ; Sorts an array of strings where length of every string should be smaller than MAX_LEN ; One by one move boundary of unsorted subarray ; Find the minimum element in unsorted array ; If min is greater than arr [ j ] ; Make arr [ j ] as minStr and update min_idx ; Swap the found minimum element with the first element ; Driver code ; Printing the array before sorting ; Printing the array after sorting
#include <bits/stdc++.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; #define MAX_LEN 100 NEW_LINE void selectionSort ( char arr [ ] [ MAX_LEN ] , int n ) { int i , j , min_idx ; char minStr [ MAX_LEN ] ; for ( i = 0 ; i < n - 1 ; i ++ ) { int min_idx = i ; strcpy ( minStr , arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( strcmp ( minStr , arr [ j ] ) > 0 ) { strcpy ( minStr , arr [ j ] ) ; min_idx = j ; } } if ( min_idx != i ) { char temp [ MAX_LEN ] ; strcpy ( temp , arr [ i ] ) ; strcpy ( arr [ i ] , arr [ min_idx ] ) ; strcpy ( arr [ min_idx ] , temp ) ; } } } int main ( ) { char arr [ ] [ MAX_LEN ] = { " GeeksforGeeks " , " Practice . GeeksforGeeks " , " GeeksQuiz " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int i ; cout << " Given ▁ array ▁ is STRNEWLINE " ; for ( i = 0 ; i < n ; i ++ ) cout << i << " : ▁ " << arr [ i ] << endl ; selectionSort ( arr , n ) ; cout << " Sorted array is " ; for ( i = 0 ; i < n ; i ++ ) cout << i << " : ▁ " << arr [ i ] << endl ; return 0 ; }
Reorder an array according to given indexes | A O ( n ) time and O ( 1 ) extra space C ++ program to sort an array according to given indexes ; Function to reorder elements of arr [ ] according to index [ ] ; Fix all elements one by one ; While index [ i ] and arr [ i ] are not fixed ; Store values of the target ( or correct ) position before placing arr [ i ] there ; Place arr [ i ] at its target ( or correct ) position . Also copy corrected index for new position ; Copy old target values to arr [ i ] and index [ i ] ; Driver program
#include <iostream> NEW_LINE using namespace std ; void reorder ( int arr [ ] , int index [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { while ( index [ i ] != i ) { int oldTargetI = index [ index [ i ] ] ; char oldTargetE = arr [ index [ i ] ] ; arr [ index [ i ] ] = arr [ i ] ; index [ index [ i ] ] = index [ i ] ; index [ i ] = oldTargetI ; arr [ i ] = oldTargetE ; } } } int main ( ) { int arr [ ] = { 50 , 40 , 70 , 60 , 90 } ; int index [ ] = { 3 , 0 , 4 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; reorder ( arr , index , n ) ; cout << " Reordered ▁ array ▁ is : ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << " Modified Index array is : " for ( int i = 0 ; i < n ; i ++ ) cout << index [ i ] << " ▁ " ; return 0 ; }
Stooge Sort | C ++ code to implement stooge sort ; Function to implement stooge sort ; If first element is smaller than last , swap them ; If there are more than 2 elements in the array ; Recursively sort first 2 / 3 elements ; Recursively sort last 2 / 3 elements ; Recursively sort first 2 / 3 elements again to confirm ; Driver Code ; Calling Stooge Sort function to sort the array ; Display the sorted array
#include <iostream> NEW_LINE using namespace std ; void stoogesort ( int arr [ ] , int l , int h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) swap ( arr [ l ] , arr [ h ] ) ; if ( h - l + 1 > 2 ) { int t = ( h - l + 1 ) / 3 ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; stoogesort ( arr , 0 , n - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Reorder an array according to given indexes | C ++ code to reorder an array according to given indices ; left child in 0 based indexing ; right child in 1 based indexing ; find largest index from root , left and right child ; swap arr whenever index is swapped ; Build heap ; Swap the largest element of index ( first element ) with the last element ; swap arr whenever index is swapped ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int heapSize ; void swap ( int & a , int & b ) { int temp = a ; a = b ; b = temp ; } void heapify ( int arr [ ] , int index [ ] , int i ) { int largest = i ; int left = 2 * i + 1 ; int right = 2 * i + 2 ; if ( left < heapSize && index [ left ] > index [ largest ] ) { largest = left ; } if ( right < heapSize && index [ right ] > index [ largest ] ) { largest = right ; } if ( largest != i ) { swap ( arr [ largest ] , arr [ i ] ) ; swap ( index [ largest ] , index [ i ] ) ; heapify ( arr , index , largest ) ; } } void heapSort ( int arr [ ] , int index [ ] , int n ) { for ( int i = ( n - 1 ) / 2 ; i >= 0 ; i -- ) { heapify ( arr , index , i ) ; } for ( int i = n - 1 ; i > 0 ; i -- ) { swap ( index [ 0 ] , index [ i ] ) ; swap ( arr [ 0 ] , arr [ i ] ) ; heapSize -- ; heapify ( arr , index , 0 ) ; } } int main ( ) { int arr [ ] = { 50 , 40 , 70 , 60 , 90 } ; int index [ ] = { 3 , 0 , 4 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; heapSize = n ; heapSort ( arr , index , n ) ; cout << " Reordered ▁ array ▁ is : ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << " Modified Index array is : " for ( int i = 0 ; i < n ; i ++ ) cout << index [ i ] << " ▁ " ; return 0 ; }
Sum of all the parent nodes having child node x | C ++ implementation to find the sum of all the parent nodes having child node x ; Node of a binary tree ; function to get a new node ; allocate memory for the node ; put in the data ; function to find the sum of all the parent nodes having child node x ; if root == NULL ; if left or right child of root is ' x ' , then add the root ' s ▁ data ▁ to ▁ ' sum ' ; recursively find the required parent nodes in the left and right subtree ; utility function to find the sum of all the parent nodes having child node x ; required sum of parent nodes ; Driver program to test above ; binary tree formation ; 4 ; / \ ; 2 5 ; 7 2 2 3
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } void sumOfParentOfX ( Node * root , int & sum , int x ) { if ( ! root ) return ; if ( ( root -> left && root -> left -> data == x ) || ( root -> right && root -> right -> data == x ) ) sum += root -> data ; sumOfParentOfX ( root -> left , sum , x ) ; sumOfParentOfX ( root -> right , sum , x ) ; } int sumOfParentOfXUtil ( Node * root , int x ) { int sum = 0 ; sumOfParentOfX ( root , sum , x ) ; return sum ; } int main ( ) { Node * root = getNode ( 4 ) ; root -> left = getNode ( 2 ) ; root -> right = getNode ( 5 ) ; root -> left -> left = getNode ( 7 ) ; root -> left -> right = getNode ( 2 ) ; root -> right -> left = getNode ( 2 ) ; root -> right -> right = getNode ( 3 ) ; int x = 2 ; cout << " Sum ▁ = ▁ " << sumOfParentOfXUtil ( root , x ) ; return 0 ; }
Sort even | Program to sort even - placed elements in increasing and odd - placed in decreasing order with constant space complexity ; first odd index ; last index ; if last index is odd ; decrement j to even index ; swapping till half of array ; Sort first half in increasing ; Sort second half in decreasing ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bitonicGenerator ( int arr [ ] , int n ) { int i = 1 ; int j = n - 1 ; if ( j % 2 != 0 ) j -- ; while ( i < j ) { swap ( arr [ i ] , arr [ j ] ) ; i += 2 ; j -= 2 ; } sort ( arr , arr + ( n + 1 ) / 2 ) ; sort ( arr + ( n + 1 ) / 2 , arr + n , greater < int > ( ) ) ; } int main ( ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; bitonicGenerator ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Count minimum number of subsets ( or subsequences ) with consecutive numbers | C ++ program to find number of subset containing consecutive numbers ; Returns count of subsets with consecutive numbers ; Sort the array so that elements which are consecutive in nature became consecutive in the array . ; int count = 1 ; Initialize result ; Check if there is beginning of another subset of consecutive number ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numofsubset ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] + 1 != arr [ i + 1 ] ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 100 , 56 , 5 , 6 , 102 , 58 , 101 , 57 , 7 , 103 , 59 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << numofsubset ( arr , n ) << endl ; return 0 ; }
Gnome Sort | A C ++ Program to implement Gnome Sort ; A function to sort the algorithm using gnome sort ; A utility function ot print an array of size n ; Driver program to test above functions .
#include <iostream> NEW_LINE using namespace std ; void gnomeSort ( int arr [ ] , int n ) { int index = 0 ; while ( index < n ) { if ( index == 0 ) index ++ ; if ( arr [ index ] >= arr [ index - 1 ] ) index ++ ; else { swap ( arr [ index ] , arr [ index - 1 ] ) ; index -- ; } } return ; } void printArray ( int arr [ ] , int n ) { cout << " Sorted ▁ sequence ▁ after ▁ Gnome ▁ sort : ▁ " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 34 , 2 , 10 , -9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; gnomeSort ( arr , n ) ; printArray ( arr , n ) ; return ( 0 ) ; }
Cocktail Sort | C ++ implementation of Cocktail Sort ; Sorts arrar a [ 0. . n - 1 ] using Cocktail sort ; reset the swapped flag on entering the loop , because it might be true from a previous iteration . ; loop from left to right same as the bubble sort ; if nothing moved , then array is sorted . ; otherwise , reset the swapped flag so that it can be used in the next stage ; move the end point back by one , because item at the end is in its rightful spot ; from right to left , doing the same comparison as in the previous stage ; increase the starting point , because the last stage would have moved the next smallest number to its rightful spot . ; Prints the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CocktailSort ( int a [ ] , int n ) { bool swapped = true ; int start = 0 ; int end = n - 1 ; while ( swapped ) { swapped = false ; for ( int i = start ; i < end ; ++ i ) { if ( a [ i ] > a [ i + 1 ] ) { swap ( a [ i ] , a [ i + 1 ] ) ; swapped = true ; } } if ( ! swapped ) break ; swapped = false ; -- end ; for ( int i = end - 1 ; i >= start ; -- i ) { if ( a [ i ] > a [ i + 1 ] ) { swap ( a [ i ] , a [ i + 1 ] ) ; swapped = true ; } } ++ start ; } } void printArray ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , a [ i ] ) ; printf ( " STRNEWLINE " ) ; } int main ( ) { int a [ ] = { 5 , 1 , 4 , 2 , 8 , 0 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; CocktailSort ( a , n ) ; printf ( " Sorted ▁ array ▁ : STRNEWLINE " ) ; printArray ( a , n ) ; return 0 ; }
Find the point where maximum intervals overlap | Program to find maximum guest at any time in a party ; Sort arrival and exit arrays ; guests_in indicates number of guests at a time ; Similar to merge in merge sort to process all events in sorted order ; If next event in sorted order is arrival , increment count of guests ; Update max_guests if needed ; increment index of arrival array ; If event is exit , decrement count ; of guests . ; Driver program to test above function
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; void findMaxGuests ( int arrl [ ] , int exit [ ] , int n ) { sort ( arrl , arrl + n ) ; sort ( exit , exit + n ) ; int guests_in = 1 , max_guests = 1 , time = arrl [ 0 ] ; int i = 1 , j = 0 ; while ( i < n && j < n ) { if ( arrl [ i ] <= exit [ j ] ) { guests_in ++ ; if ( guests_in > max_guests ) { max_guests = guests_in ; time = arrl [ i ] ; } i ++ ; } else { guests_in -- ; j ++ ; } } cout << " Maximum ▁ Number ▁ of ▁ Guests ▁ = ▁ " << max_guests << " ▁ at ▁ time ▁ " << time ; } int main ( ) { int arrl [ ] = { 1 , 2 , 10 , 5 , 5 } ; int exit [ ] = { 4 , 5 , 12 , 9 , 12 } ; int n = sizeof ( arrl ) / sizeof ( arrl [ 0 ] ) ; findMaxGuests ( arrl , exit , n ) ; return 0 ; }
Find the point where maximum intervals overlap | ; Finding maximum starting time O ( n ) ; Finding maximum ending time O ( n ) ; Creating and auxiliary array O ( n ) ; Lazy addition ; Lazily Calculating value at index i O ( n ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxOverlap ( vector < int > & start , vector < int > & end ) { int n = start . size ( ) ; int maxa = * max_element ( start . begin ( ) , start . end ( ) ) ; int maxb = * max_element ( end . begin ( ) , end . end ( ) ) ; int maxc = max ( maxa , maxb ) ; int x [ maxc + 2 ] ; memset ( x , 0 , sizeof x ) ; int cur = 0 , idx ; for ( int i = 0 ; i < n ; i ++ ) { ++ x [ start [ i ] ] ; -- x [ end [ i ] + 1 ] ; } int maxy = INT_MIN ; for ( int i = 0 ; i <= maxc ; i ++ ) { cur += x [ i ] ; if ( maxy < cur ) { maxy = cur ; idx = i ; } } cout << " Maximum ▁ value ▁ is ▁ " << maxy << " ▁ at ▁ position ▁ " << idx << endl ; } int main ( ) { vector < int > start = { 13 , 28 , 29 , 14 , 40 , 17 , 3 } , end = { 107 , 95 , 111 , 105 , 70 , 127 , 74 } ; maxOverlap ( start , end ) ; return 0 ; }
Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple C ++ program to rearrange contents of arr [ ] such that arr [ j ] becomes j if arr [ i ] is j ; A simple method to rearrange ' arr [ 0 . . n - 1 ] ' so that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' ; Create an auxiliary array of same size ; Store result in temp [ ] ; Copy temp back to arr [ ] ; A utility function to print contents of arr [ 0. . n - 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeNaive ( int arr [ ] , int n ) { int temp [ n ] , i ; for ( i = 0 ; i < n ; i ++ ) temp [ arr [ i ] ] = i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = temp [ i ] ; } void printArray ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) cout << ( " % d ▁ " , arr [ i ] ) ; cout << ( " STRNEWLINE " ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( " Given ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; rearrangeNaive ( arr , n ) ; cout << ( " Modified ▁ array ▁ is ▁ STRNEWLINE " ) ; printArray ( arr , n ) ; return 0 ; }