text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Insert a Character in a Rotated String | C ++ implementation of the approach ; Function to insert the character ; To store last position where the insertion is done ; To store size of the string ; To store the modified string ; To store characters ; Add first character to the string ; Update the size ; Update the index of last insertion ; Insert all other characters to the string ; Take the character ; Take substring upto ind ; Take modulo value of k with the size of the string ; Check if we need to move to the start of the string ; If we don 't need to move to start of the string ; Take substring from upto temp ; Take substring which will be after the inserted character ; Insert into the string ; Store new inserted position ; Store size of the new string Technically sz + 1 ; If we need to move to start of the string ; Take substring which will before the inserted character ; Take substring which will be after the inserted character ; Insert into the string ; Store new inserted position ; Store size of the new string Technically sz + 1 ; Return the required character ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; char Insert ( char arr [ ] , int n , int k ) { int ind = 0 ; int sz = 0 ; string s = " " ; char ch = arr [ 0 ] ; s += ch ; sz = 1 ; ind = 0 ; for ( int i = 1 ; i < n ; i ++ ) { ch = arr [ i ] ; string s1 = s . substr ( 0 , ind + 1 ) ; int temp = k % sz ; int ro = temp - min ( temp , sz - ind - 1 ) ; if ( ro == 0 ) { string s2 = s . substr ( ind + 1 , temp ) ; string s3 = s . substr ( ind + temp + 1 , sz - ind - temp - 1 ) ; s = s1 + s2 + ch + s3 ; ind = s1 . size ( ) + s2 . size ( ) ; sz = s . size ( ) ; } else { string s2 = s . substr ( 0 , ro ) ; string s3 = s . substr ( ro , sz - ro ) ; s = s2 + ch + s3 ; ind = s2 . size ( ) ; sz = s . size ( ) ; } } if ( ind == 0 ) return s [ sz - 1 ] ; else return s [ ind - 1 ] ; } int main ( ) { char arr [ ] = { '1' , '2' , '3' , '4' , '5' } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << Insert ( arr , n , k ) ; return 0 ; }
Rearrange the given string such that all prime multiple indexes have same character | CPP program to rearrange the given string such that all prime multiple indexes have same character ; To store answer ; Function to rearrange the given string such that all prime multiple indexes have the same character . ; Initially assume that we can kept any symbol at any positions . If at any index contains one then it is not counted in our required positions ; To store number of positions required to store elements of same kind ; Start sieve ; For all multiples of i ; map to store frequency of each character ; Store all characters in the vector and sort the vector to find the character with highest frequency ; If most occured character is less than required positions ; In all required positions keep character which occured most times ; Fill all other indexes with remaining characters ; If character frequency becomes zero then go to next character ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100005 NEW_LINE char ans [ N ] ; int sieve [ N ] ; void Rearrange ( string s , int n ) { fill ( sieve + 1 , sieve + n + 1 , 1 ) ; int sz = 0 ; for ( int i = 2 ; i <= n / 2 ; i ++ ) { if ( sieve [ i ] ) { for ( int j = 1 ; i * j <= n ; j ++ ) { if ( sieve [ i * j ] ) sz ++ ; sieve [ i * j ] = 0 ; } } } map < char , int > m ; for ( auto it : s ) m [ it ] ++ ; vector < pair < int , char > > v ; for ( auto it : m ) v . push_back ( { it . second , it . first } ) ; sort ( v . begin ( ) , v . end ( ) ) ; if ( v . back ( ) . first < sz ) { cout << -1 ; return ; } for ( int i = 2 ; i <= n ; i ++ ) { if ( ! sieve [ i ] ) { ans [ i ] = v . back ( ) . second ; } } int idx = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( sieve [ i ] ) { ans [ i ] = v [ idx ] . second ; v [ idx ] . first -- ; if ( v [ idx ] . first == 0 ) idx ++ ; } cout << ans [ i ] ; } } int main ( ) { string str = " aabaaaa " ; int n = str . size ( ) ; Rearrange ( str , n ) ; return 0 ; }
Check loop in array according to given constraints | C ++ program to check if a given array is cyclic or not ; A simple Graph DFS based recursive function to check if there is cycle in graph with vertex v as root of DFS . Refer below article for details . https : www . geeksforgeeks . org / detect - cycle - in - a - graph / ; There is a cycle if an adjacent is visited and present in recursion call stack recur [ ] ; Returns true if arr [ ] has cycle ; Create a graph using given moves in arr [ ] ; Do DFS traversal of graph to detect cycle ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCycleRec ( int v , vector < int > adj [ ] , vector < bool > & visited , vector < bool > & recur ) { visited [ v ] = true ; recur [ v ] = true ; for ( int i = 0 ; i < adj [ v ] . size ( ) ; i ++ ) { if ( visited [ adj [ v ] [ i ] ] == false ) { if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) return true ; } else if ( visited [ adj [ v ] [ i ] ] == true && recur [ adj [ v ] [ i ] ] == true ) return true ; } recur [ v ] = false ; return false ; } bool isCycle ( int arr [ ] , int n ) { vector < int > adj [ n ] ; for ( int i = 0 ; i < n ; i ++ ) if ( i != ( i + arr [ i ] + n ) % n ) adj [ i ] . push_back ( ( i + arr [ i ] + n ) % n ) ; vector < bool > visited ( n , false ) ; vector < bool > recur ( n , false ) ; for ( int i = 0 ; i < n ; i ++ ) if ( visited [ i ] == false ) if ( isCycleRec ( i , adj , visited , recur ) ) return true ; return true ; } int main ( void ) { int arr [ ] = { 2 , -1 , 1 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isCycle ( arr , n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Queries to find the last non | C ++ implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the last non - repeating character ; Starting from the last character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MAX = 256 ; int freq [ 256 ] [ 1000 ] = { 0 } ; void preCalculate ( string str , int n ) { freq [ ( int ) str [ 0 ] ] [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str [ i ] ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = ( char ) j ; if ( charToUpdate == ch ) freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 ; else freq [ j ] [ i ] = freq [ j ] [ i - 1 ] ; } } } int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch ] [ r ] ; else return ( freq [ ( int ) ch ] [ r ] - freq [ ( int ) ch ] [ l - 1 ] ) ; } string getString ( char x ) { string s ( 1 , x ) ; return s ; } string lastNonRepeating ( string str , int n , int l , int r ) { for ( int i = r ; i >= l ; i -- ) { char ch = str [ i ] ; if ( getFrequency ( ch , l , r ) == 1 ) return getString ( ch ) ; } return " - 1" ; } int main ( ) { string str = " GeeksForGeeks " ; int n = str . length ( ) ; int queries [ 3 ] [ 2 ] = { { 2 , 9 } , { 2 , 3 } , { 0 , 12 } } ; int q = 3 ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) { cout << ( lastNonRepeating ( str , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) << endl ; ; } }
Queries to answer the X | C ++ implementation of the approach ; Function to pre - process the sub - strings in sorted order ; Generate all substrings ; Iterate to find all sub - strings ; Store the sub - string in the vector ; Sort the substrings lexicographically ; Driver code ; To store all the sub - strings ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void pre_process ( vector < string > & substrings , string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { string dup = " " ; for ( int j = i ; j < n ; j ++ ) { dup += s [ j ] ; substrings . push_back ( dup ) ; } } sort ( substrings . begin ( ) , substrings . end ( ) ) ; } int main ( ) { string s = " geek " ; vector < string > substrings ; pre_process ( substrings , s ) ; int queries [ ] = { 1 , 5 , 10 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) cout << substrings [ queries [ i ] - 1 ] << endl ; return 0 ; }
Print the final string when minimum value strings get concatenated in every operation | C ++ implementation of the approach ; Class that represents a pair ; Function that prints the final string ; Add all the strings and their corresponding values to the priority queue ; Take those two strings from the priority queue whose corresponding integer values are smaller and add them up as well as their values and add them back to the priority queue while there are more than a single element in the queue ; Get the minimum valued string ; Get the second minimum valued string ; Updated integer value ; Create new entry for the queue ; Add to the queue ; Print the only remaining string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Priority { string s ; int count ; } ; struct Compare { int operator() ( Priority a , Priority b ) { if ( a . count > b . count ) return 1 ; else if ( a . count < b . count ) return -1 ; return 0 ; } } ; static void FindString ( string str [ ] , int num [ ] , int n ) { priority_queue < int , vector < Priority > , Compare > p ; for ( int i = 0 ; i < n ; i ++ ) { Priority x ; x . s = str [ i ] ; x . count = num [ i ] ; p . push ( x ) ; } while ( p . size ( ) > 1 ) { Priority x = p . top ( ) ; p . pop ( ) ; Priority y = p . top ( ) ; p . pop ( ) ; int temp = x . count + y . count ; string sb = x . s + y . s ; Priority z ; z . count = temp ; z . s = sb ; p . push ( z ) ; } Priority z = p . top ( ) ; p . pop ( ) ; cout << z . s << endl ; } int main ( ) { string str [ ] = { " Geeks " , " For " , " Geeks " } ; int num [ ] = { 2 , 3 , 7 } ; int n = sizeof ( num ) / sizeof ( int ) ; FindString ( str , num , n ) ; }
Smallest subsequence having GCD equal to GCD of given array | C ++ program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of array . ; Generate all possible pairs . ; If gcd of current pair equal to gcdArr ; Print current pair of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSmallSub ( int arr [ ] , int N ) { int gcdArr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { gcdArr = __gcd ( gcdArr , arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == gcdArr ) { cout << arr [ i ] << " ▁ " ; return ; } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( __gcd ( arr [ i ] , arr [ j ] ) == gcdArr ) { cout << arr [ i ] << " ▁ " << arr [ j ] ; return ; } } } } int main ( ) { int arr [ ] = { 4 , 6 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSmallSub ( arr , N ) ; }
Minimum cost to modify a string | C ++ implementation of the approach ; Function to return the minimum cost ; Initialize result ; To store the frequency of characters of the string ; Initialize array with 0 ; Update the frequencies of the characters of the string ; Loop to check all windows from a - z where window size is K ; Starting index of window ; Ending index of window ; Check if the string contains character ; Check if the character is on left side of window find the cost of modification for character add value to count calculate nearest distance of modification ; Check if the character is on right side of window find the cost of modification for character add value to count calculate nearest distance of modification ; Find the minimum of all costs for modifying the string ; Loop to check all windows Here window contains characters before z and after z of window size K ; Starting index of window ; Ending index of window ; Check if the string contains character ; If characters are outside window find the cost for modifying character add value to count ; Find the minimum of all costs for modifying the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string str , int K ) { int n = str . length ( ) ; int res = 999999999 , count = 0 , a , b ; int cnt [ 27 ] ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int i = 0 ; i < n ; i ++ ) cnt [ str [ i ] - ' a ' + 1 ] ++ ; for ( int i = 1 ; i < ( 26 - K + 1 ) ; i ++ ) { a = i ; b = i + K ; count = 0 ; for ( int j = 1 ; j <= 26 ; j ++ ) { if ( cnt [ j ] > 0 ) { if ( j >= a && j >= b ) count = count + ( min ( j - b , 25 - j + a + 1 ) ) * cnt [ j ] ; else if ( j <= a && j <= b ) count = count + ( min ( a - j , 25 + j - b + 1 ) ) * cnt [ j ] ; } } res = min ( res , count ) ; } for ( int i = 26 - K + 1 ; i <= 26 ; i ++ ) { a = i ; b = ( i + K ) % 26 ; count = 0 ; for ( int j = 1 ; j <= 26 ; j ++ ) { if ( cnt [ j ] > 0 ) { if ( j >= b and j <= a ) count = count + ( min ( j - b , a - j ) ) * cnt [ j ] ; } } res = min ( res , count ) ; } return res ; } int main ( ) { string str = " abcdefghi " ; int K = 2 ; cout << minCost ( str , K ) ; return 0 ; }
Generate all binary strings of length n with sub | C ++ implementation of the approach ; Utility function to print the given binary string ; This function will be called recursively to generate the next bit for given binary string according to its current state ; Base - case : if the generated binary string meets the required length and the pattern "01" appears twice ; nextbit needs to be 0 because each time we call the function recursively , we call 2 times for 2 cases : next bit is 0 or 1 The is to assure that the binary string is printed one time only ; Generate the next bit for str and call recursive ; Assign first bit ; The next generated bit will wither be 0 or 1 ; If pattern "01" occurrence is < 2 ; Set next bit ; If pattern "01" appears then increase the occurrence of pattern ; Else pattern "01" occurrence equals 2 ; If previous bit is 0 then next bit cannot be 1 ; Otherwise ; Driver code ; Length of the resulting strings must be at least 4 ; Generate all binary strings of length n with sub - string "01" appearing twice
#include <iostream> NEW_LINE #include <stdlib.h> NEW_LINE using namespace std ; void printBinStr ( int * str , int len ) { for ( int i = 0 ; i < len ; i ++ ) { cout << str [ i ] ; } cout << endl ; } void generateBinStr ( int * str , int len , int currlen , int occur , int nextbit ) { if ( currlen == len ) { if ( occur == 2 && nextbit == 0 ) printBinStr ( str , len ) ; return ; } if ( currlen == 0 ) { str [ 0 ] = nextbit ; generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } else { if ( occur < 2 ) { str [ currlen ] = nextbit ; if ( str [ currlen - 1 ] == 0 && nextbit == 1 ) { occur += 1 ; } generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } else { if ( str [ currlen - 1 ] == 0 && nextbit == 1 ) { return ; } else { str [ currlen ] = nextbit ; generateBinStr ( str , len , currlen + 1 , occur , 0 ) ; generateBinStr ( str , len , currlen + 1 , occur , 1 ) ; } } } } int main ( ) { int n = 5 ; if ( n < 4 ) cout << -1 ; else { int * str = new int [ n ] ; generateBinStr ( str , n , 0 , 0 , 0 ) ; generateBinStr ( str , n , 0 , 0 , 1 ) ; } return 0 ; }
Print last character of each word in a string | CPP implementation of the approach ; Function to print the last character of each word in the given string ; Now , last word is also followed by a space ; If current character is a space ; Then previous character must be the last character of some word ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printLastChar ( string str ) { str = str + " ▁ " ; for ( int i = 1 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ▁ ' ) cout << str [ i - 1 ] << " ▁ " ; } } int main ( ) { string str = " Geeks ▁ for ▁ Geeks " ; printLastChar ( str ) ; }
Maximum length of balanced string after swapping and removal of characters | C ++ implementation of the approach ; Function to return the length of the longest balanced sub - string ; To store the count of parentheses ; Traversing the string ; Check type of parentheses and incrementing count for it ; Sum all pair of balanced parentheses ; Driven code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxBalancedStr ( string s ) { int open1 = 0 , close1 = 0 ; int open2 = 0 , close2 = 0 ; int open3 = 0 , close3 = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { switch ( s [ i ] ) { case ' ( ' : open1 ++ ; break ; case ' ) ' : close1 ++ ; break ; case ' { ' : open2 ++ ; break ; case ' } ' : close2 ++ ; break ; case ' [ ' : open3 ++ ; break ; case ' ] ' : close3 ++ ; break ; } } int maxLen = 2 * min ( open1 , close1 ) + 2 * min ( open2 , close2 ) + 2 * min ( open3 , close3 ) ; return maxLen ; } int main ( ) { string s = " ) ) [ ] ] ( ( " ; cout << maxBalancedStr ( s ) ; return 0 ; }
Bitwise OR of N binary strings | C ++ implementation of the approach ; Function to return the bitwise OR of all the binary strings ; Get max size and reverse each string Since we have to perform OR operation on bits from right to left Reversing the string will make it easier to perform operation from left to right ; Add 0 s to the end of strings if needed ; Perform OR operation on each bit ; Reverse the resultant string to get the final string ; Return the final string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string strBitwiseOR ( string * arr , int n ) { string res ; int max_size = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { max_size = max ( max_size , ( int ) arr [ i ] . size ( ) ) ; reverse ( arr [ i ] . begin ( ) , arr [ i ] . end ( ) ) ; } for ( int i = 0 ; i < n ; i ++ ) { string s ; for ( int j = 0 ; j < max_size - arr [ i ] . size ( ) ; j ++ ) s += '0' ; arr [ i ] = arr [ i ] + s ; } for ( int i = 0 ; i < max_size ; i ++ ) { int curr_bit = 0 ; for ( int j = 0 ; j < n ; j ++ ) curr_bit = curr_bit | ( arr [ j ] [ i ] - '0' ) ; res += ( curr_bit + '0' ) ; } reverse ( res . begin ( ) , res . end ( ) ) ; return res ; } int main ( ) { string arr [ ] = { "10" , "11" , "1000001" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << strBitwiseOR ( arr , n ) ; return 0 ; }
Minimum cost to make two strings same | C ++ implementation of the approach ; Function to return the minimum cost to make the configuration of both the strings same ; Iterate and find the cost ; Find the minimum cost ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCost ( string s1 , string s2 , int a , int b , int c , int d , int n ) { int cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s1 [ i ] == s2 [ i ] ) continue ; else { if ( ( s1 [ i ] == '1' && s2 [ i ] == '2' ) || ( s2 [ i ] == '1' && s1 [ i ] == '2' ) ) cost += min ( d , min ( a , b + c ) ) ; else if ( ( s1 [ i ] == '2' && s2 [ i ] == '3' ) || ( s2 [ i ] == '2' && s1 [ i ] == '3' ) ) cost += min ( d , min ( b , a + c ) ) ; else if ( ( s1 [ i ] == '1' && s2 [ i ] == '3' ) || ( s2 [ i ] == '1' && s1 [ i ] == '3' ) ) cost += min ( d , min ( c , a + b ) ) ; } } return cost ; } int main ( ) { string s1 = "121" ; string s2 = "223" ; int a = 2 , b = 3 , c = 4 , d = 10 ; int n = s1 . size ( ) ; cout << findCost ( s1 , s2 , a , b , c , d , n ) ; return 0 ; }
Count the number of common divisors of the given strings | C ++ implementation of the approach ; Function that returns true if sub - string s [ 0. . . k ] is repeated a number of times to generate string s ; Function to return the count of common divisors ; If the length of the sub - string divides length of both the strings ; If prefixes match in both the strings ; If both the strings can be generated by repeating the current prefix ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( string s , int k ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( s [ i ] != s [ i % k ] ) return false ; return true ; } int countCommonDivisors ( string a , string b ) { int ct = 0 ; int n = a . size ( ) , m = b . size ( ) ; for ( int i = 1 ; i <= min ( n , m ) ; i ++ ) { if ( n % i == 0 && m % i == 0 ) if ( a . substr ( 0 , i ) == b . substr ( 0 , i ) ) if ( check ( a , i ) && check ( b , i ) ) ct ++ ; } return ct ; } int main ( ) { string a = " xaxa " , b = " xaxaxaxa " ; cout << countCommonDivisors ( a , b ) ; return 0 ; }
Level order traversal line by line | Set 3 ( Using One Queue ) | C ++ program to print levels line by line ; A Binary Tree Node ; Function to do level order traversal line by line ; Create an empty queue for level order traversal ; to store front element of queue . ; Pushing root node into the queue . ; Pushing delimiter into the queue . ; condition to check occurrence of next level . ; condition to check the occurence of next level ; pushing left child of current node . ; pushing right child of current node . ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown above
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { struct node * left ; int data ; struct node * right ; } ; void levelOrder ( node * root ) { if ( root == NULL ) return ; queue < node * > q ; node * curr ; q . push ( root ) ; q . push ( NULL ) ; while ( q . size ( ) > 1 ) { curr = q . front ( ) ; q . pop ( ) ; if ( curr == NULL ) { q . push ( NULL ) ; cout << " STRNEWLINE " ; } else { if ( curr -> left ) q . push ( curr -> left ) ; if ( curr -> right ) q . push ( curr -> right ) ; cout << curr -> data << " ▁ " ; } } } node * newNode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } 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 -> right = newNode ( 6 ) ; levelOrder ( root ) ; return 0 ; }
Convert given string so that it holds only distinct characters | C ++ implementation of the approach ; Function to return the index of the character that has 0 occurrence starting from index i ; If current character has 0 occurrence ; If no character has 0 occurrence ; Function to return the modified string which consists of distinct characters ; String cannot consist of all distinct characters ; Count the occurrences for each of the character ; Index for the first character that hasn 't appeared in the string ; If current character appeared more than once then it has to be replaced with some character that hasn 't occurred yet ; Decrement current character 's occurrence by 1 ; Replace the character ; Update the new character ' s ▁ occurrence ▁ ▁ This ▁ step ▁ can ▁ also ▁ be ▁ skipped ▁ as ▁ ▁ we ' ll never encounter this character in the string because it has been added just now ; Find the next character that hasn 't occurred yet ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nextZero ( int i , int occurrences [ ] ) { while ( i < 26 ) { if ( occurrences [ i ] == 0 ) return i ; i ++ ; } return -1 ; } string getModifiedString ( string str ) { int n = str . length ( ) ; if ( n > 26 ) return " - 1" ; string ch = str ; int i , occurrences [ 26 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) occurrences [ ch [ i ] - ' a ' ] ++ ; int index = nextZero ( 0 , occurrences ) ; for ( i = 0 ; i < n ; i ++ ) { if ( occurrences [ ch [ i ] - ' a ' ] > 1 ) { occurrences [ ch [ i ] - ' a ' ] -- ; ch [ i ] = ( char ) ( ' a ' + index ) ; occurrences [ index ] = 1 ; index = nextZero ( index + 1 , occurrences ) ; } } cout << ch << endl ; } int main ( ) { string str = " geeksforgeeks " ; getModifiedString ( str ) ; }
Replace all occurrences of a string with space | C ++ implementation to extract the secret message ; Function to extract the secret message ; Replacing all occurrences of Sub in Str by empty spaces ; Removing unwanted spaces in the start and end of the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string trim ( const string & s ) { auto start = s . begin ( ) ; while ( start != s . end ( ) && isspace ( * start ) ) start ++ ; auto end = s . end ( ) ; do { end -- ; } while ( distance ( start , end ) > 0 && isspace ( * end ) ) ; return string ( start , end + 1 ) ; } string extractSecretMessage ( string str , string sub ) { size_t pos ; while ( ( pos = str . find ( sub ) ) != string :: npos ) str . replace ( pos , 3 , " ▁ " ) ; str = trim ( str ) ; return str ; } int main ( int argc , char const * argv [ ] ) { string str = " LIELIEILIEAMLIECOOL " ; string sub = " LIE " ; cout << extractSecretMessage ( str , sub ) << endl ; return 0 ; }
Sub | C ++ implementation of the approach ; Function to return the count of sub - strings starting from startIndex that are also the prefixes of str ; Function to return the count of all possible sub - strings of str that are also the prefixes of str ; If current character is equal to the starting character of str ; Driver code ; Function Call
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int subStringsStartingHere ( string str , int n , int startIndex ) { int count = 0 , i = 1 ; while ( i <= n ) { if ( str . substr ( 0 , i ) == str . substr ( startIndex , i ) ) { count ++ ; } else break ; i ++ ; } return count ; } int countSubStrings ( string str , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) count += subStringsStartingHere ( str , n , i ) ; } return count ; } int main ( ) { string str = " abcda " ; int n = str . length ( ) ; cout << ( countSubStrings ( str , n ) ) ; }
Binary Search a String | CPP program to implement Binary Search for strings ; Returns index of x if it is present in arr [ ] , else return - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( string arr [ ] , string x , int n ) { int l = 0 ; int r = n - 1 ; while ( l <= r ) { int m = l + ( r - l ) / 2 ; if ( x == ( arr [ m ] ) ) res = 0 ; if ( res == 0 ) return m ; if ( x > ( arr [ m ] ) ) l = m + 1 ; else r = m - 1 ; } return -1 ; } int main ( ) { string arr [ ] = { " contribute " , " geeks " , " ide " , " practice " } ; string x = " ide " ; int n = 4 ; int result = binarySearch ( arr , x , n ) ; if ( result == -1 ) cout << ( " Element ▁ not ▁ present " ) ; else cout << ( " Element ▁ found ▁ at ▁ index ▁ " ) << result ; }
Count characters in a string whose ASCII values are prime | C ++ implementation of above approach ; Function to find prime characters in the string ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a Boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; 0 and 1 are not primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Traverse all the characters ; Driver program ; print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define max_val 257 NEW_LINE int PrimeCharacters ( string s ) { vector < bool > prime ( max_val + 1 , true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( prime [ int ( s [ i ] ) ] ) count ++ ; } return count ; } int main ( ) { string S = " geeksforgeeks " ; cout << PrimeCharacters ( S ) ; return 0 ; }
Length of largest subsequence consisting of a pair of alternating digits | C ++ program for the above approach ; Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of the string ; Increment length ; Increment length ; Update maxi ; Check if maxi is not equal to 1 the print it otherwise print 0 ; Driver Code ; Given string ; Function call
#include <iostream> NEW_LINE using namespace std ; void largestSubsequence ( string s ) { int maxi = 0 ; char prev1 ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { if ( i != j ) { int len = 0 ; prev1 = j + '0' ; for ( int k = 0 ; k < s . size ( ) ; k ++ ) { if ( s [ k ] == i + '0' && prev1 == j + '0' ) { prev1 = s [ k ] ; len ++ ; } else if ( s [ k ] == j + '0' && prev1 == i + '0' ) { prev1 = s [ k ] ; len ++ ; } } maxi = max ( len , maxi ) ; } } } if ( maxi != 1 ) cout << maxi << endl ; else cout << 0 << endl ; } int main ( ) { string s = "1542745249842" ; largestSubsequence ( s ) ; return 0 ; }
Students with maximum average score of three subjects | C ++ program to find the list of students having maximum average score ; Function to find the list of students having maximum average score Driver code ; Variables to store average score of a student and maximum average score ; List to store names of students having maximum average score ; Traversing the file data ; finding average score of a student ; Clear the list and add name of student having current maximum average score in the list ; Printing the maximum average score and names of students having this maximum average score as per the order in the file . ; Driver code ; Number of elements in string array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getStudentsList ( string file [ ] , int n ) { int avgScore ; int maxAvgScore = INT_MIN ; vector < string > names ; for ( int i = 0 ; i < n ; i += 4 ) { avgScore = ( stoi ( file [ i + 1 ] ) + stoi ( file [ i + 2 ] ) + stoi ( file [ i + 3 ] ) ) / 3 ; if ( avgScore > maxAvgScore ) { maxAvgScore = avgScore ; names . clear ( ) ; names . push_back ( file [ i ] ) ; } else if ( avgScore == maxAvgScore ) names . push_back ( file [ i ] ) ; } for ( int i = 0 ; i < names . size ( ) ; i ++ ) { cout << names [ i ] + " ▁ " ; } cout << maxAvgScore ; } int main ( ) { string file [ ] = { " Shrikanth " , "20" , "30" , "10" , " Ram " , "100" , "50" , "10" } ; int n = sizeof ( file ) / sizeof ( file [ 0 ] ) ; getStudentsList ( file , n ) ; }
Number of sub | C ++ program to find the number of sub - strings of s1 which are anagram of any sub - string of s2 ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of string pat [ ] in string txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; cout << pat << " ▁ " << txt << " ▁ " ; ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Function to return the number of sub - strings of s1 that are anagrams of any sub - string of s2 ; initializing variables ; outer loop for picking starting point ; loop for different length of substrings ; If s2 has any substring which is anagram of s1 . substr ( i , len ) ; increment the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ALL_CHARS 256 NEW_LINE bool compare ( char * arr1 , char * arr2 ) { for ( int i = 0 ; i < ALL_CHARS ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return false ; return true ; } bool search ( string pat , string txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int i ; char countP [ ALL_CHARS ] = { 0 } ; char countTW [ ALL_CHARS ] = { 0 } ; for ( i = 0 ; i < M ; i ++ ) { ( countP [ pat [ i ] ] ) ++ ; ( countTW [ txt [ i ] ] ) ++ ; } for ( i = M ; i < N ; i ++ ) { if ( compare ( countP , countTW ) ) { return true ; } ( countTW [ txt [ i ] ] ) ++ ; countTW [ txt [ i - M ] ] -- ; } if ( compare ( countP , countTW ) ) return true ; return false ; } int calculatesubString ( string s1 , string s2 , int n ) { int count = 0 , j = 0 , x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int len = 1 ; len <= n - i ; len ++ ) { if ( search ( s1 . substr ( i , len ) , s2 ) ) { count = count + 1 ; } } } return count ; } int main ( ) { string str1 = " PLEASEHELPIMTRAPPED " ; string str2 = " INAKICKSTARTFACTORY " ; int len = str1 . length ( ) ; cout << calculatesubString ( str1 , str2 , len ) ; return 0 ; }
Sum of the alphabetical values of the characters of a string | C ++ implementation of the approach ; Function to find string score ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int strScore ( string str [ ] , string s , int n ) { int score = 0 , index ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == s ) { for ( int j = 0 ; j < s . length ( ) ; j ++ ) score += s [ j ] - ' a ' + 1 ; index = i + 1 ; break ; } } score = score * index ; return score ; } int main ( ) { string str [ ] = { " sahil " , " shashanak " , " sanjit " , " abhinav " , " mohit " } ; string s = " abhinav " ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; int score = strScore ( str , s , n ) ; cout << score << endl ; return 0 ; }
Minimum swaps to group similar characters side by side ? | checks whether a string has similar characters side by side ; If similar chars side by side , continue ; If we have found a char equal to current char and does not exist side to it , return false ; counts min swap operations to convert a string that has similar characters side by side ; Base case ; considering swapping of i and l chars ; Backtrack ; not considering swapping of i and l chars ; taking min of above two ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool sameCharAdj ( string str ) { int n = str . length ( ) , i ; set < char > st ; st . insert ( str [ 0 ] ) ; for ( i = 1 ; i < n ; i ++ ) { if ( str [ i ] == str [ i - 1 ] ) continue ; if ( st . find ( str [ i ] ) != st . end ( ) ) return false ; st . insert ( str [ i ] ) ; } return true ; } int minSwaps ( string str , int l , int r , int cnt , int minm ) { if ( l == r ) { if ( sameCharAdj ( str ) ) return cnt ; else return INT_MAX ; } for ( int i = l + 1 ; i <= r ; i ++ ) { swap ( str [ i ] , str [ l ] ) ; cnt ++ ; int x = minSwaps ( str , l + 1 , r , cnt , minm ) ; swap ( str [ i ] , str [ l ] ) ; cnt -- ; int y = minSwaps ( str , l + 1 , r , cnt , minm ) ; minm = min ( minm , min ( x , y ) ) ; } return minm ; } int main ( ) { string str = " abbaacb " ; int n = str . length ( ) , cnt = 0 , minm = INT_MAX ; cout << minSwaps ( str , 0 , n - 1 , cnt , minm ) << endl ; return 0 ; }
Union | Naive implementation of find ; Naive implementation of union ( )
int find ( int parent [ ] , int i ) { if ( parent [ i ] == -1 ) return i ; return find ( parent , parent [ i ] ) ; } void Union ( int parent [ ] , int x , int y ) { int xset = find ( parent , x ) ; int yset = find ( parent , y ) ; parent [ xset ] = yset ; }
Get K | CPP implementation of above approach ; Function to return the K - th letter from new String . ; finding size = length of new string S ' ; get the K - th letter ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string K_thletter ( string S , int K ) { int N = S . size ( ) ; long size = 0 ; for ( int i = 0 ; i < N ; ++ i ) { if ( isdigit ( S [ i ] ) ) size = size * ( S [ i ] - '0' ) ; else size += 1 ; } for ( int i = N - 1 ; i >= 0 ; -- i ) { K %= size ; if ( K == 0 && isalpha ( S [ i ] ) ) return ( string ) " " + S [ i ] ; if ( isdigit ( S [ i ] ) ) size = size / ( S [ i ] - '0' ) ; else size -= 1 ; } } int main ( ) { string S = " geeks2for2" ; int K = 15 ; cout << K_thletter ( S , K ) ; return 0 ; }
Minimum number of Parentheses to be added to make it valid | C ++ Program to find minimum number of ' ( ' or ' ) ' must be added to make Parentheses string valid . ; Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minParentheses ( string p ) { int bal = 0 ; int ans = 0 ; for ( int i = 0 ; i < p . length ( ) ; ++ i ) { bal += p [ i ] == ' ( ' ? 1 : -1 ; if ( bal == -1 ) { ans += 1 ; bal += 1 ; } } return bal + ans ; } int main ( ) { string p = " ( ) ) " ; cout << minParentheses ( p ) ; return 0 ; }
Check if suffix and prefix of a string are palindromes | C ++ implementation of the approach ; Function to check whether the string is a palindrome ; reverse the string to compare with the original string ; check if both are same ; Function to check whether the string has prefix and suffix substrings of length greater than 1 which are palindromes . ; check all prefix substrings ; check if the prefix substring is a palindrome ; If we did not find any palindrome prefix of length greater than 1. ; check all suffix substrings , as the string is reversed now ; check if the suffix substring is a palindrome ; If we did not find a suffix ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string r ) { string p = r ; reverse ( p . begin ( ) , p . end ( ) ) ; return ( r == p ) ; } bool CheckStr ( string s ) { int l = s . length ( ) ; int i ; for ( i = 2 ; i <= l ; i ++ ) { if ( isPalindrome ( s . substr ( 0 , i ) ) ) break ; } if ( i == ( l + 1 ) ) return false ; i = 2 ; for ( i = 2 ; i <= l ; i ++ ) { if ( isPalindrome ( s . substr ( l - i , i ) ) ) return true ; } return false ; } int main ( ) { string s = " abccbarfgdbd " ; if ( CheckStr ( s ) ) cout << " YES STRNEWLINE " ; else cout << " NO STRNEWLINE " ; return 0 ; }
Count of ways to generate a Matrix with product of each row and column as 1 or | C ++ implementation of the above approach ; Function to return the number of possible ways ; Check if product can be - 1 ; Driver Code
#include using namespace std ; void Solve ( int N , int M ) { int temp = ( N - 1 ) * ( M - 1 ) ; int ans = pow ( 2 , temp ) ; if ( ( N + M ) % 2 != 0 ) cout << ans ; else cout << 2 * ans ; cout << endl ; } int main ( ) { int N = 3 ; int M = 3 ; Solve ( N , M ) ; return 0 ; }
Rotations of a Binary String with Odd Value | CPP program to find count of rotations with odd value . ; function to calculate total odd decimal equivalent ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int oddEquivalent ( string s , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) count ++ ; } return count ; } int main ( ) { string s = "1011011" ; int n = s . length ( ) ; cout << oddEquivalent ( s , n ) ; return 0 ; }
Minimum operation require to make first and last character same | C ++ program to find minimum operation require to make first and last character same ; Return the minimum operation require to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize result ; Traverse through all characters ; Find first occurrence ; Update result for subsequent occurrences ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 256 NEW_LINE int minimumOperation ( string s ) { int n = s . length ( ) ; vector < int > first_occ ( MAX , -1 ) ; int res = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { char x = s [ i ] ; if ( first_occ [ x ] == -1 ) first_occ [ x ] = i ; else { int last_occ = ( n - i - 1 ) ; res = min ( res , first_occ [ x ] + last_occ ) ; } } return res ; } int main ( ) { string s = " bacdefghipalop " ; cout << minimumOperation ( s ) << endl ; return 0 ; }
Lexicographically smallest and largest substring of size k | CPP program to find lexicographically largest and smallest substrings of size k . ; Initialize min and max as first substring of size k ; Consider all remaining substrings . We consider every substring ending with index i . ; Print result . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getSmallestAndLargest ( string s , int k ) { string currStr = s . substr ( 0 , k ) ; string lexMin = currStr ; string lexMax = currStr ; for ( int i = k ; i < s . length ( ) ; i ++ ) { currStr = currStr . substr ( 1 , k ) + s [ i ] ; if ( lexMax < currStr ) lexMax = currStr ; if ( lexMin > currStr ) lexMin = currStr ; } cout << ( lexMin ) << endl ; cout << ( lexMax ) << endl ; } int main ( ) { string str = " GeeksForGeeks " ; int k = 3 ; getSmallestAndLargest ( str , k ) ; }
Program to print the initials of a name with the surname | C ++ program to print the initials of a name with the surname ; to remove any leading or trailing spaces ; to store extracted words ; forming the word ; when space is encountered it means the name is completed and thereby extracted ; printing the first letter of the name in capital letters ; for the surname , we have to print the entire surname and not just the initial string " t " has the surname now ; first letter of surname in capital letter ; rest of the letters in small ; printing surname ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printInitials ( string str ) { int len = str . length ( ) ; str . erase ( 0 , str . find_first_not_of ( ' ▁ ' ) ) ; str . erase ( str . find_last_not_of ( ' ▁ ' ) + 1 ) ; string t = " " ; for ( int i = 0 ; i < len ; i ++ ) { char ch = str [ i ] ; if ( ch != ' ▁ ' ) t = t + ch ; else { cout << ( char ) toupper ( t [ 0 ] ) << " . ▁ " ; t = " " ; } } string temp = " " ; for ( int j = 0 ; j < t . length ( ) ; j ++ ) { if ( j == 0 ) temp = temp + ( char ) toupper ( t [ 0 ] ) ; else temp = temp + ( char ) tolower ( t [ j ] ) ; } cout << temp << endl ; } int main ( ) { string str = " ishita ▁ bhuiya " ; printInitials ( str ) ; }
Count of strings that can be formed from another string using each character at | / C ++ program to print the number of times str2 can be formed from str1 using the characters of str1 only once ; Function to find the number of str2 that can be formed using characters of str1 ; iterate and mark the frequencies of all characters in str1 ; find the minimum frequency of every character in str1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfTimes ( string str1 , string str2 ) { int freq [ 26 ] = { 0 } ; int freq2 [ 26 ] = { 0 } ; int l1 = str1 . length ( ) ; int l2 = str2 . length ( ) ; for ( int i = 0 ; i < l1 ; i ++ ) freq [ str1 [ i ] - ' a ' ] += 1 ; for ( int i = 0 ; i < l2 ; i ++ ) freq2 [ str2 [ i ] - ' a ' ] += 1 ; int count = INT_MAX ; for ( int i = 0 ; i < l2 ; i ++ ) { if ( freq2 [ str2 [ i ] - ' a ' ] != 0 ) count = min ( count , freq [ str2 [ i ] - ' a ' ] / freq2 [ str2 [ i ] - ' a ' ] ) ; } return count ; } int main ( ) { string str1 = " foreeksgekseg " ; string str2 = " geeks " ; cout << findNumberOfTimes ( str1 , str2 ) << endl ; return 0 ; }
String transformation using XOR and OR | C ++ program to check if string1 can be converted to string2 using XOR and OR operations ; function to check if conversion is possible or not ; if lengths are different ; iterate to check if both strings have 1 ; to check if there is even one 1 in string s1 ; to check if there is even one 1 in string s2 ; if both strings have only '0' ; if both string do not have a '1' . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool solve ( string s1 , string s2 ) { bool flag1 = 0 , flag2 = 0 ; if ( s1 . length ( ) != s2 . length ( ) ) return false ; int l = s1 . length ( ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( s1 [ i ] == '1' ) flag1 = 1 ; if ( s2 [ i ] == '1' ) flag2 = 1 ; if ( flag1 && flag2 ) return true ; } if ( ! flag1 && ! flag2 ) return true ; return false ; } int main ( ) { string s1 = "100101" ; string s2 = "100000" ; if ( solve ( s1 , s2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Smallest alphabet greater than a given character | C ++ Program to find the smallest character from the given set of letter , which is greater than the target element ; Returns the smallest character from the given set of letters that is greater than K ; Take the first element as l and the rightmost element as r ; if this while condition does not satisfy simply return the first element . ; Return the smallest element ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; char nextGreatestAlphabet ( vector < char > & alphabets , char K ) { int n = alphabets . size ( ) ; if ( K >= alphabets [ n - 1 ] ) return alphabets [ 0 ] ; int l = 0 , r = alphabets . size ( ) - 1 ; int ans = -1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( alphabets [ mid ] > K ) { r = mid - 1 ; ans = mid ; } else l = mid + 1 ; } return alphabets [ ans ] ; } int main ( ) { vector < char > letters { ' A ' , ' K ' , ' S ' } ; char K = ' L ' ; char result = nextGreatestAlphabet ( letters , K ) ; cout << result << endl ; return 0 ; }
Longest substring of 0 s in a string formed by k concatenations | C ++ code to find maximum length of substring that contains only 0 's ; Function to calculate maximum length of substring containing only zero ; loop to first calculate longest substring in string ; if all elements in string are '0' ; Else , find size of prefix and suffix containing only zeroes ; Calculate prefix containing only zeroes ; Calculate suffix containing only zeroes ; if k <= 1 then there is no need to take prefix + suffix into account ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int subzero ( string str , int k ) { int ans = 0 , curr = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str [ i ] == '0' ) curr ++ ; else curr = 0 ; ans = max ( ans , curr ) ; } if ( ans == len ) return len * k ; else { int pre = 0 , suff = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) pre ++ ; else break ; } for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' ) suff ++ ; else break ; } if ( k > 1 ) ans = max ( ans , pre + suff ) ; return ans ; } } int main ( ) { string str = "00100110" ; int k = 5 ; cout << subzero ( str , k ) ; return 0 ; }
Find the largest number smaller than integer N with maximum number of set bits | C ++ implementation to Find the largest number smaller than integer N with maximum number of set bits ; Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int n ) { int num = 0 ; int max_setBits = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { int setBits = __builtin_popcount ( i ) ; if ( setBits >= max_setBits ) { num = i ; max_setBits = setBits ; } } return num ; } int main ( ) { int N = 345 ; cout << largestNum ( N ) ; return 0 ; }
Find nth term of the Dragon Curve Sequence | CPP code to find nth term of the Dragon Curve Sequence ; function to generate the nth term ; first term ; generating each term of the sequence ; loop to generate the ith term ; add character from the original string ; add alternate 0 and 1 in between ; if previous added term was '0' then add '1' ; now current term becomes previous term ; if previous added term was '1' , then add '0' ; now current term becomes previous term ; s becomes the ith term of the sequence ; Driver program ; Taking inputs ; generate nth term of dragon curve sequence ; Printing output
#include <bits/stdc++.h> NEW_LINE using namespace std ; string Dragon_Curve_Sequence ( int n ) { string s = "1" ; for ( int i = 2 ; i <= n ; i ++ ) { string temp = "1" ; char prev = '1' , zero = '0' , one = '1' ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { temp += s [ j ] ; if ( prev == '0' ) { temp += one ; prev = one ; } else { temp += zero ; prev = zero ; } } s = temp ; } return s ; } int main ( ) { int n = 4 ; string s = Dragon_Curve_Sequence ( n ) ; cout << s << " STRNEWLINE " ; }
Number of substrings of a string | CPP program to count number of substrings of a string ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countNonEmptySubstr ( string str ) { int n = str . length ( ) ; return n * ( n + 1 ) / 2 ; } int main ( ) { string s = " abcde " ; cout << countNonEmptySubstr ( s ) ; return 0 ; }
Count substrings with each character occurring at most k times | CPP program to count number of substrings in which each character has count less than or equal to k . ; variable to store count of substrings . ; array to store count of each character . ; Initialize all characters count to zero . ; increment character count ; check only the count of current character because only the count of this character is changed . The ending point is incremented to current position only if all other characters have count at most k and hence their count is not checked . If count is less than k , then increase ans by 1. ; if count is less than k , then break as subsequent substrings for this starting point will also have count greater than k and hence are reduntant to check . ; return the final count of substrings . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubstrings ( string s , int k ) { int ans = 0 ; int cnt [ 26 ] ; int i , j , n = s . length ( ) ; for ( i = 0 ; i < n ; i ++ ) { memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( j = i ; j < n ; j ++ ) { cnt [ s [ j ] - ' a ' ] ++ ; if ( cnt [ s [ j ] - ' a ' ] <= k ) ans ++ ; else break ; } } return ans ; } int main ( ) { string S = " aaabb " ; int k = 2 ; cout << findSubstrings ( S , k ) ; return 0 ; }
Check if characters of one string can be swapped to form other | C ++ program to check if characters of one string can be swapped to form other ; if length is not same print no ; Count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; Since lengths are same , some value would definitely become negative if result is false . ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; bool targetstring ( string str1 , string str2 ) { int l1 = str1 . length ( ) ; int l2 = str2 . length ( ) ; if ( l1 != l2 ) return false ; int map [ MAX ] = { 0 } ; for ( int i = 0 ; i < l1 ; i ++ ) map [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < l2 ; i ++ ) { map [ str2 [ i ] - ' a ' ] -- ; if ( map [ str2 [ i ] - ' a ' ] < 0 ) return false ; } return true ; } int main ( ) { string str1 = " geeksforgeeks " ; string str2 = " geegeeksksfor " ; if ( targetstring ( str1 , str2 ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Find the Number which contain the digit d | C ++ program to print the number which contain the digit d from 0 to n ; Returns true if d is present as digit in number x . ; Breal loop if d is present as digit ; If loop broke ; function to display the values ; Check all numbers one by one ; checking for digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDigitPresent ( int x , int d ) { while ( x > 0 ) { if ( x % 10 == d ) break ; x = x / 10 ; } return ( x > 0 ) ; } void printNumbers ( int n , int d ) { for ( int i = 0 ; i <= n ; i ++ ) if ( i == d || isDigitPresent ( i , d ) ) cout << i << " ▁ " ; } int main ( ) { int n = 47 , d = 7 ; printNumbers ( n , d ) ; return 0 ; }
Find one extra character in a string | CPP program to find extra character in one string ; store string values in map ; store second string in map with frequency ; store first string in map with frequency ; if the frequency is 1 then this character is which is added extra ; Driver code ; given string ; find Extra Character
#include <bits/stdc++.h> NEW_LINE using namespace std ; char findExtraCharcter ( string strA , string strB ) { unordered_map < char , int > m1 ; for ( int i = 0 ; i < strB . length ( ) ; i ++ ) m1 [ strB [ i ] ] ++ ; for ( int i = 0 ; i < strA . length ( ) ; i ++ ) m1 [ strA [ i ] ] -- ; for ( auto h1 = m1 . begin ( ) ; h1 != m1 . end ( ) ; h1 ++ ) { if ( h1 -> second == 1 ) return h1 -> first ; } } int main ( ) { string strA = " abcd " ; string strB = " cbdad " ; cout << findExtraCharcter ( strA , strB ) ; }
Find one extra character in a string | CPP program to find extra character in one string ; result store the result ; traverse string A till end and xor with res ; xor with res ; traverse string B till end and xor with res ; xor with res ; print result at the end ; given string
#include <iostream> NEW_LINE using namespace std ; char findExtraCharcter ( string strA , string strB ) { int res = 0 , i ; for ( i = 0 ; i < strA . length ( ) ; i ++ ) { res ^= strA [ i ] ; } for ( i = 0 ; i < strB . length ( ) ; i ++ ) { res ^= strB [ i ] ; } return ( ( char ) ( res ) ) ; } int main ( ) { string strA = " abcd " ; string strB = " cbdad " ; cout << findExtraCharcter ( strA , strB ) ; return 0 ; }
Find one extra character in a string | C ++ program to find extra character in one string ; Determine string with extra character . ; Add character codes of both the strings ; Add last character code of large string . ; Minus the character code of smaller string from the character code of large string . The result will be the extra character code . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char findExtraCharacter ( string s1 , string s2 ) { string smallStr ; string largeStr ; if ( s1 . size ( ) > s2 . size ( ) ) { smallStr = s2 ; largeStr = s1 ; } else { smallStr = s1 ; largeStr = s2 ; } int smallStrCodeTotal = 0 ; int largeStrCodeTotal = 0 ; int i = 0 ; for ( ; i < smallStr . size ( ) ; i ++ ) { smallStrCodeTotal += smallStr [ i ] ; largeStrCodeTotal += largeStr [ i ] ; } largeStrCodeTotal += largeStr [ i ] ; int intChar = largeStrCodeTotal - smallStrCodeTotal ; return ( char ) intChar ; } int main ( ) { string s1 = " abcd " ; string s2 = " cbdae " ; char extraChar = findExtraCharacter ( s1 , s2 ) ; cout << " Extra ▁ character : ▁ " << ( extraChar ) << endl ; return 0 ; }
Function to copy string ( Iterative and Recursive ) | Iterative CPP Program to copy one String to another . ; Function to copy one string to other assuming that other string has enough space . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void myCopy ( char s1 [ ] , char s2 [ ] ) { int i = 0 ; for ( i = 0 ; s1 [ i ] != ' \0' ; i ++ ) s2 [ i ] = s1 [ i ] ; s2 [ i ] = ' \0' ; } int main ( ) { char s1 [ 100 ] = " GEEKSFORGEEKS " ; char s2 [ 100 ] = " " ; myCopy ( s1 , s2 ) ; cout << s2 ; return 0 ; }
Evaluate an array expression with numbers , + and | C ++ program to find sum of given array of string type in integer form ; Function to find the sum of given array ; if string is empty ; stoi function to convert string into integer ; stoi function to convert string into integer ; Find operator ; If operator is equal to ' + ' , add value in sum variable else subtract ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateSum ( string arr [ ] , int n ) { if ( n == 0 ) return 0 ; string s = arr [ 0 ] ; int value = stoi ( s ) ; int sum = value ; for ( int i = 2 ; i < n ; i = i + 2 ) { s = arr [ i ] ; int value = stoi ( s ) ; char operation = arr [ i - 1 ] [ 0 ] ; if ( operation == ' + ' ) sum += value ; else sum -= value ; } return sum ; } int main ( ) { string arr [ ] = { "3" , " + " , "4" , " - " , "7" , " + " , "13" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << calculateSum ( arr , n ) ; return 0 ; }
Check if two strings have a common substring | CPP program to heck if two strings have common substring ; function to return true if strings have common substring and no if strings have no common substring ; vector for storing character occurrences ; increment vector index for every character of str1 ; checking common substring of str2 in str1 ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool twoStrings ( string s1 , string s2 ) { vector < bool > v ( MAX_CHAR , 0 ) ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) v [ s1 [ i ] - ' a ' ] = true ; for ( int i = 0 ; i < s2 . length ( ) ; i ++ ) if ( v [ s2 [ i ] - ' a ' ] ) return true ; return false ; } int main ( ) { string str1 = " hello " ; string str2 = " world " ; if ( twoStrings ( str1 , str2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
String with maximum number of unique characters | C ++ code to find the largest string ; Function to find string with maximum number of unique characters . ; Index of string with maximum unique characters ; iterate through all strings ; array indicating any alphabet included or not included ; count number of unique alphabets in each string ; keep track of maximum number of alphabets ; print result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void LargestString ( string * na ) { int N = sizeof ( na ) / sizeof ( na [ 0 ] ) ; int c [ N ] ; int m = 1 ; for ( int j = 0 ; j < N ; j ++ ) { bool character [ 26 ] ; for ( int k = 0 ; k < na [ j ] . size ( ) ; k ++ ) { int x = ( int ) ( na [ j ] [ k ] - ' A ' ) ; if ( na [ j ] [ k ] != ' ▁ ' && character [ x ] == false ) { c [ j ] ++ ; character [ x ] = true ; } } if ( c [ j ] > c [ m ] ) m = j ; } cout << na [ m ] << endl ; } int main ( ) { string na [ ] = { " BOB " , " A ▁ AB ▁ C ▁ JOHNSON " , " ANJALI " , " ASKRIT " , " ARMAN ▁ MALLIK " } ; LargestString ( na ) ; }
Program for length of the longest word in a sentence | C ++ program to find the number of charters in the longest word in the sentence . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestWordLength ( string str ) { int counter = 0 ; string words [ 100 ] ; for ( short i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ▁ ' ) counter ++ ; else words [ counter ] += str [ i ] ; } int length = 0 ; for ( string word : words ) { if ( length < word . length ( ) ) { length = word . length ( ) ; } } return length ; } int main ( ) { string str = " I ▁ am ▁ an ▁ intern ▁ at ▁ geeksforgeeks " ; cout << ( LongestWordLength ( str ) ) ; }
Morse Code Implementation | CPP program to demonstrate Morse code ; function to encode a alphabet as Morse code ; refer to the Morse table image attached in the article ; for space ; character by character print Morse code ; Driver 's code
#include <iostream> NEW_LINE using namespace std ; string morseEncode ( char x ) { switch ( x ) { case ' a ' : return " . - " ; case ' b ' : return " - . . . " ; case ' c ' : return " - . - . " ; case ' d ' : return " - . . " ; case ' e ' : return " . " ; case ' f ' : return " . . - . " ; case ' g ' : return " - - . " ; case ' h ' : return " . . . . " ; case ' i ' : return " . . " ; case ' j ' : return " . - - - " ; case ' k ' : return " - . - " ; case ' l ' : return " . - . . " ; case ' m ' : return " - - " ; case ' n ' : return " - . " ; case ' o ' : return " - - - " ; case ' p ' : return " . - - . " ; case ' q ' : return " - - . - " ; case ' r ' : return " . - . " ; case ' s ' : return " . . . " ; case ' t ' : return " - " ; case ' u ' : return " . . - " ; case ' v ' : return " . . . - " ; case ' w ' : return " . - - " ; case ' x ' : return " - . . - " ; case ' y ' : return " - . - - " ; case ' z ' : return " - - . . " ; case '1' : return " . - - - - " ; case '2' : return " . . - - - " ; case '3' : return " . . . - - " ; case '4' : return " . . . . - " ; case '5' : return " . . . . . " ; case '6' : return " - . . . . " ; case '7' : return " - - . . . " ; case '8' : return " - - - . . " ; case '9' : return " - - - - . " ; case '0' : return " - - - - - " ; default : cerr << " Found ▁ invalid ▁ character : ▁ " << x << ' ▁ ' << std :: endl ; exit ( 0 ) ; } } void morseCode ( string s ) { for ( int i = 0 ; s [ i ] ; i ++ ) cout << morseEncode ( s [ i ] ) ; cout << endl ; } int main ( ) { string s = " geeksforgeeks " ; morseCode ( s ) ; return 0 ; }
Polybius Square Cipher | CPP Program to implement polybius cipher ; function to display polybius cipher text ; convert each character to its encrypted code ; finding row of the table ; finding column of the table ; if character is ' k ' ; if character is greater than ' j ' ; Driver 's Code ; print the cipher of "geeksforgeeks
#include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void polybiusCipher ( string s ) { int row , col ; for ( int i = 0 ; s [ i ] ; i ++ ) { row = ceil ( ( s [ i ] - ' a ' ) / 5 ) + 1 ; col = ( ( s [ i ] - ' a ' ) % 5 ) + 1 ; if ( s [ i ] == ' k ' ) { row = row - 1 ; col = 5 - col + 1 ; } else if ( s [ i ] >= ' j ' ) { if ( col == 1 ) { col = 6 ; row = row - 1 ; } col = col - 1 ; } cout << row << col ; } cout << endl ; } int main ( ) { string s = " geeksforgeeks " ; polybiusCipher ( s ) ; return 0 ; }
Minimum removal to make palindrome permutation | CPP Program to find minimum number of removal to make any permutation of the string a palindrome ; function to find minimum removal of characters ; hash to store frequency of each character ; to set hash array to zeros ; count frequency of each character ; count the odd frequency characters ; if count is - 1 return 0 otherwise return count ; Driver 's Code
#include <iostream> NEW_LINE using namespace std ; #define MAX_CHAR 26 NEW_LINE int minRemoval ( string str ) { int hash [ MAX_CHAR ] ; memset ( hash , 0 , sizeof ( hash ) ) ; for ( int i = 0 ; str [ i ] ; i ++ ) hash [ str [ i ] - ' a ' ] ++ ; int count = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( hash [ i ] % 2 ) count ++ ; return ( count == 0 ) ? 0 : count - 1 ; } int main ( ) { string str = " geeksforgeeks " ; cout << minRemoval ( str ) << endl ; return 0 ; }
Union | CPP program to implement Union - Find with union by rank and path compression . ; Arr to represent parent of index i ; Size to represent the number of nodes in subgxrph rooted at index i ; set parent of every node to itself and size of node to one ; Each time we follow a path , find function compresses it further until the path length is greater than or equal to 1. ; while we reach a node whose parent is equal to itself ; Skip one level ; Move to the new level ; A function that does union of two nodes x and y where xr is root node of x and yr is root node of y ; Make yr parent of xr ; Make xr parent of yr ; The main function to check whether a given gxrph contains cycle or not ; Itexrte through all edges of gxrph , find nodes connecting them . If root nodes of both are same , then there is cycle in gxrph . ; find root of i ; find root of adj [ i ] [ j ] ; If same parent ; Make them connect ; Driver progxrm to test above functions ; Initialize the values for arxry Arr and Size ; Adjacency list for gxrph ; call is_cycle to check if it contains cycle
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_VERTEX = 101 ; int Arr [ MAX_VERTEX ] ; int size [ MAX_VERTEX ] ; void initialize ( int n ) { for ( int i = 0 ; i <= n ; i ++ ) { Arr [ i ] = i ; size [ i ] = 1 ; } } int find ( int i ) { while ( Arr [ i ] != i ) { Arr [ i ] = Arr [ Arr [ i ] ] ; i = Arr [ i ] ; } return i ; } void _union ( int xr , int yr ) { if ( size [ xr ] < size [ yr ] ) { Arr [ xr ] = Arr [ yr ] ; size [ yr ] += size [ xr ] ; } else { Arr [ yr ] = Arr [ xr ] ; size [ xr ] += size [ yr ] ; } } int isCycle ( vector < int > adj [ ] , int V ) { for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < adj [ i ] . size ( ) ; j ++ ) { int x = find ( i ) ; int y = find ( adj [ i ] [ j ] ) ; if ( x == y ) return 1 ; _union ( x , y ) ; } } return 0 ; } int main ( ) { int V = 3 ; initialize ( V ) ; vector < int > adj [ V ] ; adj [ 0 ] . push_back ( 1 ) ; adj [ 0 ] . push_back ( 2 ) ; adj [ 1 ] . push_back ( 2 ) ; if ( isCycle ( adj , V ) ) cout << " Gxrph ▁ contains ▁ Cycle . STRNEWLINE " ; else cout << " Gxrph ▁ does ▁ not ▁ contain ▁ Cycle . STRNEWLINE " ; return 0 ; }
Queries for frequencies of characters in substrings | CPP program to find occurrence of character in substring l to r ; To store count of all character ; To pre - process string from 0 to size of string ; Store occurrence of character i ; Store occurrence o all character upto i ; To return occurrence of character in range l to r ; Return occurrence of character from 0 to r minus its occurrence from 0 to l ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE #define MAX_LEN 1005 NEW_LINE #define MAX_CHAR 26 NEW_LINE using namespace std ; int cnt [ MAX_LEN ] [ MAX_CHAR ] ; void preProcess ( string s ) { int n = s . length ( ) ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int i = 0 ; i < n ; i ++ ) cnt [ i ] [ s [ i ] - ' a ' ] ++ ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) cnt [ i ] [ j ] += cnt [ i - 1 ] [ j ] ; } } int findCharFreq ( int l , int r , char c ) { int count = cnt [ r ] [ c - ' a ' ] ; if ( l != 0 ) count -= cnt [ l - 1 ] [ c - ' a ' ] ; return count ; } int main ( ) { string s = " geeksforgeeks " ; int Q = 4 ; preProcess ( s ) ; cout << findCharFreq ( 0 , 5 , ' e ' ) << endl ; cout << findCharFreq ( 2 , 6 , ' f ' ) << endl ; cout << findCharFreq ( 4 , 7 , ' m ' ) << endl ; cout << findCharFreq ( 0 , 12 , ' e ' ) << endl ; return 0 ; }
Longest Uncommon Subsequence | CPP Program to find longest uncommon subsequence . ; function to calculate length of longest uncommon subsequence ; Case 1 : If strings are equal ; for case 2 and case 3 ; Driver code ; input strings
#include <iostream> NEW_LINE using namespace std ; int findLUSlength ( string a , string b ) { if ( ! a . compare ( b ) ) return 0 ; return max ( a . length ( ) , b . length ( ) ) ; } int main ( ) { string a = " abcdabcd " , b = " abcabc " ; cout << findLUSlength ( a , b ) ; return 0 ; }
Interchanging first and second halves of strings | CPP code to create two new strings by swapping first and second halves ; Function to concatenate two different halves of given strings ; Creating new strings by exchanging the first half of a and b . Please refer below for details of substr . https : www . geeksforgeeks . org / stdsubstr - in - ccpp / ; Driver function ; Calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swapTwoHalves ( string a , string b ) { int la = a . length ( ) ; int lb = b . length ( ) ; string c = a . substr ( 0 , la / 2 ) + b . substr ( lb / 2 , lb ) ; string d = b . substr ( 0 , lb / 2 ) + a . substr ( la / 2 , la ) ; cout << c << endl << d << endl ; } int main ( ) { string a = " remuneration " ; string b = " day " ; swapTwoHalves ( a , b ) ; return 0 ; }
Merge two strings in chunks of given size | C ++ program to merge n number of strings ; Function performing the calculations ; Length of string a ; Length f string b ; Pointers for string a and string b ; pa and pb denote the number of characters of both a and b extracted ; If entire substring of length k can be extracted ; Please refer below link for details of library function https : www . geeksforgeeks . org / stdsubstr - in - ccpp / ; If the remaining string is of length less than k ; If the string has been traversed ; If entire substring of length k can be extracted ; If the remaining string is of length less than k ; If the string has been traversed ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string a , string b , int k ) { string s = " " ; int la = a . length ( ) ; int lb = b . length ( ) ; int l = la + lb ; int indexa = 0 , indexb = 0 ; while ( l > 0 ) { int pa = 0 , pb = 0 ; if ( la - indexa >= k ) { s = s + a . substr ( indexa , k ) ; indexa = indexa + k ; pa = k ; } else if ( la - indexa < k && la - indexa > 0 ) { s = s + a . substr ( indexa , la - indexa ) ; pa = la - indexa ; indexa = la ; } else if ( indexa >= la ) pa = 0 ; if ( lb - indexb >= k ) { s = s + b . substr ( indexb , k ) ; pb = k ; indexb = indexb + k ; } else if ( lb - indexb < k && lb - indexb > 0 ) { s = s + b . substr ( indexb , lb - indexb ) ; pb = lb - indexb ; indexb = lb ; } else if ( indexb >= lb ) pb = 0 ; l = l - pa - pb ; } cout << s ; } int main ( ) { string a = " determination " , b = " stance " ; int k = 3 ; solve ( a , b , k ) ; return 0 ; }
Longest sub | C ++ implementation to find the length of the longest substring having frequency of each character less than equal to k ; function to find the length of the longest substring having frequency of each character less than equal to k ; hash table to store frequency of each table ; ' start ' index of the current substring ; to store the maximum length ; traverse the string ' str ' ; get the current character as ' ch ' ; increase frequency of ' ch ' in ' freq [ ] ' ; if frequency of ' ch ' becomes more than ' k ' ; update ' maxLen ' ; decrease frequency of each character as they are encountered from the ' start ' index until frequency of ' ch ' is greater than ' k ' ; decrement frequency by '1' ; increment ' start ' ; update maxLen ; required length ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 26 NEW_LINE int longSubstring ( string str , int k ) { int freq [ SIZE ] ; memset ( freq , 0 , sizeof ( freq ) ) ; int start = 0 ; int maxLen = 0 ; char ch ; int n = str . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { ch = str [ i ] ; freq [ ch - ' a ' ] ++ ; if ( freq [ ch - ' a ' ] > k ) { if ( maxLen < ( i - start ) ) maxLen = i - start ; while ( freq [ ch - ' a ' ] > k ) { freq [ str [ start ] - ' a ' ] -- ; start ++ ; } } } if ( maxLen < ( n - start ) ) maxLen = n - start ; return maxLen ; } int main ( ) { string str = " babcaag " ; int k = 1 ; cout << " Length ▁ = ▁ " << longSubstring ( str , k ) ; return 0 ; }
Magical Indices in an array | C ++ program to find number of magical indices in the given array . ; Function to count number of magical indices . ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define mp make_pair NEW_LINE #define pb push_back NEW_LINE #define mod 1000000007 NEW_LINE int solve ( int A [ ] , int n ) { int i , cnt = 0 , j ; int parent [ n + 1 ] ; int vis [ n + 1 ] ; memset ( parent , -1 , sizeof ( parent ) ) ; memset ( vis , 0 , sizeof ( vis ) ) ; for ( i = 0 ; i < n ; i ++ ) { j = i ; if ( parent [ j ] == -1 ) { while ( parent [ j ] == -1 ) { parent [ j ] = i ; j = ( j + A [ j ] + 1 ) % n ; } if ( parent [ j ] == i ) { while ( ! vis [ j ] ) { vis [ j ] = 1 ; cnt ++ ; j = ( j + A [ j ] + 1 ) % n ; } } } } return cnt ; } int main ( ) { int A [ ] = { 0 , 0 , 0 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << solve ( A , n ) ; return 0 ; }
Longest path between any pair of vertices | C ++ program to find the longest cable length between any two cities . ; visited [ ] array to make nodes visited src is starting node for DFS traversal prev_len is sum of cable length till current node max_len is pointer which stores the maximum length of cable value after DFS traversal ; Mark the src node visited ; curr_len is for length of cable from src city to its adjacent city ; Adjacent is pair type which stores destination city and cable length ; Traverse all adjacent ; Adjacent element ; If node or city is not visited ; Total length of cable from src city to its adjacent ; Call DFS for adjacent city ; If total cable length till now greater than previous length then update it ; make curr_len = 0 for next adjacent ; n is number of cities or nodes in graph cable_lines is total cable_lines among the cities or edges in graph ; maximum length of cable among the connected cities ; call DFS for each city to find maximum length of cable ; initialize visited array with 0 ; Call DFS for src vertex i ; driver program to test the input ; n is number of cities ; create undirected graph first edge ; second edge ; third edge ; fourth edge ; fifth edge
#include <bits/stdc++.h> NEW_LINE using namespace std ; void DFS ( vector < pair < int , int > > graph [ ] , int src , int prev_len , int * max_len , vector < bool > & visited ) { visited [ src ] = 1 ; int curr_len = 0 ; pair < int , int > adjacent ; for ( int i = 0 ; i < graph [ src ] . size ( ) ; i ++ ) { adjacent = graph [ src ] [ i ] ; if ( ! visited [ adjacent . first ] ) { curr_len = prev_len + adjacent . second ; DFS ( graph , adjacent . first , curr_len , max_len , visited ) ; } if ( ( * max_len ) < curr_len ) * max_len = curr_len ; curr_len = 0 ; } } int longestCable ( vector < pair < int , int > > graph [ ] , int n ) { int max_len = INT_MIN ; for ( int i = 1 ; i <= n ; i ++ ) { vector < bool > visited ( n + 1 , false ) ; DFS ( graph , i , 0 , & max_len , visited ) ; } return max_len ; } int main ( ) { int n = 6 ; vector < pair < int , int > > graph [ n + 1 ] ; graph [ 1 ] . push_back ( make_pair ( 2 , 3 ) ) ; graph [ 2 ] . push_back ( make_pair ( 1 , 3 ) ) ; graph [ 2 ] . push_back ( make_pair ( 3 , 4 ) ) ; graph [ 3 ] . push_back ( make_pair ( 2 , 4 ) ) ; graph [ 2 ] . push_back ( make_pair ( 6 , 2 ) ) ; graph [ 6 ] . push_back ( make_pair ( 2 , 2 ) ) ; graph [ 4 ] . push_back ( make_pair ( 6 , 6 ) ) ; graph [ 6 ] . push_back ( make_pair ( 4 , 6 ) ) ; graph [ 5 ] . push_back ( make_pair ( 6 , 5 ) ) ; graph [ 6 ] . push_back ( make_pair ( 5 , 5 ) ) ; cout << " Maximum ▁ length ▁ of ▁ cable ▁ = ▁ " << longestCable ( graph , n ) ; return 0 ; }
Level order traversal with direction change after every two levels | CPP program to print Zig - Zag traversal in groups of size 2. ; A Binary Tree Node ; Function to print the level order of given binary tree . Direction of printing level order traversal of binary tree changes after every two levels ; For null root ; Maintain a queue for normal level order traversal ; Maintain a stack for printing nodes in reverse order after they are popped out from queue . ; sz is used for storing the count of nodes in a level ; Used for changing the direction of level order traversal ; Used for changing the direction of level order traversal ; Push root node to the queue ; Run this while loop till queue got empty ; Do a normal level order traversal ; For printing nodes from left to right , simply print the nodes in the order in which they are being popped out from the queue . ; For printing nodes from right to left , push the nodes to stack instead of printing them . ; for printing the nodes in order from right to left ; Change the direction of printing nodes after every two levels . ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree
#include <iostream> NEW_LINE #include <queue> NEW_LINE #include <stack> NEW_LINE using namespace std ; struct Node { struct Node * left ; int data ; struct Node * right ; } ; void modifiedLevelOrder ( struct Node * node ) { if ( node == NULL ) return ; if ( node -> left == NULL && node -> right == NULL ) { cout << node -> data ; return ; } queue < Node * > myQueue ; stack < Node * > myStack ; struct Node * temp = NULL ; int sz ; int ct = 0 ; bool rightToLeft = false ; myQueue . push ( node ) ; while ( ! myQueue . empty ( ) ) { ct ++ ; sz = myQueue . size ( ) ; for ( int i = 0 ; i < sz ; i ++ ) { temp = myQueue . front ( ) ; myQueue . pop ( ) ; if ( rightToLeft == false ) cout << temp -> data << " ▁ " ; else myStack . push ( temp ) ; if ( temp -> left ) myQueue . push ( temp -> left ) ; if ( temp -> right ) myQueue . push ( temp -> right ) ; } if ( rightToLeft == true ) { while ( ! myStack . empty ( ) ) { temp = myStack . top ( ) ; myStack . pop ( ) ; cout << temp -> data << " ▁ " ; } } if ( ct == 2 ) { rightToLeft = ! rightToLeft ; ct = 0 ; } cout << " STRNEWLINE " ; } } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } 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 -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 3 ) ; root -> left -> right -> right = newNode ( 1 ) ; root -> right -> left -> left = newNode ( 4 ) ; root -> right -> left -> right = newNode ( 2 ) ; root -> right -> right -> left = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 2 ) ; root -> left -> right -> left -> left = newNode ( 16 ) ; root -> left -> right -> left -> right = newNode ( 17 ) ; root -> right -> left -> right -> left = newNode ( 18 ) ; root -> right -> right -> left -> right = newNode ( 19 ) ; modifiedLevelOrder ( root ) ; return 0 ; }
Minimum cost to connect all cities | C ++ code to find out minimum cost path to connect all the cities ; Function to find out minimum valued node among the nodes which are not yet included in MST ; Loop through all the values of the nodes which are not yet included in MST and find the minimum valued one . ; Function to find out the MST and the cost of the MST . ; Array to store the parent node of a particular node . ; Array to store key value of each node . ; Boolean Array to hold bool values whether a node is included in MST or not . ; Set all the key values to infinite and none of the nodes is included in MST . ; Start to find the MST from node 0. Parent of node 0 is none so set - 1. key value or minimum cost to reach 0 th node from 0 th node is 0. ; Find the rest n - 1 nodes of MST . ; First find out the minimum node among the nodes which are not yet included in MST . ; Now the uth node is included in MST . ; Update the values of neighbor nodes of u which are not yet included in MST . ; Find out the cost by adding the edge values of MST . ; Utility Program : ; Input 1 ; Input 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minnode ( int n , int keyval [ ] , bool mstset [ ] ) { int mini = numeric_limits < int > :: max ( ) ; int mini_index ; for ( int i = 0 ; i < n ; i ++ ) { if ( mstset [ i ] == false && keyval [ i ] < mini ) { mini = keyval [ i ] , mini_index = i ; } } return mini_index ; } void findcost ( int n , vector < vector < int > > city ) { int parent [ n ] ; int keyval [ n ] ; bool mstset [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { keyval [ i ] = numeric_limits < int > :: max ( ) ; mstset [ i ] = false ; } parent [ 0 ] = -1 ; keyval [ 0 ] = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int u = minnode ( n , keyval , mstset ) ; mstset [ u ] = true ; for ( int v = 0 ; v < n ; v ++ ) { if ( city [ u ] [ v ] && mstset [ v ] == false && city [ u ] [ v ] < keyval [ v ] ) { keyval [ v ] = city [ u ] [ v ] ; parent [ v ] = u ; } } } int cost = 0 ; for ( int i = 1 ; i < n ; i ++ ) cost += city [ parent [ i ] ] [ i ] ; cout << cost << endl ; } int main ( ) { int n1 = 5 ; vector < vector < int > > city1 = { { 0 , 1 , 2 , 3 , 4 } , { 1 , 0 , 5 , 0 , 7 } , { 2 , 5 , 0 , 6 , 0 } , { 3 , 0 , 6 , 0 , 0 } , { 4 , 7 , 0 , 0 , 0 } } ; findcost ( n1 , city1 ) ; int n2 = 6 ; vector < vector < int > > city2 = { { 0 , 1 , 1 , 100 , 0 , 0 } , { 1 , 0 , 1 , 0 , 0 , 0 } , { 1 , 1 , 0 , 0 , 0 , 0 } , { 100 , 0 , 0 , 0 , 2 , 2 } , { 0 , 0 , 0 , 2 , 0 , 2 } , { 0 , 0 , 0 , 2 , 2 , 0 } } ; findcost ( n2 , city2 ) ; return 0 ; }
Minimum Product Spanning Tree | A C ++ program for getting minimum product spanning tree The program is for adjacency matrix representation of the graph ; Number of vertices in the graph ; A utility function to find the vertex with minimum key value , from the set of vertices not yet included in MST ; Initialize min value ; A utility function to print the constructed MST stored in parent [ ] and print Minimum Obtaiable product ; Function to construct and print MST for a graph represented using adjacency matrix representation inputGraph is sent for printing actual edges and logGraph is sent for actual MST operations ; Array to store constructed MST ; Key values used to pick minimum ; weight edge in cut To represent set of vertices not ; yet included in MST Initialize all keys as INFINITE ; Always include first 1 st vertex in MST . Make key 0 so that this vertex is ; picked as first vertex First node is always root of MST ; The MST will have V vertices ; Pick the minimum key vertex from the set of vertices not yet included in MST ; Add the picked vertex to the MST Set ; Update key value and parent index of the adjacent vertices of the picked vertex . Consider only those vertices which are not yet included in MST ; logGraph [ u ] [ v ] is non zero only for adjacent vertices of m mstSet [ v ] is false for vertices not yet included in MST Update the key only if logGraph [ u ] [ v ] is smaller than key [ v ] ; print the constructed MST ; Method to get minimum product spanning tree ; Constructing logGraph from original graph ; Applyting standard Prim 's MST algorithm on Log graph. ; driver program to test above function ; Let us create the following graph 2 3 ( 0 ) -- ( 1 ) -- ( 2 ) | / \ | 6 | 8 / \ 5 | 7 | / \ | ( 3 ) -- -- -- - ( 4 ) 9 ; Print the solution
#include <bits/stdc++.h> NEW_LINE #define V 5 NEW_LINE int minKey ( int key [ ] , bool mstSet [ ] ) { int min = INT_MAX , min_index ; for ( int v = 0 ; v < V ; v ++ ) if ( mstSet [ v ] == false && key [ v ] < min ) min = key [ v ] , min_index = v ; return min_index ; } int printMST ( int parent [ ] , int n , int graph [ V ] [ V ] ) { printf ( " Edge ▁ Weight STRNEWLINE " ) ; int minProduct = 1 ; for ( int i = 1 ; i < V ; i ++ ) { printf ( " % d ▁ - ▁ % d ▁ % d ▁ STRNEWLINE " , parent [ i ] , i , graph [ i ] [ parent [ i ] ] ) ; minProduct *= graph [ i ] [ parent [ i ] ] ; } printf ( " Minimum ▁ Obtainable ▁ product ▁ is ▁ % d STRNEWLINE " , minProduct ) ; } void primMST ( int inputGraph [ V ] [ V ] , double logGraph [ V ] [ V ] ) { int parent [ V ] ; int key [ V ] ; bool mstSet [ V ] ; for ( int i = 0 ; i < V ; i ++ ) key [ i ] = INT_MAX , mstSet [ i ] = false ; key [ 0 ] = 0 ; parent [ 0 ] = -1 ; for ( int count = 0 ; count < V - 1 ; count ++ ) { int u = minKey ( key , mstSet ) ; mstSet [ u ] = true ; for ( int v = 0 ; v < V ; v ++ ) if ( logGraph [ u ] [ v ] > 0 && mstSet [ v ] == false && logGraph [ u ] [ v ] < key [ v ] ) parent [ v ] = u , key [ v ] = logGraph [ u ] [ v ] ; } printMST ( parent , V , inputGraph ) ; } void minimumProductMST ( int graph [ V ] [ V ] ) { double logGraph [ V ] [ V ] ; for ( int i = 0 ; i < V ; i ++ ) { for ( int j = 0 ; j < V ; j ++ ) { if ( graph [ i ] [ j ] > 0 ) logGraph [ i ] [ j ] = log ( graph [ i ] [ j ] ) ; else logGraph [ i ] [ j ] = 0 ; } } primMST ( graph , logGraph ) ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 2 , 0 , 6 , 0 } , { 2 , 0 , 3 , 8 , 5 } , { 0 , 3 , 0 , 0 , 7 } , { 6 , 8 , 0 , 0 , 9 } , { 0 , 5 , 7 , 9 , 0 } , } ; minimumProductMST ( graph ) ; return 0 ; }
Level order traversal with direction change after every two levels | CPP program to print Zig - Zag traversal in groups of size 2. ; A Binary Tree Node ; Utility function to create a new tree node ; Function to print the level order of given binary tree . Direction of printing level order traversal of binary tree changes after every two levels ; Run this while loop till queue got empty ; For printing nodes from right to left , push the nodes to stack instead of printing them . ; for printing the nodes in order from right to left ; Change the direction of traversal . ; Driver program to test above functions ; Let us create binary tree
#include <iostream> NEW_LINE #include <stack> NEW_LINE #include <queue> NEW_LINE using namespace std ; #define LEFT 0 NEW_LINE #define RIGHT 1 NEW_LINE #define ChangeDirection ( Dir ) ((Dir) = 1 - (Dir)) NEW_LINE 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 modifiedLevelOrder ( struct node * root ) { if ( ! root ) return ; int dir = LEFT ; struct node * temp ; queue < struct node * > Q ; stack < struct node * > S ; S . push ( root ) ; while ( ! Q . empty ( ) || ! S . empty ( ) ) { while ( ! S . empty ( ) ) { temp = S . top ( ) ; S . pop ( ) ; cout << temp -> data << " ▁ " ; if ( dir == LEFT ) { if ( temp -> left ) Q . push ( temp -> left ) ; if ( temp -> right ) Q . push ( temp -> right ) ; } else { if ( temp -> right ) Q . push ( temp -> right ) ; if ( temp -> left ) Q . push ( temp -> left ) ; } } cout << endl ; while ( ! Q . empty ( ) ) { temp = Q . front ( ) ; Q . pop ( ) ; cout << temp -> data << " ▁ " ; if ( dir == LEFT ) { if ( temp -> left ) S . push ( temp -> left ) ; if ( temp -> right ) S . push ( temp -> right ) ; } else { if ( temp -> right ) S . push ( temp -> right ) ; if ( temp -> left ) S . push ( temp -> left ) ; } } cout << endl ; ChangeDirection ( dir ) ; } } 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 -> left -> left -> left = newNode ( 8 ) ; root -> left -> left -> right = newNode ( 9 ) ; root -> left -> right -> left = newNode ( 3 ) ; root -> left -> right -> right = newNode ( 1 ) ; root -> right -> left -> left = newNode ( 4 ) ; root -> right -> left -> right = newNode ( 2 ) ; root -> right -> right -> left = newNode ( 7 ) ; root -> right -> right -> right = newNode ( 2 ) ; root -> left -> right -> left -> left = newNode ( 16 ) ; root -> left -> right -> left -> right = newNode ( 17 ) ; root -> right -> left -> right -> left = newNode ( 18 ) ; root -> right -> right -> left -> right = newNode ( 19 ) ; modifiedLevelOrder ( root ) ; return 0 ; }
Insertion in a Binary Tree in level order | C ++ program to insert element in Binary Tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to create a new node ; Inorder traversal of a binary tree ; Function to insert element in binary tree ; do level order traversal until we find an empty place , i . e . either left child or right child of some node is pointing to NULL . ; Driver code
#include <iostream> NEW_LINE #include <queue> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; } ; Node * CreateNode ( int data ) { Node * newNode = new Node ( ) ; if ( ! newNode ) { cout << " Memory ▁ error STRNEWLINE " ; return NULL ; } newNode -> data = data ; newNode -> left = newNode -> right = NULL ; return newNode ; } void inorder ( Node * temp ) { if ( temp == NULL ) return ; inorder ( temp -> left ) ; cout << temp -> data << ' ▁ ' ; inorder ( temp -> right ) ; } Node * InsertNode ( Node * root , int data ) { if ( root == NULL ) { root = CreateNode ( data ) ; return root ; } queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; else { temp -> left = CreateNode ( data ) ; return root ; } if ( temp -> right != NULL ) q . push ( temp -> right ) ; else { temp -> right = CreateNode ( data ) ; return root ; } } } int main ( ) { Node * root = CreateNode ( 10 ) ; root -> left = CreateNode ( 11 ) ; root -> left -> left = CreateNode ( 7 ) ; root -> right = CreateNode ( 9 ) ; root -> right -> left = CreateNode ( 15 ) ; root -> right -> right = CreateNode ( 8 ) ; cout << " Inorder ▁ traversal ▁ before ▁ insertion : ▁ " ; inorder ( root ) ; cout << endl ; int key = 12 ; root = InsertNode ( root , key ) ; cout << " Inorder ▁ traversal ▁ after ▁ insertion : ▁ " ; inorder ( root ) ; cout << endl ; return 0 ; }
Tug of War | ; function that tries every possible solution by calling itself recursively ; checks whether the it is going out of bound ; checks that the numbers of elements left are not less than the number of elements required to form the solution ; consider the cases when current element is not included in the solution ; add the current element to the solution ; checks if a solution is formed ; checks if the solution formed is better than the best solution so far ; consider the cases where current element is included in the solution ; removes current element before returning to the caller of this function ; main function that generate an arr ; the boolean array that contains the inclusion and exclusion of an element in current set . The number excluded automatically form the other set ; The inclusion / exclusion array for final solution ; Find the solution using recursive function TOWUtil ( ) ; Print the solution ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void TOWUtil ( int * arr , int n , bool * curr_elements , int no_of_selected_elements , bool * soln , int * min_diff , int sum , int curr_sum , int curr_position ) { if ( curr_position == n ) return ; if ( ( n / 2 - no_of_selected_elements ) > ( n - curr_position ) ) return ; TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , min_diff , sum , curr_sum , curr_position + 1 ) ; no_of_selected_elements ++ ; curr_sum = curr_sum + arr [ curr_position ] ; curr_elements [ curr_position ] = true ; if ( no_of_selected_elements == n / 2 ) { if ( abs ( sum / 2 - curr_sum ) < * min_diff ) { * min_diff = abs ( sum / 2 - curr_sum ) ; for ( int i = 0 ; i < n ; i ++ ) soln [ i ] = curr_elements [ i ] ; } } else { TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , min_diff , sum , curr_sum , curr_position + 1 ) ; } curr_elements [ curr_position ] = false ; } void tugOfWar ( int * arr , int n ) { bool * curr_elements = new bool [ n ] ; bool * soln = new bool [ n ] ; int min_diff = INT_MAX ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; curr_elements [ i ] = soln [ i ] = false ; } TOWUtil ( arr , n , curr_elements , 0 , soln , & min_diff , sum , 0 , 0 ) ; cout << " The ▁ first ▁ subset ▁ is : ▁ " ; for ( int i = 0 ; i < n ; i ++ ) { if ( soln [ i ] == true ) cout << arr [ i ] << " ▁ " ; } cout << " The second subset is : " for ( int i = 0 ; i < n ; i ++ ) { if ( soln [ i ] == false ) cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 23 , 45 , -34 , 12 , 0 , 98 , -99 , 4 , 189 , -1 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; tugOfWar ( arr , n ) ; return 0 ; }
The Knight 's tour problem | Backtracking | C ++ program for Knight Tour problem ; A utility function to check if i , j are valid indexes for N * N chessboard ; A utility function to print solution matrix sol [ N ] [ N ] ; This function solves the Knight Tour problem using Backtracking . This function mainly uses solveKTUtil ( ) to solve the problem . It returns false if no complete tour is possible , otherwise return true and prints the tour . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; Initialization of solution matrix ; xMove [ ] and yMove [ ] define next move of Knight . xMove [ ] is for next value of x coordinate yMove [ ] is for next value of y coordinate ; Since the Knight is initially at the first block ; Start from 0 , 0 and explore all tours using solveKTUtil ( ) ; A recursive utility function to solve Knight Tour problem ; Try all next moves from the current coordinate x , y ; backtracking ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 8 NEW_LINE int solveKTUtil ( int x , int y , int movei , int sol [ N ] [ N ] , int xMove [ ] , int yMove [ ] ) ; int isSafe ( int x , int y , int sol [ N ] [ N ] ) { return ( x >= 0 && x < N && y >= 0 && y < N && sol [ x ] [ y ] == -1 ) ; } void printSolution ( int sol [ N ] [ N ] ) { for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < N ; y ++ ) cout << " ▁ " << setw ( 2 ) << sol [ x ] [ y ] << " ▁ " ; cout << endl ; } } int solveKT ( ) { int sol [ N ] [ N ] ; for ( int x = 0 ; x < N ; x ++ ) for ( int y = 0 ; y < N ; y ++ ) sol [ x ] [ y ] = -1 ; int xMove [ 8 ] = { 2 , 1 , -1 , -2 , -2 , -1 , 1 , 2 } ; int yMove [ 8 ] = { 1 , 2 , 2 , 1 , -1 , -2 , -2 , -1 } ; sol [ 0 ] [ 0 ] = 0 ; if ( solveKTUtil ( 0 , 0 , 1 , sol , xMove , yMove ) == 0 ) { cout << " Solution ▁ does ▁ not ▁ exist " ; return 0 ; } else printSolution ( sol ) ; return 1 ; } int solveKTUtil ( int x , int y , int movei , int sol [ N ] [ N ] , int xMove [ N ] , int yMove [ N ] ) { int k , next_x , next_y ; if ( movei == N * N ) return 1 ; for ( k = 0 ; k < 8 ; k ++ ) { next_x = x + xMove [ k ] ; next_y = y + yMove [ k ] ; if ( isSafe ( next_x , next_y , sol ) ) { sol [ next_x ] [ next_y ] = movei ; if ( solveKTUtil ( next_x , next_y , movei + 1 , sol , xMove , yMove ) == 1 ) return 1 ; else sol [ next_x ] [ next_y ] = -1 ; } } return 0 ; } int main ( ) { solveKT ( ) ; return 0 ; }
Rat in a Maze | Backtracking | C ++ program to solve Rat in a Maze problem using backtracking ; Maze size ; A utility function to print solution matrix sol [ N ] [ N ] ; A utility function to check if x , y is valid index for N * N maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return true ; Check if maze [ x ] [ y ] is valid ; Check if the current block is already part of solution path . ; mark x , y as part of solution path ; Move forward in x direction ; If moving in x direction doesn 't give solution then Move down in y direction ; If moving in y direction doesn 't give solution then Move back in x direction ; If moving backwards in x direction doesn 't give solution then Move upwards in y direction ; If none of the above movements work then BACKTRACK : unmark x , y as part of solution path ; driver program to test above function
#include <stdio.h> NEW_LINE #define N 4 NEW_LINE bool solveMazeUtil ( int maze [ N ] [ N ] , int x , int y , int sol [ N ] [ N ] ) ; void printSolution ( int sol [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) printf ( " ▁ % d ▁ " , sol [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } bool isSafe ( int maze [ N ] [ N ] , int x , int y ) { if ( x >= 0 && x < N && y >= 0 && y < N && maze [ x ] [ y ] == 1 ) return true ; return false ; } bool solveMaze ( int maze [ N ] [ N ] ) { int sol [ N ] [ N ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( solveMazeUtil ( maze , 0 , 0 , sol ) == false ) { printf ( " Solution ▁ doesn ' t ▁ exist " ) ; return false ; } printSolution ( sol ) ; return true ; } bool solveMazeUtil ( int maze [ N ] [ N ] , int x , int y , int sol [ N ] [ N ] ) { if ( x == N - 1 && y == N - 1 && maze [ x ] [ y ] == 1 ) { sol [ x ] [ y ] = 1 ; return true ; } if ( isSafe ( maze , x , y ) == true ) { if ( sol [ x ] [ y ] == 1 ) return false ; sol [ x ] [ y ] = 1 ; if ( solveMazeUtil ( maze , x + 1 , y , sol ) == true ) return true ; if ( solveMazeUtil ( maze , x , y + 1 , sol ) == true ) return true ; if ( solveMazeUtil ( maze , x - 1 , y , sol ) == true ) return true ; if ( solveMazeUtil ( maze , x , y - 1 , sol ) == true ) return true ; sol [ x ] [ y ] = 0 ; return false ; } return false ; } int main ( ) { int maze [ N ] [ N ] = { { 1 , 0 , 0 , 0 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 0 , 0 } , { 1 , 1 , 1 , 1 } } ; solveMaze ( maze ) ; return 0 ; }
m Coloring Problem | Backtracking | ; Number of vertices in the graph ; A utility function to print solution ; check if the colored graph is safe or not ; check for every edge ; This function solves the m Coloring problem using recursion . It returns false if the m colours cannot be assigned , otherwise , return true and prints assignments of colours to all vertices . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; if current index reached end ; if coloring is safe ; Print the solution ; Assign each color from 1 to m ; Recur of the rest vertices ; Driver code ; Create following graph and test whether it is 3 colorable ( 3 ) -- - ( 2 ) | / | | / | | / | ( 0 ) -- - ( 1 ) ; Number of colors ; Initialize all color values as 0. This initialization is needed correct functioning of isSafe ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 4 NEW_LINE void printSolution ( int color [ ] ) ; void printSolution ( int color [ ] ) { cout << " Solution ▁ Exists : " " ▁ Following ▁ are ▁ the ▁ assigned ▁ colors ▁ STRNEWLINE " ; for ( int i = 0 ; i < V ; i ++ ) cout << " ▁ " << color [ i ] ; cout << " STRNEWLINE " ; } bool isSafe ( bool graph [ V ] [ V ] , int color [ ] ) { for ( int i = 0 ; i < V ; i ++ ) for ( int j = i + 1 ; j < V ; j ++ ) if ( graph [ i ] [ j ] && color [ j ] == color [ i ] ) return false ; return true ; } bool graphColoring ( bool graph [ V ] [ V ] , int m , int i , int color [ V ] ) { if ( i == V ) { if ( isSafe ( graph , color ) ) { printSolution ( color ) ; return true ; } return false ; } for ( int j = 1 ; j <= m ; j ++ ) { color [ i ] = j ; if ( graphColoring ( graph , m , i + 1 , color ) ) return true ; color [ i ] = 0 ; } return false ; } int main ( ) { bool graph [ V ] [ V ] = { { 0 , 1 , 1 , 1 } , { 1 , 0 , 1 , 0 } , { 1 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } , } ; int m = 3 ; int color [ V ] ; for ( int i = 0 ; i < V ; i ++ ) color [ i ] = 0 ; if ( ! graphColoring ( graph , m , 0 , color ) ) cout << " Solution ▁ does ▁ not ▁ exist " ; return 0 ; }
m Coloring Problem | Backtracking | CPP program for the above approach ; A node class which stores the color and the edges connected to the node ; Create a visited array of n nodes , initialized to zero ; maxColors used till now are 1 as all nodes are painted color 1 ; Do a full BFS traversal from all unvisited starting points ; If the starting point is unvisited , mark it visited and push it in queue ; BFS Travel starts here ; Checking all adjacent nodes to " top " edge in our queue ; IMPORTANT : If the color of the adjacent node is same , increase it by 1 ; If number of colors used shoots m , return 0 ; If the adjacent node is not visited , mark it visited and push it in queue ; Driver code ; Number of colors ; Create a vector of n + 1 nodes of type " node " The zeroth position is just dummy ( 1 to n to be used ) ; Add edges to each node as per given input ; Connect the undirected graph ; Display final answer
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; class node { public : int color = 1 ; set < int > edges ; } ; int canPaint ( vector < node > & nodes , int n , int m ) { vector < int > visited ( n + 1 , 0 ) ; int maxColors = 1 ; for ( int sv = 1 ; sv <= n ; sv ++ ) { if ( visited [ sv ] ) continue ; visited [ sv ] = 1 ; queue < int > q ; q . push ( sv ) ; while ( ! q . empty ( ) ) { int top = q . front ( ) ; q . pop ( ) ; for ( auto it = nodes [ top ] . edges . begin ( ) ; it != nodes [ top ] . edges . end ( ) ; it ++ ) { if ( nodes [ top ] . color == nodes [ * it ] . color ) nodes [ * it ] . color += 1 ; maxColors = max ( maxColors , max ( nodes [ top ] . color , nodes [ * it ] . color ) ) ; if ( maxColors > m ) return 0 ; if ( ! visited [ * it ] ) { visited [ * it ] = 1 ; q . push ( * it ) ; } } } } return 1 ; } int main ( ) { int n = 4 ; bool graph [ n ] [ n ] = { { 0 , 1 , 1 , 1 } , { 1 , 0 , 1 , 0 } , { 1 , 1 , 0 , 1 } , { 1 , 0 , 1 , 0 } } ; int m = 3 ; vector < node > nodes ( n + 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( graph [ i ] [ j ] ) { nodes [ i ] . edges . insert ( i ) ; nodes [ j ] . edges . insert ( j ) ; } } } cout << canPaint ( nodes , n , m ) ; cout << " STRNEWLINE " ; return 0 ; }
Maximize pair decrements required to reduce all array elements except one to 0 | C ++ program to implement the above approach ; Function to count maximum number of steps to make ( N - 1 ) array elements to 0 ; Stores maximum count of steps to make ( N - 1 ) elements equal to 0 ; Stores array elements ; Traverse the array ; Insert arr [ i ] into PQ ; Extract top 2 elements from the array while ( N - 1 ) array elements become 0 ; Stores top element of PQ ; Pop the top element of PQ . ; Stores top element of PQ ; Pop the top element of PQ . ; Update X ; Update Y ; If X is not equal to 0 ; Insert X into PQ ; if Y is not equal to 0 ; Insert Y into PQ ; Update cntOp ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntMaxOperationToMakeN_1_0 ( int arr [ ] , int N ) { int cntOp = 0 ; priority_queue < int > PQ ; for ( int i = 0 ; i < N ; i ++ ) { PQ . push ( arr [ i ] ) ; } while ( PQ . size ( ) > 1 ) { int X = PQ . top ( ) ; PQ . pop ( ) ; int Y = PQ . top ( ) ; PQ . pop ( ) ; X -- ; Y -- ; if ( X != 0 ) { PQ . push ( X ) ; } if ( Y != 0 ) { PQ . push ( Y ) ; } cntOp += 1 ; } return cntOp ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntMaxOperationToMakeN_1_0 ( arr , N ) ; return 0 ; }
Flip all K | C ++ Program for the above approach ; Function to flip all K - bits of an unsigned number N ; Stores ( 2 ^ K ) - 1 ; Update N ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void flippingBits ( unsigned long N , unsigned long K ) { unsigned long X = ( 1 << ( K - 1 ) ) - 1 ; N = X - N ; cout << N ; } int main ( ) { unsigned long N = 1 , K = 8 ; flippingBits ( N , K ) ; return 0 ; }
Generate a matrix having even sum of all diagonals in each 2 x 2 submatrices | C ++ program for the above approach ; Function to construct a matrix such that the sum elements in both diagonals of every 2 * 2 matrices is even ; Stores odd numbers ; Stores even numbers ; Store matrix elements such that sum of elements in both diagonals of every 2 * 2 submatrices is even ; Fill all the values of matrix elements ; Update odd ; Update even ; Print the matrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generateMatrix ( int N ) { int odd = 1 ; int even = 2 ; int mat [ N + 1 ] [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { if ( ( i + j ) % 2 == 0 ) { mat [ i ] [ j ] = odd ; odd += 2 ; } else { mat [ i ] [ j ] = even ; even += 2 ; } } } for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= N ; j ++ ) { cout << mat [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { int N = 4 ; generateMatrix ( N ) ; return 0 ; }
Queries to calculate sum by alternating signs of array elements in a given range | C ++ program to implement the above approach ; Function to build the segment tree ; If current node is a leaf node of the segment tree ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree ; Update on L segment tree ; Update on R segment tree ; Find the sum from L subtree and R subtree ; Function to update elements at index pos by val in the segment tree ; If current node is a leaf node ; If current index is even ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree elements into L and R subtree ; If element lies in L subtree ; Update tree [ index ] ; Function to find the sum of array elements in the range [ L , R ] ; If start and end not lies in the range [ L , R ] ; If start and end comleately lies in the range [ L , R ] ; Stores sum from left subtree ; Stores sum from right subtree ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void build ( int tree [ ] , int arr [ ] , int start , int end , int index ) { if ( start == end ) { if ( start % 2 == 0 ) { tree [ index ] = arr [ start ] ; } else { tree [ index ] = - arr [ start ] ; } return ; } int mid = start + ( end - start ) / 2 ; build ( tree , arr , start , mid , 2 * index + 1 ) ; build ( tree , arr , mid + 1 , end , 2 * index + 2 ) ; tree [ index ] = tree [ 2 * index + 1 ] + tree [ 2 * index + 2 ] ; } void update ( int tree [ ] , int index , int start , int end , int pos , int val ) { if ( start == end ) { if ( start % 2 == 0 ) { tree [ index ] = val ; } else { tree [ index ] = - val ; } return ; } int mid = start + ( end - start ) / 2 ; if ( mid >= pos ) { update ( tree , 2 * index + 1 , start , mid , pos , val ) ; } else { update ( tree , 2 * index + 2 , mid + 1 , end , pos , val ) ; } tree [ index ] = tree [ 2 * index + 1 ] + tree [ 2 * index + 2 ] ; } int FindSum ( int tree [ ] , int start , int end , int L , int R , int index ) { if ( L > end R < start ) { return 0 ; } if ( L <= start && R >= end ) { return tree [ index ] ; } int mid = start + ( end - start ) / 2 ; int X = FindSum ( tree , start , mid , L , R , 2 * index + 1 ) ; int Y = FindSum ( tree , mid + 1 , end , L , R , 2 * index + 2 ) ; return X + Y ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int tree [ 4 * N + 5 ] = { 0 } ; build ( tree , arr , 0 , N - 1 , 0 ) ; int Q [ ] [ 3 ] = { { 2 , 0 , 3 } , { 1 , 1 , 5 } , { 2 , 1 , 2 } } ; int cntQuey = 3 ; for ( int i = 0 ; i < cntQuey ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { update ( tree , 0 , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] ) ; } else { if ( Q [ i ] [ 1 ] % 2 == 0 ) { cout << FindSum ( tree , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 ) << " ▁ " ; } else { cout << - FindSum ( tree , 0 , N - 1 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 ) << " ▁ " ; } } } }
Split an array into minimum number of non | C ++ program for the above approach ; Function to split the array into minimum count of subarrays such that each subarray is either non - increasing or non - decreasing ; Initialize variable to keep track of current sequence ; Stores the required result ; Traverse the array , arr [ ] ; If current sequence is neither non - increasing nor non - decreasing ; If previous element is greater ; Update current ; If previous element is equal to the current element ; Update current ; Otherwise ; Update current ; If current sequence is in non - decreasing ; If previous element is less than or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; If current sequence is Non - Increasing ; If previous element is greater or equal to the current element ; Otherwise ; Update current as N and increment answer by 1 ; Print the answer ; Driver Code ; Given array ; Given size of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSubarrays ( int arr [ ] , int n ) { char current = ' N ' ; int answer = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( current == ' N ' ) { if ( arr [ i ] < arr [ i - 1 ] ) { current = ' D ' ; } else if ( arr [ i ] == arr [ i - 1 ] ) { current = ' N ' ; } else { current = ' I ' ; } } else if ( current == ' I ' ) { if ( arr [ i ] >= arr [ i - 1 ] ) { current = ' I ' ; } else { current = ' N ' ; answer += 1 ; } } else { if ( arr [ i ] <= arr [ i - 1 ] ) { current = ' D ' ; } else { current = ' N ' ; answer += 1 ; } } } cout << answer ; } int main ( ) { int arr [ ] = { 2 , 3 , 9 , 5 , 4 , 6 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumSubarrays ( arr , n ) ; return 0 ; }
Convert a Matrix into another Matrix of given dimensions | C ++ program to implement the above approach ; Function to construct a matrix of size A * B from the given matrix elements ; Initialize a new matrix ; Traverse the matrix , mat [ ] [ ] ; Update idx ; Print the resultant matrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ConstMatrix ( int * mat , int N , int M , int A , int B ) { if ( N * M != A * B ) return ; int idx = 0 ; int res [ A ] [ B ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { res [ idx / B ] [ idx % B ] = * ( ( mat + i * M ) + j ) ; idx ++ ; } } for ( int i = 0 ; i < A ; i ++ ) { for ( int j = 0 ; j < B ; j ++ ) cout << res [ i ] [ j ] << " ▁ " ; cout << " STRNEWLINE " ; } } int main ( ) { int mat [ ] [ 6 ] = { { 1 , 2 , 3 , 4 , 5 , 6 } } ; int A = 2 ; int B = 3 ; int N = sizeof ( mat ) / sizeof ( mat [ 0 ] ) ; int M = sizeof ( mat [ 0 ] ) / sizeof ( int ) ; ConstMatrix ( ( int * ) mat , N , M , A , B ) ; return 0 ; }
Modify given array by reducing each element by its next smaller element | C ++ program for the above approach ; Function to print the final array after reducing each array element by its next smaller element ; Initialize stack ; Array size ; To store the corresponding element ; If stack is not empty ; If top element is smaller than the current element ; Keep popping until stack is empty or top element is greater than the current element ; If stack is not empty ; Push current element ; Print the final array ; Driver Code ; Given array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printFinalPrices ( vector < int > & arr ) { stack < int > minStk ; int n = arr . size ( ) ; vector < int > reduce ( n , 0 ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( ! minStk . empty ( ) ) { if ( minStk . top ( ) <= arr [ i ] ) { reduce [ i ] = minStk . top ( ) ; } else { while ( ! minStk . empty ( ) && ( minStk . top ( ) > arr [ i ] ) ) { minStk . pop ( ) ; } if ( ! minStk . empty ( ) ) { reduce [ i ] = minStk . top ( ) ; } } } minStk . push ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] - reduce [ i ] << " ▁ " ; } int main ( ) { vector < int > arr = { 8 , 4 , 6 , 2 , 3 } ; printFinalPrices ( arr ) ; return 0 ; }
Generate array having differences between count of occurrences of every array element on its left and right | C ++ program of the above approach ; Function to construct array of differences of counts on the left and right of the given array ; Initialize left and right frequency arrays ; Construct left cumulative frequency table ; Construct right cumulative frequency table ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructArray ( int A [ ] , int N ) { int left [ N + 1 ] = { 0 } ; int right [ N + 1 ] = { 0 } ; int X [ N + 1 ] = { 0 } , Y [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { X [ i ] = left [ A [ i ] ] ; left [ A [ i ] ] ++ ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { Y [ i ] = right [ A [ i ] ] ; right [ A [ i ] ] ++ ; } for ( int i = 0 ; i < N ; i ++ ) { cout << Y [ i ] - X [ i ] << " ▁ " ; } } int main ( ) { int A [ ] = { 3 , 2 , 1 , 2 , 3 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; constructArray ( A , N ) ; return 0 ; }
Mean of distinct odd fibonacci nodes in a Linked List | C ++ program to implement the above approach ; Structure of a singly Linked List ; Stores data value of a Node ; Stores pointer to next Node ; Function to insert a node at the beginning of the singly Linked List ; Create a new Node ; Insert the data into the Node ; Insert pointer to the next Node ; Update head_ref ; Function to find the largest element from the linked list ; Stores the largest element in the linked list ; Iterate over the linked list ; If max is less than head -> data ; Update max ; Update head ; Function to store all Fibonacci numbers up to the largest element of the list ; Store all Fibonacci numbers up to Max ; Stores first element of Fibonacci number ; Stores second element of Fibonacci number ; Insert prev into hashmap ; Insert curr into hashmap ; Insert all elements of Fibonacci numbers up to Max ; Stores current fibonacci number ; Insert temp into hashmap ; Update prev ; Update curr ; Function to find the mean of odd Fibonacci nodes ; Stores the largest element in the linked list ; Stores all fibonacci numbers up to Max ; Stores current node of linked list ; Stores count of odd Fibonacci nodes ; Stores sum of all odd fibonacci nodes ; Traverse the linked list ; if the data value of current node is an odd number ; if data value of the node is present in hashmap ; Update cnt ; Update sum ; Remove current fibonacci number from hashmap so that duplicate elements can 't be counted ; Update curr ; Return the required mean ; Driver Code ; Stores head node of the linked list ; Insert all data values in the linked list
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int largestElement ( struct Node * head_ref ) { int Max = INT_MIN ; Node * head = head_ref ; while ( head != NULL ) { if ( Max < head -> data ) { Max = head -> data ; } head = head -> next ; } return Max ; } set < int > createHashMap ( int Max ) { set < int > hashmap ; int prev = 0 ; int curr = 1 ; hashmap . insert ( prev ) ; hashmap . insert ( curr ) ; while ( curr <= Max ) { int temp = curr + prev ; hashmap . insert ( temp ) ; prev = curr ; curr = temp ; } return hashmap ; } double meanofnodes ( struct Node * head ) { int Max = largestElement ( head ) ; set < int > hashmap = createHashMap ( Max ) ; Node * curr = head ; int cnt = 0 ; double sum = 0.0 ; while ( curr != NULL ) { if ( ( curr -> data ) & 1 ) { if ( hashmap . count ( curr -> data ) ) { cnt ++ ; sum += curr -> data ; hashmap . erase ( curr -> data ) ; } } curr = curr -> next ; } return ( sum / cnt ) ; } int main ( ) { Node * head = NULL ; push ( & head , 5 ) ; push ( & head , 21 ) ; push ( & head , 8 ) ; push ( & head , 12 ) ; push ( & head , 3 ) ; push ( & head , 13 ) ; push ( & head , 144 ) ; push ( & head , 6 ) ; cout << meanofnodes ( head ) ; return 0 ; }
Generate an alternate odd | C ++ Program to implement the above approach ; Function to print the required sequence ; Print ith odd number ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void findNumbers ( int n ) { int i = 0 ; while ( i <= n ) { cout << 2 * i * i + 4 * i + 1 + i % 2 << " ▁ " ; i ++ ; } } int main ( ) { int n = 6 ; findNumbers ( n ) ; }
Program to calculate gross salary of a person | C ++ Program to implement the above approach ; Function to calculate the salary of the person ; Condition to compute the allowance for the person ; Calculate gross salary ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int computeSalary ( int basic , char grade ) { int allowance ; double hra , da , pf ; hra = 0.2 * basic ; da = 0.5 * basic ; pf = 0.11 * basic ; if ( grade == ' A ' ) { allowance = 1700 ; } else if ( grade == ' B ' ) { allowance = 1500 ; } else { allowance = 1300 ; } int gross ; gross = round ( basic + hra + da + allowance - pf ) ; return gross ; } int main ( ) { int basic = 10000 ; char grade = ' A ' ; cout << computeSalary ( basic , grade ) ; }
Rearrange and update array elements as specified by the given queries | C ++ program to implement the above approach ; Function to perform the given operations ; Dequeue to store the array elements ; Insert all element of the array into the dequeue ; Stores the size of the queue ; Traverse each query ; Query for left shift . ; Extract the element at the front of the queue ; Pop the element at the front of the queue ; Push the element at the back of the queue ; Query for right shift ; Extract the element at the back of the queue ; Pop the element at the back of the queue ; Push the element at the front of the queue ; Query for update ; Query to get the value ; Driver Code ; All possible Queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Queries ( int arr [ ] , int N , vector < vector < int > > & Q ) { deque < int > dq ; for ( int i = 0 ; i < N ; i ++ ) { dq . push_back ( arr [ i ] ) ; } int sz = Q . size ( ) ; for ( int i = 0 ; i < sz ; i ++ ) { if ( Q [ i ] [ 0 ] == 0 ) { int front = dq [ 0 ] ; dq . pop_front ( ) ; dq . push_back ( front ) ; } else if ( Q [ i ] [ 0 ] == 1 ) { int back = dq [ N - 1 ] ; dq . pop_back ( ) ; dq . push_front ( back ) ; } else if ( Q [ i ] [ 0 ] == 2 ) { dq [ Q [ i ] [ 1 ] ] = Q [ i ] [ 2 ] ; } else { cout << dq [ Q [ i ] [ 1 ] ] << " ▁ " ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < vector < int > > Q ; Q = { { 0 } , { 1 } , { 3 , 1 } , { 2 , 2 , 54 } , { 3 , 2 } } ; Queries ( arr , N , Q ) ; return 0 ; }
Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal | C ++ Program to implement the above approach ; Function ot find the length of the smallest subarray ; Stores ( prefix Sum , index ) as ( key , value ) mappings ; Iterate till N ; Update the prefixSum ; Update the length ; Put the latest index to find the minimum length ; Update the length ; Return the answer ; Function to find the length of the largest subarray ; Stores the sum of all array elements after modification ; Change greater than k to 1 ; Change smaller than k to - 1 ; Change equal to k to 0 ; Update total_sum ; No deletion required , return 0 ; Delete smallest subarray that has sum = total_sum ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallSubarray ( int arr [ ] , int n , int total_sum ) { unordered_map < int , int > m ; int length = INT_MAX ; int prefixSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { prefixSum += arr [ i ] ; if ( prefixSum == total_sum ) { length = min ( length , i + 1 ) ; } m [ prefixSum ] = i ; if ( m . count ( prefixSum - total_sum ) ) { length = min ( length , i - m [ prefixSum - total_sum ] ) ; } } return length ; } int smallestSubarrayremoved ( int arr [ ] , int n , int k ) { int total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > k ) { arr [ i ] = 1 ; } else if ( arr [ i ] < k ) { arr [ i ] = -1 ; } else { arr [ i ] = 0 ; } total_sum += arr [ i ] ; } if ( total_sum == 0 ) { return 0 ; } else { return smallSubarray ( arr , n , total_sum ) ; } } int main ( ) { int arr [ ] = { 12 , 16 , 12 , 13 , 10 } ; int K = 13 ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << smallestSubarrayremoved ( arr , n , K ) ; return 0 ; }
Balanced Ternary Number System | C ++ program to convert positive decimals into balanced ternary system ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string balancedTernary ( int n ) { string output = " " ; while ( n > 0 ) { int rem = n % 3 ; n = n / 3 ; if ( rem == 2 ) { rem = -1 ; n ++ ; } output = ( rem == 0 ? '0' : ( rem == 1 ) ? '1' : ' Z ' ) + output ; } return output ; } int main ( ) { int n = 238 ; cout << " Equivalent ▁ Balanced ▁ Ternary ▁ of ▁ " << n << " ▁ is : ▁ " << balancedTernary ( n ) ; return 0 ; }
Spt function or Smallest Parts Function of a given number | C ++ implementation to find the Spt Function to given number ; variable to store spt function of a number ; Function to add value of frequency of minimum element among all representations of n ; find the value of frequency of minimum element ; calculate spt ; Recursive function to find different ways in which n can be written as a sum of at one or more positive integers ; if sum becomes n , consider this representation ; start from previous element in the representation till n ; include current element from representation ; call function again with reduced sum ; backtrack - remove current element from representation ; Function to find the spt function ; Using recurrence find different ways in which n can be written as a sum of at 1 or more positive integers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int spt = 0 ; void printVector ( vector < int > & arr ) { int min_i = INT_MAX ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) min_i = min ( min_i , arr [ i ] ) ; int freq = count ( arr . begin ( ) , arr . end ( ) , min_i ) ; spt += freq ; } void findWays ( vector < int > & arr , int i , int n ) { if ( n == 0 ) printVector ( arr ) ; for ( int j = i ; j <= n ; j ++ ) { arr . push_back ( j ) ; findWays ( arr , j , n - j ) ; arr . pop_back ( ) ; } } void spt_function ( int n ) { vector < int > arr ; findWays ( arr , 1 , n ) ; cout << spt ; } int main ( ) { int N = 4 ; spt_function ( N ) ; return 0 ; }
Find initial integral solution of Linear Diophantine equation if finite solution exists | C ++ program for the above approach ; Function to implement the extended euclid algorithm ; Base Case ; Recursively find the gcd ; Function to print the solutions of the given equations ax + by = c ; Condition for infinite solutions ; Condition for no solutions exist ; Condition for no solutions exist ; Print the solution ; Driver Code ; Given coefficients ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd_extend ( int a , int b , int & x , int & y ) { if ( b == 0 ) { x = 1 ; y = 0 ; return a ; } else { int g = gcd_extend ( b , a % b , x , y ) ; int x1 = x , y1 = y ; x = y1 ; y = x1 - ( a / b ) * y1 ; return g ; } } void print_solution ( int a , int b , int c ) { int x , y ; if ( a == 0 && b == 0 ) { if ( c == 0 ) { cout << " Infinite ▁ Solutions ▁ Exist " << endl ; } else { cout << " No ▁ Solution ▁ exists " << endl ; } } int gcd = gcd_extend ( a , b , x , y ) ; if ( c % gcd != 0 ) { cout << " No ▁ Solution ▁ exists " << endl ; } else { cout << " x ▁ = ▁ " << x * ( c / gcd ) << " , ▁ y ▁ = ▁ " << y * ( c / gcd ) << endl ; } } int main ( void ) { int a , b , c ; a = 4 ; b = 18 ; c = 10 ; print_solution ( a , b , c ) ; return 0 ; }
Count of pairs whose bitwise AND is a power of 2 | C ++ program for the above approach ; Function to check if x is power of 2 ; Returns true if x is a power of 2 ; Function to return the number of valid pairs ; Iterate for all possible pairs ; Bitwise and value of the pair is passed ; Return the final count ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int x ) { return x && ( ! ( x & ( x - 1 ) ) ) ; } int count ( int arr [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( check ( arr [ i ] & arr [ j ] ) ) cnt ++ ; } } return cnt ; } int main ( ) { int arr [ ] = { 6 , 4 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << count ( arr , n ) ; return 0 ; }
Check if the Matrix follows the given constraints or not | C ++ implementation of the above approach ; Function checks if n is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; Function returns sum of all elements of matrix ; Stores the sum of the matrix ; Function to check if all a [ i ] [ j ] with prime ( i + j ) are prime ; If index is prime ; If element not prime ; Driver code ; Check for both conditions
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i <= sqrt ( n ) ; i ++ ) if ( n % i == 0 ) return false ; return true ; } int takeSum ( int a [ 4 ] [ 5 ] ) { int sum = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) for ( int j = 0 ; j < 5 ; j ++ ) sum += a [ i ] [ j ] ; return sum ; } bool checkIndex ( int n , int m , int a [ 4 ] [ 5 ] ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( isPrime ( i + j ) ) { if ( ! isPrime ( a [ i ] [ j ] ) ) return false ; } } } return true ; } int main ( ) { int n = 4 , m = 5 ; int a [ 4 ] [ 5 ] = { { 1 , 2 , 3 , 2 , 2 } , { 2 , 2 , 7 , 7 , 7 } , { 7 , 7 , 21 , 7 , 10 } , { 2 , 2 , 3 , 6 , 7 } } ; int sum = takeSum ( a ) ; if ( isPrime ( sum ) && checkIndex ( n , m , a ) ) { cout << " YES " << endl ; } else cout << " NO " << endl ; return 0 ; }
Count of all possible pairs of array elements with same parity | C ++ program for the above approach ; Function to return the answer ; Generate all possible pairs ; Increment the count if both even or both odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int A [ ] , int n ) { int count = 0 , i , j ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( ( A [ i ] % 2 == 0 && A [ j ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ j ] % 2 != 0 ) ) count ++ ; } } return count ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 1 , 3 } ; int n = sizeof ( A ) / sizeof ( int ) ; cout << countPairs ( A , n ) ; }
Smallest number whose sum of digits is square of N | C ++ implementation of the above approach ; Function to return smallest number whose sum of digits is n ^ 2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNum ( int n ) { cout << pow ( 10 , n * n / 9 ) << endl ; return ( n * n % 9 + 1 ) * pow ( 10 , n * n / 9 ) - 1 ; } int main ( ) { int n = 4 ; cout << smallestNum ( n ) ; return 0 ; }
Second heptagonal numbers | C ++ implementation to find N - th term in the series ; Function to find N - th term in the series ; Driver code ; Function call
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void findNthTerm ( int n ) { cout << n * ( 5 * n + 3 ) / 2 << endl ; } int main ( ) { int N = 4 ; findNthTerm ( N ) ; return 0 ; } findNthTerm ( N ) ; return 0 ; }
Weakly Prime Numbers | C ++ Program to check if n is Weakly Prime Number ; function to check if N is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; function to check if n is a Weakly Prime Number ; number should be prime ; converting N to string ; loop to change digit at every character one by one . ; loop to store every digit one by one at index j ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool isWeaklyPrimeNum ( int N ) { if ( ! isPrime ( N ) ) return false ; string s = to_string ( N ) ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { string str = s ; for ( int i = 0 ; i <= 9 ; i ++ ) { char c = '0' + i ; str [ j ] = c ; int Num = stoi ( str ) ; if ( str [ j ] != s [ j ] && isPrime ( Num ) ) { return false ; } } } return true ; } int main ( ) { int n = 294001 ; if ( isWeaklyPrimeNum ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Unprimeable Numbers | C ++ Program to check if n is unprimeable Number ; function to check if N is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; function to check if n is a unprimeable Number ; number should be composite ; converting N to string ; loop to change digit at every character one by one . ; loop to store every digit one by one at index j ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool isUnPrimeableNum ( int N ) { if ( isPrime ( N ) ) return false ; string s = to_string ( N ) ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { string str = s ; for ( int i = 0 ; i <= 9 ; i ++ ) { char c = '0' + i ; str [ j ] = c ; int Num = stoi ( str ) ; if ( str [ j ] != s [ j ] && isPrime ( Num ) ) { return false ; } } } return true ; } int main ( ) { int n = 200 ; if ( isUnPrimeableNum ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the Nth row in Pascal 's Triangle | C ++ program to find the Nth index row in Pascal 's triangle ; Function to find the elements of rowIndex in Pascal 's Triangle ; 1 st element of every row is 1 ; Check if the row that has to be returned is the first row ; Generate the previous row ; Generate the elements of the current row by the help of the previous row ; Return the row ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > getRow ( int rowIndex ) { vector < int > currow ; currow . push_back ( 1 ) ; if ( rowIndex == 0 ) { return currow ; } vector < int > prev = getRow ( rowIndex - 1 ) ; for ( int i = 1 ; i < prev . size ( ) ; i ++ ) { int curr = prev [ i - 1 ] + prev [ i ] ; currow . push_back ( curr ) ; } currow . push_back ( 1 ) ; return currow ; } int main ( ) { int n = 3 ; vector < int > arr = getRow ( n ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( i == arr . size ( ) - 1 ) cout << arr [ i ] ; else cout << arr [ i ] << " , ▁ " ; } return 0 ; }
All possible values of floor ( N / K ) for all values of K | C ++ Program for the above approach ; Function to print all possible values of floor ( N / K ) ; loop from 1 to N + 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void allQuotients ( int N ) { set < int > s ; for ( int k = 1 ; k <= N + 1 ; k ++ ) { s . insert ( N / k ) ; } for ( auto it : s ) cout << it << " ▁ " ; } int main ( ) { int N = 5 ; allQuotients ( N ) ; return 0 ; }
Greatest odd factor of an even number | C ++ program for the above approach ; Function to print greatest odd factor ; Initialize i with 1 ; Iterate till i <= pow_2 ; Find the pow ( 2 , i ) ; If factor is odd , then print the number and break ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int greatestOddFactor ( int n ) { int pow_2 = ( int ) ( log ( n ) ) ; int i = 1 ; while ( i <= pow_2 ) { int fac_2 = ( 2 * i ) ; if ( n % fac_2 == 0 ) { if ( ( n / fac_2 ) % 2 == 1 ) { return ( n / fac_2 ) ; } } i += 1 ; } } int main ( ) { int N = 8642 ; cout << greatestOddFactor ( N ) ; return 0 ; }
Find the element in a linked list with frequency at least N / 3 | C ++ program to find an element with frequency of at least N / 3 in a linked list ; Structure of a node for the linked list ; Utility function to create a node ; Function to find and return the element with frequency of at least N / 3 ; Candidates for being the required majority element ; Store the frequencies of the respective candidates ; Iterate all nodes ; Increase frequency of candidate s ; Increase frequency of candidate t ; Set the new sting as candidate for majority ; Set the new sting as second candidate for majority ; Decrease the frequency ; Check the frequency of two final selected candidate linklist ; Increase the frequency of first candidate ; Increase the frequency of second candidate ; Return the string with higher frequency ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { string i ; node * next = NULL ; } ; struct node * newnode ( string s ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> i = s ; temp -> next = NULL ; return temp ; } string Majority_in_linklist ( node * head ) { string s = " " , t = " " ; int p = 0 , q = 0 ; node * ptr = NULL ; while ( head != NULL ) { if ( s . compare ( head -> i ) == 0 ) { p = p + 1 ; } else { if ( t . compare ( head -> i ) == 0 ) { q = q + 1 ; } else { if ( p == 0 ) { s = head -> i ; p = 1 ; } else { if ( q == 0 ) { t = head -> i ; q = 1 ; } else { p = p - 1 ; q = q - 1 ; } } } } head = head -> next ; } head = ptr ; p = 0 ; q = 0 ; while ( head != NULL ) { if ( s . compare ( head -> i ) == 0 ) { p = 1 ; } else { if ( t . compare ( head -> i ) == 0 ) { q = 1 ; } } head = head -> next ; } if ( p > q ) { return s ; } else { return t ; } } int main ( ) { node * ptr = NULL ; node * head = newnode ( " geeks " ) ; head -> next = newnode ( " geeks " ) ; head -> next -> next = newnode ( " abcd " ) ; head -> next -> next -> next = newnode ( " game " ) ; head -> next -> next -> next -> next = newnode ( " game " ) ; head -> next -> next -> next -> next -> next = newnode ( " knight " ) ; head -> next -> next -> next -> next -> next -> next = newnode ( " harry " ) ; head -> next -> next -> next -> next -> next -> next -> next = newnode ( " geeks " ) ; cout << Majority_in_linklist ( head ) << endl ; return 0 ; }