text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Count the number of carry operations required to add two numbers | C ++ implementation of above approach ; Function to count the number of carry operations ; Initialize the value of carry to 0 ; Counts the number of carry operations ; Initialize len_a and len_b with the sizes of strings ; Assigning the ascii value of the character ; Add both numbers / digits ; If sum > 0 , increment count and set carry to 1 ; Else , set carry to 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_carry ( string a , string b ) { int carry = 0 ; int count = 0 ; int len_a = a . length ( ) , len_b = b . length ( ) ; while ( len_a != 0 len_b != 0 ) { int x = 0 , y = 0 ; if ( len_a > 0 ) { x = a [ len_a - 1 ] - '0' ; len_a -- ; } if ( len_b > 0 ) { y = b [ len_b - 1 ] - '0' ; len_b -- ; } int sum = x + y + carry ; if ( sum >= 10 ) { carry = 1 ; count ++ ; } else carry = 0 ; } return count ; } int main ( ) { string a = "9555" , b = "555" ; int count = count_carry ( a , b ) ; if ( count == 0 ) cout << "0 STRNEWLINE " ; else if ( count == 1 ) cout << "1 STRNEWLINE " ; else cout << count << " STRNEWLINE " ; return 0 ; }
Check if a number is in given base or not | CPP program to check if given number is in given base or not . ; Allowed bases are till 16 ( Hexadecimal ) ; If base is below or equal to 10 , then all digits should be from 0 to 9. ; If base is below or equal to 16 , then all digits should be from 0 to 9 or from ' A ' ; Driver code
#include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; bool isInGivenBase ( string str , int base ) { if ( base > 16 ) return false ; else if ( base <= 10 ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( ! ( str [ i ] >= '0' and str [ i ] < ( '0' + base ) ) ) return false ; } else { for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( ! ( ( str [ i ] >= '0' && str [ i ] < ( '0' + base ) ) || ( str [ i ] >= ' A ' && str [ i ] < ( ' A ' + base - 10 ) ) ) ) return false ; } return true ; } int main ( ) { string str = " AF87" ; if ( isInGivenBase ( str , 16 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find indices of all occurrence of one string in other | C ++ program to find indices of all occurrences of one string in other . ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printIndex ( string str , string s ) { bool flag = false ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . substr ( i , s . length ( ) ) == s ) { cout << i << " ▁ " ; flag = true ; } } if ( flag == false ) cout << " NONE " ; } int main ( ) { string str1 = " GeeksforGeeks " ; string str2 = " Geeks " ; printIndex ( str1 , str2 ) ; return 0 ; }
Alternatively Merge two Strings in Java | C ++ code to alternatively merge two strings ; Function for alternatively merging two strings ; To store the final string ; For every index in the strings ; First choose the ith character of the first string if it exists ; Then choose the ith character of the second string if it exists ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string merge ( string s1 , string s2 ) { string result = " " ; for ( int i = 0 ; i < s1 . length ( ) || i < s2 . length ( ) ; i ++ ) { if ( i < s1 . length ( ) ) result += s1 [ i ] ; if ( i < s2 . length ( ) ) result += s2 [ i ] ; } return result ; } int main ( ) { string s1 = " geeks " ; string s2 = " forgeeks " ; cout << merge ( s1 , s2 ) ; return 0 ; }
Maximum occurring character in an input string | Set | C ++ implementation to find the maximum occurring character in an input string which is lexicographically first ; function to find the maximum occurring character in an input string which is lexicographically first ; freq [ ] used as hash table ; to store maximum frequency ; to store the maximum occurring character ; length of ' str ' ; get frequency of each character of ' str ' ; for each character , where character is obtained by ( i + ' a ' ) check whether it is the maximum character so far and accodingly update ' result ' ; maximum occurring character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char getMaxOccurringChar ( char str [ ] ) { int freq [ 26 ] = { 0 } ; int max = -1 ; char result ; int len = strlen ( str ) ; for ( int i = 0 ; i < len ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) if ( max < freq [ i ] ) { max = freq [ i ] ; result = ( char ) ( i + ' a ' ) ; } return result ; } int main ( ) { char str [ ] = " sample ▁ program " ; cout << " Maximum ▁ occurring ▁ character ▁ = ▁ " << getMaxOccurringChar ( str ) ; return 0 ; }
Check if the given string of words can be formed from words present in the dictionary | C ++ program to check if a sentence can be formed from a given set of words . ; here isEnd is an integer that will store count of words ending at that node ; utility function to create a new node ; Initialize new node with null ; Function to insert new words in trie ; Iterate for the length of a word ; If the next key does not contains the character ; isEnd is increment so not only the word but its count is also stored ; Search function to find a word of a sentence ; Iterate for the complete length of the word ; If the character is not present then word is also not present ; If present move to next character in Trie ; If word foundthen decrement count of the word ; if the word is found decrement isEnd showing one occurrence of this word is already taken so ; Function to check if string can be formed from the sentence ; Iterate for all words in the string ; if a word is not found in a string then the sentence cannot be made from this dictionary of words ; If possible ; Function to insert all the words of dictionary in the Trie ; Driver Code ; Dictionary of words ; Calling Function to insert words of dictionary to tree ; String to be checked ; Function call to check possibility
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int ALPHABET_SIZE = 26 ; struct trieNode { trieNode * t [ ALPHABET_SIZE ] ; int isEnd ; } ; trieNode * getNode ( ) { trieNode * temp = new ( trieNode ) ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) temp -> t [ i ] = NULL ; temp -> isEnd = 0 ; return temp ; } void insert ( trieNode * root , string key ) { trieNode * trail ; trail = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { if ( trail -> t [ key [ i ] - ' a ' ] == NULL ) { trieNode * temp ; temp = getNode ( ) ; trail -> t [ key [ i ] - ' a ' ] = temp ; } trail = trail -> t [ key [ i ] - ' a ' ] ; } ( trail -> isEnd ) ++ ; } bool search_mod ( trieNode * root , string word ) { trieNode * trail ; trail = root ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { if ( trail -> t [ word [ i ] - ' a ' ] == NULL ) return false ; trail = trail -> t [ word [ i ] - ' a ' ] ; } if ( ( trail -> isEnd ) > 0 && trail != NULL ) { ( trail -> isEnd ) -- ; return true ; } else return false ; } void checkPossibility ( string sentence [ ] , int m , trieNode * root ) { int flag = 1 ; for ( int i = 0 ; i < m ; i ++ ) { if ( search_mod ( root , sentence [ i ] ) == false ) { cout << " NO " ; return ; } } cout << " YES " ; } void insertToTrie ( string dictionary [ ] , int n , trieNode * root ) { for ( int i = 0 ; i < n ; i ++ ) insert ( root , dictionary [ i ] ) ; } int main ( ) { trieNode * root ; root = getNode ( ) ; string dictionary [ ] = { " find " , " a " , " geeks " , " all " , " for " , " on " , " geeks " , " answers " , " inter " } ; int N = sizeof ( dictionary ) / sizeof ( dictionary [ 0 ] ) ; insertToTrie ( dictionary , N , root ) ; string sentence [ ] = { " find " , " all " , " answers " , " on " , " geeks " , " for " , " geeks " } ; int M = sizeof ( sentence ) / sizeof ( sentence [ 0 ] ) ; checkPossibility ( sentence , M , root ) ; return 0 ; }
Given two numbers as strings , find if one is a power of other | CPP program to check if one number is power of other ; Multiply the numbers . It multiplies each digit of second string to each digit of first and stores the result . ; If the digit exceeds 9 , add the cumulative carry to previous digit . ; if all zeroes , return "0" . ; Remove starting zeroes . ; Removes Extra zeroes from front of a string . ; Make sure there are no leading zeroes in the string . ; Making sure that s1 is smaller . If it is greater , we recur we reversed parameters . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isGreaterThanEqualTo ( string s1 , string s2 ) { if ( s1 . size ( ) > s2 . size ( ) ) return true ; return ( s1 == s2 ) ; } string multiply ( string s1 , string s2 ) { int n = s1 . size ( ) ; int m = s2 . size ( ) ; vector < int > result ( n + m , 0 ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) for ( int j = m - 1 ; j >= 0 ; j -- ) result [ i + j + 1 ] += ( s1 [ i ] - '0' ) * ( s2 [ j ] - '0' ) ; int size = result . size ( ) ; for ( int i = size - 1 ; i > 0 ; i -- ) { if ( result [ i ] >= 10 ) { result [ i - 1 ] += result [ i ] / 10 ; result [ i ] = result [ i ] % 10 ; } } int i = 0 ; while ( i < size && result [ i ] == 0 ) i ++ ; if ( i == size ) return "0" ; string temp ; while ( i < size ) { temp += ( result [ i ] + '0' ) ; i ++ ; } return temp ; } string removeLeadingZeores ( string s ) { int n = s . size ( ) ; int i = 0 ; while ( i < n && s [ i ] == '0' ) i ++ ; if ( i == n ) return "0" ; string temp ; while ( i < n ) temp += s [ i ++ ] ; return temp ; } bool isPower ( string s1 , string s2 ) { s1 = removeLeadingZeores ( s1 ) ; s2 = removeLeadingZeores ( s2 ) ; if ( s1 == "0" s2 == "0" ) return false ; if ( s1 == "1" && s2 == "1" ) return true ; if ( s1 == "1" s2 == "1" ) return true ; if ( s1 . size ( ) > s2 . size ( ) ) return isPower ( s2 , s1 ) ; string temp = s1 ; while ( ! isGreaterThanEqualTo ( s1 , s2 ) ) s1 = multiply ( s1 , temp ) ; return s1 == s2 ; } int main ( ) { string s1 = "374747" , s2 = "52627712618930723" ; cout << ( isPower ( s1 , s2 ) ? " YES STRNEWLINE " : " NO STRNEWLINE " ) ; s1 = "4099" , s2 = "2" ; cout << ( isPower ( s1 , s2 ) ? " YES STRNEWLINE " : " NO STRNEWLINE " ) ; return 0 ; }
Check for balanced parentheses in an expression | O ( 1 ) space | C ++ code to check balanced parentheses with O ( 1 ) space . ; Function1 to match closing bracket ; Function1 to match opening bracket ; Function to check balanced parentheses ; helper variables ; Handling case of opening parentheses ; Handling case of closing parentheses ; If corresponding matching opening parentheses doesn 't lie in given interval return 0 ; else continue ; If corresponding closing parentheses doesn 't lie in given interval return 0 ; if found , now check for each opening and closing parentheses in this interval ; Driver Code
#include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int matchClosing ( char X [ ] , int start , int end , char open , char close ) { int c = 1 ; int i = start + 1 ; while ( i <= end ) { if ( X [ i ] == open ) c ++ ; else if ( X [ i ] == close ) c -- ; if ( c == 0 ) return i ; i ++ ; } return i ; } int matchingOpening ( char X [ ] , int start , int end , char open , char close ) { int c = -1 ; int i = end - 1 ; while ( i >= start ) { if ( X [ i ] == open ) c ++ ; else if ( X [ i ] == close ) c -- ; if ( c == 0 ) return i ; i -- ; } return -1 ; } bool isBalanced ( char X [ ] , int n ) { int i , j , k , x , start , end ; for ( i = 0 ; i < n ; i ++ ) { if ( X [ i ] == ' ( ' ) j = matchClosing ( X , i , n - 1 , ' ( ' , ' ) ' ) ; else if ( X [ i ] == ' { ' ) j = matchClosing ( X , i , n - 1 , ' { ' , ' } ' ) ; else if ( X [ i ] == ' [ ' ) j = matchClosing ( X , i , n - 1 , ' [ ' , ' ] ' ) ; else { if ( X [ i ] == ' ) ' ) j = matchingOpening ( X , 0 , i , ' ( ' , ' ) ' ) ; else if ( X [ i ] == ' } ' ) j = matchingOpening ( X , 0 , i , ' { ' , ' } ' ) ; else if ( X [ i ] == ' ] ' ) j = matchingOpening ( X , 0 , i , ' [ ' , ' ] ' ) ; if ( j < 0 j > = i ) return false ; continue ; } if ( j >= n j < 0 ) return false ; start = i ; end = j ; for ( k = start + 1 ; k < end ; k ++ ) { if ( X [ k ] == ' ( ' ) { x = matchClosing ( X , k , end , ' ( ' , ' ) ' ) ; if ( ! ( k < x && x < end ) ) { return false ; } } else if ( X [ k ] == ' ) ' ) { x = matchingOpening ( X , start , k , ' ( ' , ' ) ' ) ; if ( ! ( start < x && x < k ) ) { return false ; } } if ( X [ k ] == ' { ' ) { x = matchClosing ( X , k , end , ' { ' , ' } ' ) ; if ( ! ( k < x && x < end ) ) { return false ; } } else if ( X [ k ] == ' } ' ) { x = matchingOpening ( X , start , k , ' { ' , ' } ' ) ; if ( ! ( start < x && x < k ) ) { return false ; } } if ( X [ k ] == ' [ ' ) { x = matchClosing ( X , k , end , ' [ ' , ' ] ' ) ; if ( ! ( k < x && x < end ) ) { return false ; } } else if ( X [ k ] == ' ] ' ) { x = matchingOpening ( X , start , k , ' [ ' , ' ] ' ) ; if ( ! ( start < x && x < k ) ) { return false ; } } } } return true ; } int main ( ) { char X [ ] = " [ ( ) ] ( ) " ; int n = 6 ; if ( isBalanced ( X , n ) ) printf ( " Yes STRNEWLINE " ) ; else printf ( " No STRNEWLINE " ) ; char Y [ ] = " [ [ ( ) ] ] ) " ; n = 7 ; if ( isBalanced ( Y , n ) ) printf ( " Yes STRNEWLINE " ) ; else printf ( " No STRNEWLINE " ) ; return 0 ; }
Sorting array with conditional swapping | CPP program to Check if it is possible to sort the array in ascending order . ; Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string possibleToSort ( int * arr , int n , string str ) { int max_element = -1 ; for ( long i = 0 ; i < str . size ( ) ; i ++ ) { max_element = max ( max_element , arr [ i ] ) ; if ( str [ i ] == '0' ) { if ( max_element > i + 1 ) return " No " ; } } return " Yes " ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string str = "01110" ; cout << possibleToSort ( arr , n , str ) ; return 0 ; }
Find sub | C ++ program to find substring with given power ; Function to print indexes of substring with power as given power . ; Create an empty map ; Maintains sum of powers of characters so far . ; Add current character power to curr_power . ; If curr_power is equal to target power we found a substring starting from index 0 and ending at index i . ; If curr_power - power already exists in map then we have found a subarray with target power . ; If we reach here , then no substring exists . ; Drivers code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; void findSubstring ( string str , ll power ) { ll i ; unordered_map < ll , ll > map ; int curr_power = 0 ; int len = str . length ( ) ; for ( i = 0 ; i < len ; i ++ ) { curr_power = curr_power + ( str [ i ] - ' a ' + 1 ) ; if ( curr_power == power ) { cout << " Substring ▁ from ▁ index ▁ " << 0 << " ▁ to ▁ " << i << " ▁ has ▁ power ▁ " << power << endl ; return ; } if ( map . find ( curr_power - power ) != map . end ( ) ) { cout << " Substring ▁ from ▁ index ▁ " << map [ curr_power - power ] + 1 << " ▁ to ▁ " << i << " ▁ has ▁ power ▁ " << power << endl ; return ; } map [ curr_power ] = i ; } cout << " No ▁ substring ▁ with ▁ given ▁ power ▁ exists . " ; } int main ( ) { string str = " geeksforgeeks " ; ll power = 36 ; findSubstring ( str , power ) ; return 0 ; }
Prime String | C ++ program to find if string is a Prime or not . ; Function that checks if sum is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrimeString ( string str ) { int len = str . length ( ) , n = 0 ; for ( int i = 0 ; i < len ; i ++ ) n += ( int ) str [ i ] ; 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 ; } int main ( ) { string str = " geekRam " ; if ( isPrimeString ( str ) ) cout << " Yes " << endl ; else cout << " No " << endl ; }
Ways to split string such that each partition starts with distinct character | CPP Program to find number of way to split string such that each partition starts with distinct character with maximum number of partitions . ; Returns the number of we can split the string ; Finding the frequency of each character . ; making frequency of first character of string equal to 1. ; Finding the product of frequency of occurrence of each character . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( string s ) { int count [ 26 ] = { 0 } ; for ( char x : s ) count [ x - ' a ' ] ++ ; count [ s [ 0 ] - ' a ' ] = 1 ; int ans = 1 ; for ( int i = 0 ; i < 26 ; ++ i ) if ( count [ i ] != 0 ) ans *= count [ i ] ; return ans ; } int main ( ) { string s = " acbbcc " ; cout << countWays ( s ) << endl ; return 0 ; }
Lexicographically next greater string using same character set | C ++ implementation of above algorithm . ; function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; return ; end the program ; searching the first character left of index k and not equal to greatest character of the string ; finding the just next greater character than s [ i ] ; suffix with smallest character ; if we reach here then all indices to the left of k had the greatest character ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void lexoString ( string s , int k ) { int n = s . size ( ) ; vector < char > v ; map < char , int > mp ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( mp [ s [ i ] ] == 0 ) { mp [ s [ i ] ] = 1 ; v . push_back ( s [ i ] ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; if ( k > n ) { cout << s ; for ( int i = n ; i < k ; i ++ ) { cout << v [ 0 ] ; } } for ( int i = k - 1 ; i >= 0 ; i -- ) { if ( s [ i ] != v [ v . size ( ) - 1 ] ) { for ( int j = 0 ; j < i ; j ++ ) { cout << s [ j ] ; } for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v [ j ] > s [ i ] ) { cout << v [ j ] ; break ; } } for ( int j = i + 1 ; j < k ; j ++ ) cout << v [ 0 ] ; return ; } } cout << " No ▁ lexicographically ▁ greater ▁ string ▁ of ▁ length ▁ " << k << " ▁ possible ▁ here . " ; } int main ( ) { string s = " gi " ; int k = 3 ; lexoString ( s , k ) ; return 0 ; }
Number of palindromic permutations | Set 1 | CPP program to find number of palindromic permutations of a given string ; Returns factorial of n ; Returns count of palindromic permutations of str . ; Count frequencies of all characters ; Since half of the characters decide count of palindromic permutations , we take ( n / 2 ) ! ; To make sure that there is at most one odd occurring char ; Traverse through all counts ; To make sure that the string can permute to form a palindrome ; If there are more than one odd occurring chars ; Divide all permutations with repeated characters ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 256 ; long long int fact ( int n ) { long long int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } int countPalinPermutations ( string & str ) { int n = str . length ( ) ; int freq [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ str [ i ] ] ++ ; long long int res = fact ( n / 2 ) ; bool oddFreq = false ; for ( int i = 0 ; i < MAX ; i ++ ) { int half = freq [ i ] / 2 ; if ( freq [ i ] % 2 != 0 ) { if ( oddFreq == true ) return 0 ; oddFreq = true ; } res = res / fact ( half ) ; } return res ; } int main ( ) { string str = " gffg " ; cout << countPalinPermutations ( str ) ; return 0 ; }
Rearrange characters to form palindrome if possible | C ++ program to rearrange a string to make palindrome . ; Store counts of characters ; find the number of odd elements . Takes O ( n ) ; odd_cnt = 1 only if the length of str is odd ; Generate first halh of palindrome ; Build a string of floor ( count / 2 ) occurrences of current character ; Attach the built string to end of and begin of second half ; Insert odd character if there is any ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string getPalindrome ( string str ) { unordered_map < char , int > hmap ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) hmap [ str [ i ] ] ++ ; int oddCount = 0 ; char oddChar ; for ( auto x : hmap ) { if ( x . second % 2 != 0 ) { oddCount ++ ; oddChar = x . first ; } } if ( oddCount > 1 || oddCount == 1 && str . length ( ) % 2 == 0 ) return " NO ▁ PALINDROME " ; string firstHalf = " " , secondHalf = " " ; for ( auto x : hmap ) { string s ( x . second / 2 , x . first ) ; firstHalf = firstHalf + s ; secondHalf = s + secondHalf ; } return ( oddCount == 1 ) ? ( firstHalf + oddChar + secondHalf ) : ( firstHalf + secondHalf ) ; } int main ( ) { string s = " mdaam " ; cout << getPalindrome ( s ) ; return 0 ; }
Substrings starting with vowel and ending with consonants and vice versa | CPP program to count special strings ; Returns true if ch is vowel ; function to check consonant ; in case of empty string , we can 't fullfill the required condition, hence we return ans as 0. ; co [ i ] is going to store counts of consonants from str [ len - 1 ] to str [ i ] . vo [ i ] is going to store counts of vowels from str [ len - 1 ] to str [ i ] . ; Counting consonants and vowels from end of string . ; Now we traverse string from beginning ; If vowel , then count of substrings starting with str [ i ] is equal to count of consonants after it . ; If consonant , then count of substrings starting with str [ i ] is equal to count of vowels after it . ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } bool isCons ( char ch ) { return ( ch != ' a ' && ch != ' e ' && ch != ' i ' && ch != ' o ' && ch != ' u ' ) ; } int countSpecial ( string & str ) { int len = str . length ( ) ; if ( len == 0 ) return 0 ; int co [ len + 1 ] ; int vo [ len + 1 ] ; memset ( co , 0 , sizeof ( co ) ) ; memset ( vo , 0 , sizeof ( vo ) ) ; if ( isCons ( str [ len - 1 ] ) == 1 ) co [ len - 1 ] = 1 ; else vo [ len - 1 ] = 1 ; for ( int i = len - 2 ; i >= 0 ; i -- ) { if ( isCons ( str [ i ] ) == 1 ) { co [ i ] = co [ i + 1 ] + 1 ; vo [ i ] = vo [ i + 1 ] ; } else { co [ i ] = co [ i + 1 ] ; vo [ i ] = vo [ i + 1 ] + 1 ; } } long long ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( isVowel ( str [ i ] ) ) ans = ans + co [ i + 1 ] ; else ans = ans + vo [ i + 1 ] ; } return ans ; } int main ( ) { string str = " adceba " ; cout << countSpecial ( str ) ; return 0 ; }
Convert the string into palindrome string by changing only one character | CPP program to Check if it is possible to convert the string into palindrome string by changing only one character . ; Function to check if it is possible to convert the string into palindrome ; Counting number of characters that should be changed . ; If count of changes is less than or equal to 1 ; Driver function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPalindrome ( string str ) { int n = str . length ( ) ; int count = 0 ; for ( int i = 0 ; i < n / 2 ; ++ i ) if ( str [ i ] != str [ n - i - 1 ] ) ++ count ; return ( count <= 1 ) ; } int main ( ) { string str = " abccaa " ; if ( checkPalindrome ( str ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Counting even decimal value substrings in a binary string | Program to count all even decimal value substring . ; function return count of even decimal value substring ; store the count of even decimal value substring ; substring started with '0' ; increment result by ( n - i ) because all substring which are generate by this character produce even decimal value . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int evenDecimalValue ( string str , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) { result += ( n - i ) ; } } return result ; } int main ( ) { string str = "10010" ; int n = 5 ; cout << evenDecimalValue ( str , n ) << endl ; return 0 ; }
Number of substrings with odd decimal value in a binary string | CPP program to count substrings with odd decimal value ; function to count number of substrings with odd decimal representation ; auxiliary array to store count of 1 's before ith index ; store count of 1 's before i-th index ; variable to store answer ; traverse the string reversely to calculate number of odd substrings before i - th index ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countSubstr ( string s ) { int n = s . length ( ) ; int auxArr [ n ] = { 0 } ; if ( s [ 0 ] == '1' ) auxArr [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) auxArr [ i ] = auxArr [ i - 1 ] + 1 ; else auxArr [ i ] = auxArr [ i - 1 ] ; } int count = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) if ( s [ i ] == '1' ) count += auxArr [ i ] ; return count ; } int main ( ) { string s = "1101" ; cout << countSubstr ( s ) ; return 0 ; }
Find the starting indices of the substrings in string ( S ) which is made by concatenating all words from a list ( L ) | CPP program to calculate the starting indices of substrings inside S which contains all the words present in List L . ; Returns an integer vector consisting of starting indices of substrings present inside the string S ; Number of a characters of a word in list L . ; Number of words present inside list L . ; Total characters present in list L . ; Resultant vector which stores indices . ; If the total number of characters in list L is more than length of string S itself . ; Map stores the words present in list L against it 's occurrences inside list L ; Traverse the substring ; Extract the word ; If word not found or if frequency of current word is more than required simply break . ; Else decrement the count of word from hash_map ; Store the starting index of that substring when all the words in the list are in substring ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findSubstringIndices ( string S , const vector < string > & L ) { int size_word = L [ 0 ] . size ( ) ; int word_count = L . size ( ) ; int size_L = size_word * word_count ; vector < int > res ; if ( size_L > S . size ( ) ) return res ; unordered_map < string , int > hash_map ; for ( int i = 0 ; i < word_count ; i ++ ) hash_map [ L [ i ] ] ++ ; for ( int i = 0 ; i <= S . size ( ) - size_L ; i ++ ) { unordered_map < string , int > temp_hash_map ( hash_map ) ; int j = i , count = word_count ; while ( j < i + size_L ) { string word = S . substr ( j , size_word ) ; if ( hash_map . find ( word ) == hash_map . end ( ) temp_hash_map [ word ] == 0 ) break ; else { temp_hash_map [ word ] -- ; count -- ; } j += size_word ; } if ( count == 0 ) res . push_back ( i ) ; } return res ; } int main ( ) { string S = " barfoothefoobarman " ; vector < string > L = { " foo " , " bar " } ; vector < int > indices = findSubstringIndices ( S , L ) ; for ( int i = 0 ; i < indices . size ( ) ; i ++ ) cout << indices [ i ] << " ▁ " ; return 0 ; }
Check whether second string can be formed from characters of first string | CPP program to check whether second string can be formed from first string ; Create a count array and count frequencies characters in str1 . ; Now traverse through str2 to check if every character has enough counts ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 256 ; bool canMakeStr2 ( string str1 , string str2 ) { int count [ MAX ] = { 0 } ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) count [ str1 [ i ] ] ++ ; for ( int i = 0 ; i < str2 . length ( ) ; i ++ ) { if ( count [ str2 [ i ] ] == 0 ) return false ; count [ str2 [ i ] ] -- ; } return true ; } int main ( ) { string str1 = " geekforgeeks " ; string str2 = " for " ; if ( canMakeStr2 ( str1 , str2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Position of robot after given movements | C ++ implementation to find final position of robot after the complete movement ; Function to find final position of robot after the complete movement ; Traverse the instruction string ' move ' ; For each movement increment its respective counter ; Required final position of robot ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void finalPosition ( string move ) { int l = move . size ( ) ; int countUp = 0 , countDown = 0 ; int countLeft = 0 , countRight = 0 ; for ( int i = 0 ; i < l ; i ++ ) { if ( move [ i ] == ' U ' ) countUp ++ ; else if ( move [ i ] == ' D ' ) countDown ++ ; else if ( move [ i ] == ' L ' ) countLeft ++ ; else if ( move [ i ] == ' R ' ) countRight ++ ; } cout << " Final ▁ Position : ▁ ( " << ( countRight - countLeft ) << " , ▁ " << ( countUp - countDown ) << " ) " << endl ; } int main ( ) { string move = " UDDLLRUUUDUURUDDUULLDRRRR " ; finalPosition ( move ) ; return 0 ; }
Length of longest balanced parentheses prefix | CPP Program to find length of longest balanced parentheses prefix . ; Return the length of longest balanced parentheses prefix . ; Traversing the string . ; If open bracket add 1 to sum . ; If closed bracket subtract 1 from sum ; if first bracket is closing bracket then this condition would help ; If sum is 0 , store the index value . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxbalancedprefix ( char str [ ] , int n ) { int sum = 0 ; int maxi = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) sum += 1 ; else sum -= 1 ; if ( sum < 0 ) break ; if ( sum == 0 ) maxi = i + 1 ; } return maxi ; } int main ( ) { char str [ ] = " ( ( ( ) ( ) ) ( ) ) ( ( " ; int n = strlen ( str ) ; cout << maxbalancedprefix ( str , n ) << endl ; return 0 ; }
Minimum cost to convert string into palindrome | CPP program to find minimum cost to make a palindrome . ; Function to return cost ; length of string ; Iterate from both sides of string . If not equal , a cost will be there ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cost ( string str ) { int len = str . length ( ) ; int res = 0 ; for ( int i = 0 , j = len - 1 ; i < j ; i ++ , j -- ) if ( str [ i ] != str [ j ] ) res += min ( str [ i ] , str [ j ] ) - ' a ' + 1 ; return res ; } int main ( ) { string str = " abcdef " ; cout << cost ( str ) << endl ; return 0 ; }
Encoding a word into Pig Latin | C ++ program to encode a word to a Pig Latin . ; the index of the first vowel is stored . ; Pig Latin is possible only if vowels is present ; Take all characters after index ( including index ) . Append all characters which are before index . Finally append " ay " ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { return ( c == ' A ' c == ' E ' c == ' I ' c == ' O ' c == ' U ' c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } string pigLatin ( string s ) { int len = s . length ( ) ; int index = -1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( isVowel ( s [ i ] ) ) { index = i ; break ; } } if ( index == -1 ) return " - 1" ; return s . substr ( index ) + s . substr ( 0 , index ) + " ay " ; } int main ( ) { string str = pigLatin ( " graphic " ) ; if ( str == " - 1" ) cout << " No ▁ vowels ▁ found . ▁ Pig ▁ Latin ▁ not ▁ possible " ; else cout << str ; }
Possibility of a word from a given set of characters | CPP program to check if a query string is present is given set . ; Count occurrences of all characters in s . ; Check if number of occurrences of every character in q is less than or equal to that in s . ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; bool isPresent ( string s , string q ) { int freq [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) freq [ s [ i ] ] ++ ; for ( int i = 0 ; i < q . length ( ) ; i ++ ) { freq [ q [ i ] ] -- ; if ( freq [ q [ i ] ] < 0 ) return false ; } return true ; } int main ( ) { string s = " abctd " ; string q = " cat " ; if ( isPresent ( s , q ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimum reduce operations to convert a given string into a palindrome | CPP program to count minimum reduce operations to make a palindrome ; Returns count of minimum character reduce operations to make palindrome . ; Compare every character of first half with the corresponding character of second half and add difference to result . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countReduce ( string & str ) { int n = str . length ( ) ; int res = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) res += abs ( str [ i ] - str [ n - i - 1 ] ) ; return res ; } int main ( ) { string str = " abcd " ; cout << countReduce ( str ) ; return 0 ; }
Minimal operations to make a number magical | CPP program to make a number magical ; function to calculate the minimal changes ; maximum digits that can be changed ; nested loops to generate all 6 digit numbers ; counter to count the number of change required ; if first digit is equal ; if 2 nd digit is equal ; if 3 rd digit is equal ; if 4 th digit is equal ; if 5 th digit is equal ; if 6 th digit is equal ; checks if less then the previous calculate changes ; returns the answer ; driver program to test the above function ; number stored in string ; prints the minimum operations
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int calculate ( string s ) { int ans = 6 ; for ( int i = 0 ; i < 10 ; ++ i ) { for ( int j = 0 ; j < 10 ; ++ j ) { for ( int k = 0 ; k < 10 ; ++ k ) { for ( int l = 0 ; l < 10 ; ++ l ) { for ( int m = 0 ; m < 10 ; ++ m ) { for ( int n = 0 ; n < 10 ; ++ n ) { if ( i + j + k == l + m + n ) { int c = 0 ; if ( i != s [ 0 ] - '0' ) c ++ ; if ( j != s [ 1 ] - '0' ) c ++ ; if ( k != s [ 2 ] - '0' ) c ++ ; if ( l != s [ 3 ] - '0' ) c ++ ; if ( m != s [ 4 ] - '0' ) c ++ ; if ( n != s [ 5 ] - '0' ) c ++ ; if ( c < ans ) ans = c ; } } } } } } } return ans ; } int main ( ) { string s = "123456" ; cout << calculate ( s ) ; }
Check if a two character string can be made using given words | CPP code to check if a two character string can be made using given strings ; Function to check if str can be made using given words ; If str itself is present ; Match first character of str with second of word and vice versa ; If both characters found . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool makeAndCheckString ( vector < string > words , string str ) { int n = words . size ( ) ; bool first = false , second = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( words [ i ] == str ) return true ; if ( str [ 0 ] == words [ i ] [ 1 ] ) first = true ; if ( str [ 1 ] == words [ i ] [ 0 ] ) second = true ; if ( first && second ) return true ; } return false ; } int main ( ) { string str = " ya " ; vector < string > words = { " ah " , " oy " , " to " , " ha " } ; if ( makeAndCheckString ( words , str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Print N | C ++ program to print all N - bit binary ; Function to get the binary representation of the number N ; loop for each bit ; generate numbers in the range of ( 2 ^ N ) - 1 to 2 ^ ( N - 1 ) inclusive ; longest prefix check ; if counts of 1 is greater than counts of zero ; do sub - prefixes check ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; string getBinaryRep ( int N , int num_of_bits ) { string r = " " ; num_of_bits -- ; while ( num_of_bits >= 0 ) { if ( N & ( 1 << num_of_bits ) ) r . append ( "1" ) ; else r . append ( "0" ) ; num_of_bits -- ; } return r ; } vector < string > NBitBinary ( int N ) { vector < string > r ; int first = 1 << ( N - 1 ) ; int last = first * 2 ; for ( int i = last - 1 ; i >= first ; -- i ) { int zero_cnt = 0 ; int one_cnt = 0 ; int t = i ; int num_of_bits = 0 ; while ( t ) { if ( t & 1 ) one_cnt ++ ; else zero_cnt ++ ; num_of_bits ++ ; t = t >> 1 ; } if ( one_cnt >= zero_cnt ) { bool all_prefix_match = true ; int msk = ( 1 << num_of_bits ) - 2 ; int prefix_shift = 1 ; while ( msk ) { int prefix = ( msk & i ) >> prefix_shift ; int prefix_one_cnt = 0 ; int prefix_zero_cnt = 0 ; while ( prefix ) { if ( prefix & 1 ) prefix_one_cnt ++ ; else prefix_zero_cnt ++ ; prefix = prefix >> 1 ; } if ( prefix_zero_cnt > prefix_one_cnt ) { all_prefix_match = false ; break ; } prefix_shift ++ ; msk = msk & ( msk << 1 ) ; } if ( all_prefix_match ) { r . push_back ( getBinaryRep ( i , num_of_bits ) ) ; } } } return r ; } int main ( ) { int n = 4 ; vector < string > results = NBitBinary ( n ) ; for ( int i = 0 ; i < results . size ( ) ; ++ i ) cout << results [ i ] << " ▁ " ; cout << endl ; return 0 ; }
Find winner of an election where votes are represented as candidate names | C ++ ++ program to find winner in an election . ; We have four Candidates with name as ' John ' , ' Johnny ' , ' jamie ' , ' jackie ' . The votes in String array are as per the votes casted . Print the name of candidates received Max vote . ; Insert all votes in a hashmap ; Traverse through map to find the candidate with maximum votes . ; If there is a tie , pick lexicographically smaller . ; Driver code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; void findWinner ( vector < string > & votes ) { unordered_map < string , int > mapObj ; for ( auto & str : votes ) { mapObj [ str ] ++ ; } int maxValueInMap = 0 ; string winner ; for ( auto & entry : mapObj ) { string key = entry . first ; int val = entry . second ; if ( val > maxValueInMap ) { maxValueInMap = val ; winner = key ; } else if ( val == maxValueInMap && winner > key ) winner = key ; } cout << winner << endl ; } int main ( ) { vector < string > votes = { " john " , " johnny " , " jackie " , " johnny " , " john " , " jackie " , " jamie " , " jamie " , " john " , " johnny " , " jamie " , " johnny " , " john " } ; findWinner ( votes ) ; return 0 ; }
Luhn algorithm | C ++ program to implement Luhn algorithm ; Returns true if given card number is valid ; We add two digits to handle cases that make two digits after doubling ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkLuhn ( const string & cardNo ) { int nDigits = cardNo . length ( ) ; int nSum = 0 , isSecond = false ; for ( int i = nDigits - 1 ; i >= 0 ; i -- ) { int d = cardNo [ i ] - '0' ; if ( isSecond == true ) d = d * 2 ; nSum += d / 10 ; nSum += d % 10 ; isSecond = ! isSecond ; } return ( nSum % 10 == 0 ) ; } int main ( ) { string cardNo = "79927398713" ; if ( checkLuhn ( cardNo ) ) printf ( " This ▁ is ▁ a ▁ valid ▁ card " ) ; else printf ( " This ▁ is ▁ not ▁ a ▁ valid ▁ card " ) ; return 0 ; }
Distributing all balls without repetition | CPP program to find if its possible to distribute balls without repitiion ; function to find if its possible to distribute balls or not ; count array to count how many times each color has occurred ; increasing count of each color every time it appears ; to check if any color appears more than K times if it does we will print NO ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool distributingBalls ( int k , int n , string str ) { int a [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { a [ str [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( a [ i ] > k ) return false ; return true ; } int main ( ) { long long int n = 6 , k = 3 ; string str = " aacaab " ; if ( distributingBalls ( k , n , str ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Find substrings that contain all vowels | CPP program to find all substring that contain all vowels ; Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Outer loop picks starting character and inner loop picks ending character . ; If current character is not vowel , then no more result substrings possible starting from str [ i ] . ; If vowel , then we insert it in hash ; If all vowels are present in current substring ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } void FindSubstring ( string str ) { int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( isVowel ( str [ j ] ) == false ) break ; hash . insert ( str [ j ] ) ; if ( hash . size ( ) == 5 ) cout << str . substr ( i , j - i + 1 ) << " ▁ " ; } hash . clear ( ) ; } } int main ( ) { string str = " aeoibsddaeiouudb " ; FindSubstring ( str ) ; return 0 ; }
Find if an array contains a string with one mismatch | C ++ program to find if given string is present with one mismatch . ; If the array is empty ; If sizes are same ; If first mismatch ; Second mismatch ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < string > list , string s ) { int n = ( int ) list . size ( ) ; if ( n == 0 ) return false ; for ( int i = 0 ; i < n ; i ++ ) { if ( list [ i ] . size ( ) != s . size ( ) ) continue ; bool diff = false ; for ( int j = 0 ; j < ( int ) list [ i ] . size ( ) ; j ++ ) { if ( list [ i ] [ j ] != s [ j ] ) { if ( ! diff ) diff = true ; else { diff = false ; break ; } } } if ( diff ) return true ; } return false ; } int main ( ) { vector < string > s ; s . push_back ( " bana " ) ; s . push_back ( " apple " ) ; s . push_back ( " banacb " ) ; s . push_back ( " bonanza " ) ; s . push_back ( " banamf " ) ; cout << check ( s , " banana " ) ; return 0 ; }
Sentence Palindrome ( Palindrome after removing spaces , dots , . . etc ) | CPP program to find if a sentence is palindrome ; To check sentence is palindrome or not ; Lowercase string ; Compares character until they are equal ; If there is another symbol in left of sentence ; If there is another symbol in right of sentence ; If characters are equal ; If characters are not equal then sentence is not palindrome ; Returns true if sentence is palindrome ; Driver program to test sentencePalindrome ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool sentencePalindrome ( string str ) { int l = 0 , h = str . length ( ) - 1 ; for ( int i = 0 ; i <= h ; i ++ ) str [ i ] = tolower ( str [ i ] ) ; while ( l <= h ) { if ( ! ( str [ l ] >= ' a ' && str [ l ] <= ' z ' ) ) l ++ ; else if ( ! ( str [ h ] >= ' a ' && str [ h ] <= ' z ' ) ) h -- ; else if ( str [ l ] == str [ h ] ) l ++ , h -- ; else return false ; } return true ; } int main ( ) { string str = " Too ▁ hot ▁ to ▁ hoot . " ; if ( sentencePalindrome ( str ) ) cout << " Sentence ▁ is ▁ palindrome . " ; else cout << " Sentence ▁ is ▁ not ▁ palindrome . " ; return 0 ; }
Ways to remove one element from a binary string so that XOR becomes zero | C ++ program to count number of ways to remove an element so that XOR of remaining string becomes 0. ; Return number of ways in which XOR become ZERO by remove 1 element ; Counting number of 0 and 1 ; If count of ones is even then return count of zero else count of one ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorZero ( string str ) { int one_count = 0 , zero_count = 0 ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == '1' ) one_count ++ ; else zero_count ++ ; if ( one_count % 2 == 0 ) return zero_count ; return one_count ; } int main ( ) { string str = "11111" ; cout << xorZero ( str ) << endl ; return 0 ; }
Keyword Cipher | CPP program for encoding the string using classical cipher ; Function generates the encoded text ; This array represents the 26 letters of alphabets ; This loop inserts the keyword at the start of the encoded string ; To check whether the character is inserted earlier in the encoded string or not ; This loop inserts the remaining characters in the encoded string . ; Function that generates encodes ( cipher ) the message ; This loop ciphered the message . Spaces , special characters and numbers remain same . ; Driver code ; Hold the Keyword ; Function call to generate encoded text ; Message that need to encode ; Function call to print ciphered text
#include <bits/stdc++.h> NEW_LINE using namespace std ; string encoder ( string key ) { string encoded = " " ; bool arr [ 26 ] = { 0 } ; for ( int i = 0 ; i < key . size ( ) ; i ++ ) { if ( key [ i ] >= ' A ' && key [ i ] <= ' Z ' ) { if ( arr [ key [ i ] - 65 ] == 0 ) { encoded += key [ i ] ; arr [ key [ i ] - 65 ] = 1 ; } } else if ( key [ i ] >= ' a ' && key [ i ] <= ' z ' ) { if ( arr [ key [ i ] - 97 ] == 0 ) { encoded += key [ i ] - 32 ; arr [ key [ i ] - 97 ] = 1 ; } } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( arr [ i ] == 0 ) { arr [ i ] = 1 ; encoded += char ( i + 65 ) ; } } return encoded ; } string cipheredIt ( string msg , string encoded ) { string cipher = " " ; for ( int i = 0 ; i < msg . size ( ) ; i ++ ) { if ( msg [ i ] >= ' a ' && msg [ i ] <= ' z ' ) { int pos = msg [ i ] - 97 ; cipher += encoded [ pos ] ; } else if ( msg [ i ] >= ' A ' && msg [ i ] <= ' Z ' ) { int pos = msg [ i ] - 65 ; cipher += encoded [ pos ] ; } else { cipher += msg [ i ] ; } } return cipher ; } int main ( ) { string key ; key = " Computer " ; cout << " Keyword ▁ : ▁ " << key << endl ; string encoded = encoder ( key ) ; string message = " GeeksforGeeks " ; cout << " Message ▁ before ▁ Ciphering ▁ : ▁ " << message << endl ; cout << " Ciphered ▁ Text ▁ : ▁ " << cipheredIt ( message , encoded ) << endl ; return 0 ; }
Check if both halves of the string have same set of characters | C ++ program to check if it is possible to split string or not ; function to check if we can split string or not ; Counter array initialized with 0 ; Length of the string ; traverse till the middle element is reached ; First half ; Second half ; Checking if values are different set flag to 1 ; Driver program to test above function ; String to be checked
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool checkCorrectOrNot ( string s ) { int count [ MAX_CHAR ] = { 0 } ; int n = s . length ( ) ; if ( n == 1 ) return true ; for ( int i = 0 , j = n - 1 ; i < j ; i ++ , j -- ) { count [ s [ i ] - ' a ' ] ++ ; count [ s [ j ] - ' a ' ] -- ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( count [ i ] != 0 ) return false ; return true ; } int main ( ) { string s = " abab " ; if ( checkCorrectOrNot ( s ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Check if a string is Isogram or not | CPP code to check string is isogram or not ; function to check isogram ; loop to store count of chars and check if it is greater than 1 ; if count > 1 , return false ; Driver code ; checking str as isogram ; checking str2 as isogram
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check_isogram ( string str ) { int length = str . length ( ) ; int mapHash [ 26 ] = { 0 } ; for ( int i = 0 ; i < length ; i ++ ) { mapHash [ str [ i ] - ' a ' ] ++ ; if ( mapHash [ str [ i ] - ' a ' ] > 1 ) { return false ; } } return true ; } int main ( ) { string str = " geeks " ; string str2 = " computer " ; if ( check_isogram ( str ) ) { cout << " True " << endl ; } else { cout << " False " << endl ; } if ( check_isogram ( str2 ) ) { cout << " True " << endl ; } else { cout << " False " << endl ; } return 0 ; }
Check if a binary string has a 0 between 1 s or not | Set 1 ( General approach ) | C ++ program to check if a string is valid or not . ; Function returns 1 when string is valid else returns 0 ; Find first occurrence of 1 in s [ ] ; Find last occurrence of 1 in s [ ] ; Check if there is any 0 in range ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkString ( string s ) { int len = s . length ( ) ; int first = s . size ( ) + 1 ; for ( int i = 0 ; i < len ; i ++ ) { if ( s [ i ] == '1' ) { first = i ; break ; } } int last = 0 ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) { last = i ; break ; } } for ( int i = first ; i <= last ; i ++ ) if ( s [ i ] == '0' ) return false ; return true ; } int main ( ) { string s = "00011111111100000" ; checkString ( s ) ? cout << " VALID STRNEWLINE " : cout << " NOT ▁ VALID STRNEWLINE " ; return 0 ; }
Program to print all substrings of a given string | * C ++ program to print all possible * substrings of a given string * without checking for duplication . ; * Function to print all ( n * ( n + 1 ) ) / 2 * substrings of a given string s of length n . ; * Fix start index in outer loop . * Reveal new character in inner loop till end of string . * Print till - now - formed string . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printAllSubstrings ( string s , int n ) { for ( int i = 0 ; i < n ; i ++ ) { char temp [ n - i + 1 ] ; int tempindex = 0 ; for ( int j = i ; j < n ; j ++ ) { temp [ tempindex ++ ] = s [ j ] ; temp [ tempindex ] = ' \0' ; printf ( " % s STRNEWLINE " , temp ) ; } } } int main ( ) { string s = " Geeky " ; printAllSubstrings ( s , s . length ( ) ) ; return 0 ; }
Reverse a string preserving space positions | C ++ program to implement the above approach ; Initialize two pointers as two corners ; Move both pointers toward each other ; If character at start or end is space , ignore it ; If both are not spaces , do swap ; Driver code
#include <iostream> NEW_LINE using namespace std ; void preserveSpace ( string & str ) { int n = str . length ( ) ; int start = 0 ; int end = n - 1 ; while ( start < end ) { if ( str [ start ] == ' ▁ ' ) { start ++ ; continue ; } else if ( str [ end ] == ' ▁ ' ) { end -- ; continue ; } else { swap ( str [ start ] , str [ end ] ) ; start ++ ; end -- ; } } } int main ( ) { string str = " internship ▁ at ▁ geeks ▁ for ▁ geeks " ; preserveSpace ( str ) ; cout << str ; return 0 ; }
Put spaces between words starting with capital letters | C ++ program to put spaces between words starting with capital letters . ; Function to amend the sentence ; Traverse the string ; Convert to lowercase if its an uppercase character ; Print space before it if its an uppercase character ; Print the character ; if lowercase character then just print ; Driver code
#include <iostream> NEW_LINE using namespace std ; void amendSentence ( string str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { str [ i ] = str [ i ] + 32 ; if ( i != 0 ) cout << " ▁ " ; cout << str [ i ] ; } else cout << str [ i ] ; } } int main ( ) { string str = " BruceWayneIsBatman " ; amendSentence ( str ) ; return 0 ; }
C ++ program to concatenate a string given number of times | C ++ program to concatenate given string n number of times ; Function which return string by concatenating it . ; Copying given string to temporary string . ; s += s1 ; Concatenating strings ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <string> NEW_LINE using namespace std ; string repeat ( string s , int n ) { string s1 = s ; for ( int i = 1 ; i < n ; i ++ ) return s ; } int main ( ) { string s = " geeks " ; int n = 3 ; cout << repeat ( s , n ) << endl ; ; return 0 ; }
Number of distinct permutation a String can have | C ++ program to find number of distinct permutations of a string . ; Utility function to find factorial of n . ; Returns count of distinct permutations of str . ; finding frequency of all the lower case alphabet and storing them in array of integer ; finding factorial of number of appearances and multiplying them since they are repeating alphabets ; finding factorial of size of string and dividing it by factorial found after multiplying ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; int factorial ( int n ) { int fact = 1 ; for ( int i = 2 ; i <= n ; i ++ ) fact = fact * i ; return fact ; } int countDistinctPermutations ( string str ) { int length = str . length ( ) ; int freq [ MAX_CHAR ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < length ; i ++ ) if ( str [ i ] >= ' a ' ) freq [ str [ i ] - ' a ' ] ++ ; int fact = 1 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) fact = fact * factorial ( freq [ i ] ) ; return factorial ( length ) / fact ; } int main ( ) { string str = " fvvfhvgv " ; printf ( " % d " , countDistinctPermutations ( str ) ) ; return 0 ; }
Determine if a string has all Unique Characters | C ++ program to illustrate string with unique characters using brute force technique ; Assuming string can have characters a - z , this has 32 bits set to 0 ; if that bit is already set in checker , return false ; otherwise update and continue by setting that bit in the checker ; no duplicates encountered , return true ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool uniqueCharacters ( string str ) { int checker = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { int bitAtIndex = str [ i ] - ' a ' ; if ( ( checker & ( 1 << bitAtIndex ) ) > 0 ) { return false ; } checker = checker | ( 1 << bitAtIndex ) ; } return true ; } int main ( ) { string str = " geeksforgeeks " ; if ( uniqueCharacters ( str ) ) { cout << " The ▁ String ▁ " << str << " ▁ has ▁ all ▁ unique ▁ characters STRNEWLINE " ; } else { cout << " The ▁ String ▁ " << str << " ▁ has ▁ duplicate ▁ characters STRNEWLINE " ; } return 0 ; }
Alternate vowel and consonant string | C ++ implementation of alternate vowel and consonant string ; ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required alternate vowel and consonant string ; count vowels and update vowel string ; count consonants and update consonant string ; no such string can be formed ; remove first character of vowel string then create alternate string with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant string then create alternate string with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating string with consonant ; start creating string with vowel ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) return true ; return false ; } string createAltStr ( string str1 , string str2 , int start , int l ) { string finalStr = " " ; for ( int i = 0 , j = start ; j < l ; i ++ , j ++ ) finalStr = ( finalStr + str1 . at ( i ) ) + str2 . at ( j ) ; return finalStr ; } string findAltStr ( string str ) { int nv = 0 , nc = 0 ; string vstr = " " , cstr = " " ; int l = str . size ( ) ; for ( int i = 0 ; i < l ; i ++ ) { char ch = str . at ( i ) ; if ( isVowel ( ch ) ) { nv ++ ; vstr = vstr + ch ; } else { nc ++ ; cstr = cstr + ch ; } } if ( abs ( nv - nc ) >= 2 ) return " no ▁ such ▁ string " ; if ( nv > nc ) return ( vstr . at ( 0 ) + createAltStr ( cstr , vstr , 1 , nv ) ) ; if ( nc > nv ) return ( cstr . at ( 0 ) + createAltStr ( vstr , cstr , 1 , nc ) ) ; if ( cstr . at ( 0 ) < vstr . at ( 0 ) ) return createAltStr ( cstr , vstr , 0 , nv ) ; return createAltStr ( vstr , cstr , 0 , nc ) ; } int main ( ) { string str = " geeks " ; cout << findAltStr ( str ) ; return 0 ; }
Check whether K | CPP program to check if k - th bit of a given number is set or not ; Driver code
#include <iostream> NEW_LINE using namespace std ; void isKthBitSet ( int n , int k ) { if ( n & ( 1 << ( k - 1 ) ) ) cout << " SET " ; else cout << " NOT ▁ SET " ; } int main ( ) { int n = 5 , k = 1 ; isKthBitSet ( n , k ) ; return 0 ; }
Reverse string without using any temporary variable | Reversing a string using reverse ( ) ; Reverse str [ beign . . end ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { string str = " geeksforgeeks " ; reverse ( str . begin ( ) , str . end ( ) ) ; cout << str ; return 0 ; }
Recursive function to check if a string is palindrome | A recursive C ++ program to check whether a given number is palindrome or not ; A recursive function that check a str [ s . . e ] is palindrome or not . ; If there is only one character ; If first and last characters do not match ; If there are more than two characters , check if middle substring is also palindrome or not . ; An empty string is considered as palindrome ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalRec ( char str [ ] , int s , int e ) { if ( s == e ) return true ; if ( str [ s ] != str [ e ] ) return false ; if ( s < e + 1 ) return isPalRec ( str , s + 1 , e - 1 ) ; return true ; } bool isPalindrome ( char str [ ] ) { int n = strlen ( str ) ; if ( n == 0 ) return true ; return isPalRec ( str , 0 , n - 1 ) ; } int main ( ) { char str [ ] = " geeg " ; if ( isPalindrome ( str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count substrings with same first and last characters | Most efficient C ++ program to count all substrings with same first and last characters . ; assuming lower case only ; Calculating frequency of each character in the string . ; Computing result using counts ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; int countSubstringWithEqualEnds ( string s ) { int result = 0 ; int n = s . length ( ) ; int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ s [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) result += ( count [ i ] * ( count [ i ] + 1 ) / 2 ) ; return result ; } int main ( ) { string s ( " abcab " ) ; cout << countSubstringWithEqualEnds ( s ) ; return 0 ; }
Maximum consecutive repeating character in string | C ++ program to find the maximum consecutive repeating character in given string ; Returns the maximum repeating character in a given string ; Traverse string except last character ; If current character matches with next ; If doesn 't match, update result (if required) and reset count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char maxRepeating ( string str ) { int n = str . length ( ) ; int count = 0 ; char res = str [ 0 ] ; int cur_count = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n - 1 && str [ i ] == str [ i + 1 ] ) cur_count ++ ; else { if ( cur_count > count ) { count = cur_count ; res = str [ i ] ; } cur_count = 1 ; } } return res ; } int main ( ) { string str = " aaaabbaaccde " ; cout << maxRepeating ( str ) ; return 0 ; }
Queries on subsequence of string | C ++ program to answer subsequence queries for a given string . ; Precompute the position of each character from each position of String S ; Computing position of each character from each position of String S ; Print " Yes " if T is subsequence of S , else " No " ; Traversing the string T ; If next position is greater than length of S set flag to false . ; Setting position of next character ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define MAX 10000 NEW_LINE #define CHAR_SIZE 26 NEW_LINE using namespace std ; void precompute ( int mat [ MAX ] [ CHAR_SIZE ] , char str [ ] , int len ) { for ( int i = 0 ; i < CHAR_SIZE ; ++ i ) mat [ len ] [ i ] = len ; for ( int i = len - 1 ; i >= 0 ; -- i ) { for ( int j = 0 ; j < CHAR_SIZE ; ++ j ) mat [ i ] [ j ] = mat [ i + 1 ] [ j ] ; mat [ i ] [ str [ i ] - ' a ' ] = i ; } } bool query ( int mat [ MAX ] [ CHAR_SIZE ] , const char * str , int len ) { int pos = 0 ; for ( int i = 0 ; i < strlen ( str ) ; ++ i ) { if ( mat [ pos ] [ str [ i ] - ' a ' ] >= len ) return false ; else pos = mat [ pos ] [ str [ i ] - ' a ' ] + 1 ; } return true ; } int main ( ) { char S [ ] = " geeksforgeeks " ; int len = strlen ( S ) ; int mat [ MAX ] [ CHAR_SIZE ] ; precompute ( mat , S , len ) ; query ( mat , " gg " , len ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; query ( mat , " gro " , len ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; query ( mat , " gfg " , len ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; query ( mat , " orf " , len ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; }
Queries for characters in a repeated string | Queries for same characters in a repeated string ; Print whether index i and j have same element or not . ; Finding relative position of index i , j . ; Checking is element are same at index i , j . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void query ( char s [ ] , int i , int j ) { int n = strlen ( s ) ; i %= n ; j %= n ; ( s [ i ] == s [ j ] ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; } int main ( ) { char X [ ] = " geeksforgeeks " ; query ( X , 0 , 8 ) ; query ( X , 8 , 13 ) ; query ( X , 6 , 15 ) ; return 0 ; }
Count of character pairs at same distance as in English alphabets | A Simple C ++ program to find pairs with distance equal to English alphabet distance ; Function to count pairs ; Increment count if characters are at same distance ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( string str ) { int result = 0 ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( abs ( str [ i ] - str [ j ] ) == abs ( i - j ) ) result ++ ; return result ; } int main ( ) { string str = " geeksforgeeks " ; cout << countPairs ( str ) ; return 0 ; }
Longest common subsequence with permutations allowed | C ++ program to find LCS with permutations allowed ; Function to calculate longest string str1 -- > first string str2 -- > second string count1 [ ] -- > hash array to calculate frequency of characters in str1 count [ 2 ] -- > hash array to calculate frequency of characters in str2 result -- > resultant longest string whose permutations are sub - sequence of given two strings ; calculate frequency of characters ; Now traverse hash array ; append character ( ' a ' + i ) in resultant string ' result ' by min ( count1 [ i ] , count2i ] ) times ; Driver program to run the case
#include <bits/stdc++.h> NEW_LINE using namespace std ; void longestString ( string str1 , string str2 ) { int count1 [ 26 ] = { 0 } , count2 [ 26 ] = { 0 } ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) count1 [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < str2 . length ( ) ; i ++ ) count2 [ str2 [ i ] - ' a ' ] ++ ; string result ; for ( int i = 0 ; i < 26 ; i ++ ) for ( int j = 1 ; j <= min ( count1 [ i ] , count2 [ i ] ) ; j ++ ) result . push_back ( ' a ' + i ) ; cout << result ; } int main ( ) { string str1 = " geeks " , str2 = " cake " ; longestString ( str1 , str2 ) ; return 0 ; }
Check if string follows order of characters defined by a pattern or not | Set 1 | C ++ program check if characters in the input string follows the same order as determined by characters present in the given pattern ; Function to check if characters in the input string follows the same order as determined by characters present in the given pattern ; len stores length of the given pattern ; if length of pattern is more than length of input string , return false ; ; x , y are two adjacent characters in pattern ; find index of last occurrence of character x in the input string ; find index of first occurrence of character y in the input string ; return false if x or y are not present in the input string OR last occurrence of x is after the first occurrence of y in the input string ; return true if string matches the pattern ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool checkPattern ( string str , string pattern ) { int len = pattern . length ( ) ; if ( str . length ( ) < len ) return false ; for ( int i = 0 ; i < len - 1 ; i ++ ) { char x = pattern [ i ] ; char y = pattern [ i + 1 ] ; size_t last = str . find_last_of ( x ) ; size_t first = str . find_first_of ( y ) ; if ( last == string :: npos first == string :: npos last > first ) return false ; } return true ; } int main ( ) { string str = " engineers ▁ rock " ; string pattern = " gsr " ; cout << boolalpha << checkPattern ( str , pattern ) ; return 0 ; }
Calculate sum of all numbers present in a string | C ++ program to calculate sum of all numbers present in a string containing alphanumeric characters ; Function to calculate sum of all numbers present in a string containing alphanumeric characters ; A temporary string ; holds sum of all numbers present in the string ; read each character in input string ; if current character is a digit ; if current character is an alphabet ; increment sum by number found earlier ( if any ) ; reset temporary string to empty ; atoi ( temp . c_str ( ) ) takes care of trailing numbers ; Driver code ; input alphanumeric string ; Function call
#include <iostream> NEW_LINE using namespace std ; int findSum ( string str ) { string temp = " " ; int sum = 0 ; for ( char ch : str ) { if ( isdigit ( ch ) ) temp += ch ; else { sum += atoi ( temp . c_str ( ) ) ; temp = " " ; } } return sum + atoi ( temp . c_str ( ) ) ; } int main ( ) { string str = "12abc20yz68" ; cout << findSum ( str ) ; return 0 ; }
Count number of substrings with exactly k distinct characters | C ++ program to count number of substrings with exactly k distinct characters in a given string ; Function to count number of substrings with exactly k unique characters ; Initialize result ; To store count of characters from ' a ' to ' z ' ; Consider all substrings beginning with str [ i ] ; Initializing array with 0 ; Consider all substrings between str [ i . . j ] ; If this is a new character for this substring , increment dist_count . ; Increment count of current character ; If distinct character count becomes k , then increment result . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countkDist ( string str , int k ) { int n = str . length ( ) ; int res = 0 ; int cnt [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { int dist_count = 0 ; memset ( cnt , 0 , sizeof ( cnt ) ) ; for ( int j = i ; j < n ; j ++ ) { if ( cnt [ str [ j ] - ' a ' ] == 0 ) dist_count ++ ; cnt [ str [ j ] - ' a ' ] ++ ; if ( dist_count == k ) res ++ ; if ( dist_count > k ) break ; } } return res ; } int main ( ) { string str = " abcbaa " ; int k = 3 ; cout << " Total ▁ substrings ▁ with ▁ exactly ▁ " << k << " ▁ distinct ▁ characters ▁ : " << countkDist ( str , k ) << endl ; return 0 ; }
Lower case to upper case | C ++ program to convert a string to uppercase ; Converts a string to uppercase ; Driver code
#include <iostream> NEW_LINE using namespace std ; string to_upper ( string & in ) { for ( int i = 0 ; i < in . length ( ) ; i ++ ) if ( ' a ' <= in [ i ] <= ' z ' ) in [ i ] = in [ i ] - ' a ' + ' A ' ; return in ; } int main ( ) { string str = " geeksforgeeks " ; cout << to_upper ( str ) ; return 0 ; }
Longest Common Prefix using Character by Character Matching | A C ++ Program to find the longest common prefix ; A Function to find the string having the minimum length and returns that length ; A Function that returns the longest common prefix from the array of strings ; Our resultant string char current ; The current character ; Current character ( must be same in all strings to be a part of result ) ; Append to result ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinLength ( string arr [ ] , int n ) { int min = arr [ 0 ] . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] . length ( ) < min ) min = arr [ i ] . length ( ) ; return ( min ) ; } string commonPrefix ( string arr [ ] , int n ) { int minlen = findMinLength ( arr , n ) ; string result ; for ( int i = 0 ; i < minlen ; i ++ ) { current = arr [ 0 ] [ i ] ; for ( int j = 1 ; j < n ; j ++ ) if ( arr [ j ] [ i ] != current ) return result ; result . push_back ( current ) ; } return ( result ) ; } int main ( ) { string arr [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string ans = commonPrefix ( arr , n ) ; if ( ans . length ( ) ) cout << " The ▁ longest ▁ common ▁ prefix ▁ is ▁ " << ans ; else cout << " There ▁ is ▁ no ▁ common ▁ prefix " ; return ( 0 ) ; }
Print Concatenation of Zig | C ++ program to print string obtained by concatenation of different rows of Zig - Zag fashion ; Prints concatenation of all rows of str 's Zig-Zag fashion ; Corner Case ( Only one row ) ; Find length of string ; Create an array of strings for all n rows ; Initialize index for array of strings arr [ ] ; True if we are moving down in rows , else false ; Traverse through given string ; append current character to current row ; If last row is reached , change direction to ' up ' ; If 1 st row is reached , change direction to ' down ' ; If direction is down , increment , else decrement ; Print concatenation of all rows ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printZigZagConcat ( string str , int n ) { if ( n == 1 ) { cout << str ; return ; } int len = str . length ( ) ; string arr [ n ] ; int row = 0 ; bool down ; for ( int i = 0 ; i < len ; ++ i ) { arr [ row ] . push_back ( str [ i ] ) ; if ( row == n - 1 ) down = false ; else if ( row == 0 ) down = true ; ( down ) ? ( row ++ ) : ( row -- ) ; } for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] ; } int main ( ) { string str = " GEEKSFORGEEKS " ; int n = 3 ; printZigZagConcat ( str , n ) ; return 0 ; }
Check if two given strings are isomorphic to each other | C ++ program to check if two strings are isomorphic ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one corresponance ; To mark visited characters in str2 ; To store mapping of every character from str1 to that of str2 . Initialize all entries of map as - 1. ; Process all characters one by on ; If current character of str1 is seen first time in it . ; If current character of str2 is already seen , one to one mapping not possible ; Mark current character of str2 as visited ; Store mapping of current characters ; If this is not first appearance of current character in str1 , then check if previous appearance mapped to same character of str2 ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHARS 256 NEW_LINE bool areIsomorphic ( string str1 , string str2 ) { int m = str1 . length ( ) , n = str2 . length ( ) ; if ( m != n ) return false ; bool marked [ MAX_CHARS ] = { false } ; int map [ MAX_CHARS ] ; memset ( map , -1 , sizeof ( map ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( map [ str1 [ i ] ] == -1 ) { if ( marked [ str2 [ i ] ] == true ) return false ; marked [ str2 [ i ] ] = true ; map [ str1 [ i ] ] = str2 [ i ] ; } else if ( map [ str1 [ i ] ] != str2 [ i ] ) return false ; } return true ; } int main ( ) { cout << areIsomorphic ( " aab " , " xxy " ) << endl ; cout << areIsomorphic ( " aab " , " xyz " ) << endl ; return 0 ; }
Check if two given strings are isomorphic to each other | C ++ program for the above approach ; This function returns true if str1 and str2 are isomorphic ; Length of both strings must be same for one to one correspondence ; For counting the previous appearances of character in both the strings ; Process all characters one by one ; For string to be isomorphic the previous counts of appearances of current character in both string must be same if it is not same we return false . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHARS 26 NEW_LINE bool areIsomorphic ( string str1 , string str2 ) { int n = str1 . length ( ) , m = str2 . length ( ) ; if ( n != m ) return false ; int count [ MAX_CHARS ] = { 0 } ; int dcount [ MAX_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { count [ str1 [ i ] - ' a ' ] ++ ; dcount [ str2 [ i ] - ' a ' ] ++ ; if ( count [ str1 [ i ] - ' a ' ] != dcount [ str2 [ i ] - ' a ' ] ) return false ; } return true ; } int main ( ) { cout << areIsomorphic ( " aab " , " xxy " ) << endl ; cout << areIsomorphic ( " aab " , " xyz " ) << endl ; return 0 ; }
Minimum insertions to form shortest palindrome | C ++ program to find minimum number of insertions on left side to form a palindrome . ; Returns true if a string str [ st . . end ] is palindrome ; Returns count of insertions on left side to make str [ ] a palindrome ; Find the largest prefix of given string that is palindrome . ; Characters after the palindromic prefix must be added at the beginning also to make the complete string palindrome ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalin ( char str [ ] , int st , int end ) { while ( st < end ) { if ( str [ st ] != str [ end ] ) return false ; st ++ ; end -- ; } return true ; } int findMinInsert ( char str [ ] , int n ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( isPalin ( str , 0 , i ) ) return ( n - i - 1 ) ; } } int main ( ) { char Input [ ] = " JAVA " ; printf ( " % d " , findMinInsert ( Input , strlen ( Input ) ) ) ; return 0 ; }
Remove repeated digits in a given number | C ++ program to remove repeated digits ; Store first digits as previous digit ; Initialize power ; Iterate through all digits of n , note that the digits are processed from least significant digit to most significant digit . ; Store current digit ; Add the current digit to the beginning of result ; Update previous result and power ; Remove last digit from n ; Driver program
#include <iostream> NEW_LINE using namespace std ; long int removeRecur ( long int n ) { int prev_digit = n % 10 ; long int pow = 10 ; long int res = prev_digit ; while ( n ) { int curr_digit = n % 10 ; if ( curr_digit != prev_digit ) { res += curr_digit * pow ; prev_digit = curr_digit ; pow *= 10 ; } n = n / 10 ; } return res ; } int main ( ) { long int n = 12224 ; cout << removeRecur ( n ) ; return 0 ; }
Remove " b " and " ac " from a given string | A C ++ program to remove " b " and ' ac ' from input string ; The main function that removes occurrences of " a " and " bc " in input string ; previous character ; current character ; check if current and next character forms ac ; if current character is b ; if current char is ' c ▁ & & ▁ last ▁ char ▁ in ▁ output ▁ ▁ is ▁ ' a ' so delete both ; else copy curr char to output string ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void stringFilter ( char * str ) { int n = strlen ( str ) ; int i = -1 ; int j = 0 ; while ( j < n ) { if ( j < n - 1 && str [ j ] == ' a ' && str [ j + 1 ] == ' c ' ) j += 2 ; else if ( str [ j ] == ' b ' ) j ++ ; else if ( i >= 0 && str [ j ] == ' c ' && str [ i ] == ' a ' ) i -- , j ++ ; else str [ ++ i ] = str [ j ++ ] ; } str [ ++ i ] = ' \0' ; } int main ( ) { char str1 [ ] = " ad " ; cout << " Input ▁ = > ▁ " << str1 << " Output = > " stringFilter ( str1 ) ; cout << str1 << endl << endl ; char str2 [ ] = " acbac " ; cout << " Input ▁ = > ▁ " << str2 << " Output = > " stringFilter ( str2 ) ; cout << str2 << endl << endl ; char str3 [ ] = " aaac " ; cout << " Input ▁ = > ▁ " << str3 << " Output = > " stringFilter ( str3 ) ; cout << str3 << endl << endl ; char str4 [ ] = " react " ; cout << " Input ▁ = > ▁ " << str4 << " Output = > " stringFilter ( str4 ) ; cout << str4 << endl << endl ; char str5 [ ] = " aa " ; cout << " Input ▁ = > ▁ " << str5 << " Output = > " stringFilter ( str5 ) ; cout << str5 << endl << endl ; char str6 [ ] = " ababaac " ; cout << " Input ▁ = > ▁ " << str6 << " Output = > " stringFilter ( str6 ) ; cout << str6 << endl << endl ; char str [ ] = " abc " ; cout << " Input ▁ = > ▁ " << str << " Output = > " stringFilter ( str ) ; cout << str << endl << endl ; return 0 ; }
Write your own atoi ( ) | A simple C ++ program for implementation of atoi ; if whitespaces then ignore . ; sign of number ; checking for valid input ; handling overflow test case ; Driver Code ; Functional Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int myAtoi ( const char * str ) { int sign = 1 , base = 0 , i = 0 ; while ( str [ i ] == ' ▁ ' ) { i ++ ; } if ( str [ i ] == ' - ' str [ i ] == ' + ' ) { sign = 1 - 2 * ( str [ i ++ ] == ' - ' ) ; } while ( str [ i ] >= '0' && str [ i ] <= '9' ) { if ( base > INT_MAX / 10 || ( base == INT_MAX / 10 && str [ i ] - '0' > 7 ) ) { if ( sign == 1 ) return INT_MAX ; else return INT_MIN ; } base = 10 * base + ( str [ i ++ ] - '0' ) ; } return base * sign ; } int main ( ) { char str [ ] = " ▁ - 123" ; int val = myAtoi ( str ) ; cout << " ▁ " << val ; return 0 ; }
Check whether two strings are anagram of each other | C ++ program to check if two strings are anagrams of each other ; function to check if two strings are anagrams of each other ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE bool areAnagram ( char * str1 , char * str2 ) { int count [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count [ str1 [ i ] ] ++ ; count [ str2 [ i ] ] -- ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] ) return false ; return true ; } int main ( ) { char str1 [ ] = " geeksforgeeks " ; char str2 [ ] = " forgeeksgeeks " ; if ( areAnagram ( str1 , str2 ) ) cout << " The ▁ two ▁ strings ▁ are ▁ anagram ▁ of ▁ each ▁ other " ; else cout << " The ▁ two ▁ strings ▁ are ▁ not ▁ anagram ▁ of ▁ each ▁ " " other " ; return 0 ; }
Length of the longest substring without repeating characters | C ++ program to find the length of the longest substring without repeating characters ; This functionr eturns true if all characters in str [ i . . j ] are distinct , otherwise returns false ; Note : Default values in visited are false ; Returns length of the longest substring with all distinct characters . ; result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areDistinct ( string str , int i , int j ) { vector < bool > visited ( 26 ) ; for ( int k = i ; k <= j ; k ++ ) { if ( visited [ str [ k ] - ' a ' ] == true ) return false ; visited [ str [ k ] - ' a ' ] = true ; } return true ; } int longestUniqueSubsttr ( string str ) { int n = str . size ( ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i ; j < n ; j ++ ) if ( areDistinct ( str , i , j ) ) res = max ( res , j - i + 1 ) ; return res ; } int main ( ) { string str = " geeksforgeeks " ; cout << " The ▁ input ▁ string ▁ is ▁ " << str << endl ; int len = longestUniqueSubsttr ( str ) ; cout << " The ▁ length ▁ of ▁ the ▁ longest ▁ non - repeating ▁ " " character ▁ substring ▁ is ▁ " << len ; return 0 ; }
Given a string , find its first non | CPP program to find first non - repeating character ; this function return the index of first non - repeating character if found , or else it returns - 1 ; initializing all elements to - 1 ; sets all repeating characters to - 2 and non - repeating characters contain the index where they occur ; If this character is not - 1 or - 2 then it means that this character occurred only once so find the min index of all characters that occur only once , that 's our first index ; if res remains INT_MAX , it means there are no characters that repeat only once or the string is empty
# include <iostream> NEW_LINE # include <climits> NEW_LINE using namespace std ; int firstNonRepeating ( string str ) { int fi [ 256 ] ; for ( int i = 0 ; i < 256 ; i ++ ) fi [ i ] = -1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( fi [ str [ i ] ] == -1 ) { fi [ str [ i ] ] = i ; } else { fi [ str [ i ] ] = -2 ; } } int res = INT_MAX ; for ( int i = 0 ; i < 256 ; i ++ ) { if ( fi [ i ] >= 0 ) res = min ( res , fi [ i ] ) ; } if ( res == INT_MAX ) return -1 ; else return res ; } int main ( ) { string str ; str = " geeksforgeeks " ; int firstIndex = firstNonRepeating ( str ) ; if ( firstIndex == -1 ) cout << " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ string ▁ is ▁ empty " ; else cout << " First ▁ non - repeating ▁ character ▁ is ▁ " << str [ firstIndex ] ; return 0 ; }
Remove duplicates from a given string | C ++ program to create a unique string ; Function to make the string unique ; loop to traverse the string and check for repeating chars using IndexOf ( ) method in Java ; character at i 'th index of s ; If c is present in str , it returns the index of c , else it returns npos ; Adding c to str if npos is returned ; Driver code ; Input string with repeating chars
#include <bits/stdc++.h> NEW_LINE using namespace std ; string unique ( string s ) { string str ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = s [ i ] ; auto found = str . find ( c ) ; if ( found == std :: string :: npos ) { str += c ; } } return str ; } int main ( ) { string s = " geeksforgeeks " ; cout << unique ( s ) << endl ; }
Sum of all subsets whose sum is a Perfect Number from a given array | C ++ program for the above approach ; Function to check is a given number is a perfect number or not ; Stores the sum of its divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find sum of all subsets from an array whose sum is a perfect number ; Print the current subset sum if it is a perfect number ; Check if sum is a perfect number or not ; Calculate sum of the subset including arr [ l ] ; Calculate sum of the subset excluding arr [ l ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPerfect ( int x ) { int sum_div = 1 ; for ( int i = 2 ; i <= x / 2 ; ++ i ) { if ( x % i == 0 ) { sum_div += i ; } } if ( sum_div == x ) { return 1 ; } else return 0 ; } void subsetSum ( int arr [ ] , int l , int r , int sum = 0 ) { if ( l > r ) { if ( isPerfect ( sum ) ) { cout << sum << " ▁ " ; } return ; } subsetSum ( arr , l + 1 , r , sum + arr [ l ] ) ; subsetSum ( arr , l + 1 , r , sum ) ; } int main ( ) { int arr [ ] = { 5 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; subsetSum ( arr , 0 , N - 1 ) ; return 0 ; }
Print all possible ways to split an array into K subsets | C ++ program for the above approach ; Utility function to find all possible ways to split array into K subsets ; If count of elements in K subsets are greater than or equal to N ; If count of subsets formed is equal to K ; Print K subsets by splitting array into K subsets ; Print current subset ; If current element is the last element of the subset ; Otherwise ; If any subset is occupied , then push the element in that first ; Recursively do the same for remaining elements ; Backtrack ; Otherwise , push it in an empty subset and increase the subset count by 1 ; Break to avoid the case of going in other empty subsets , if available , and forming the same combination ; Function to to find all possible ways to split array into K subsets ; Stores K subset by splitting array into K subsets ; Size of each subset must be less than the number of elements ; Driver Code ; Given array ; Given K ; Size of the array ; Prints all possible splits into subsets
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PartitionSub ( int arr [ ] , int i , int N , int K , int nos , vector < vector < int > > & v ) { if ( i >= N ) { if ( nos == K ) { for ( int x = 0 ; x < v . size ( ) ; x ++ ) { cout << " { ▁ " ; for ( int y = 0 ; y < v [ x ] . size ( ) ; y ++ ) { cout << v [ x ] [ y ] ; if ( y == v [ x ] . size ( ) - 1 ) { cout << " ▁ " ; } else { cout << " , ▁ " ; } } if ( x == v . size ( ) - 1 ) { cout << " } " ; } else { cout << " } , ▁ " ; } } cout << endl ; } return ; } for ( int j = 0 ; j < K ; j ++ ) { if ( v [ j ] . size ( ) > 0 ) { v [ j ] . push_back ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos , v ) ; v [ j ] . pop_back ( ) ; } else { v [ j ] . push_back ( arr [ i ] ) ; PartitionSub ( arr , i + 1 , N , K , nos + 1 , v ) ; v [ j ] . pop_back ( ) ; break ; } } } void partKSubsets ( int arr [ ] , int N , int K ) { vector < vector < int > > v ( K ) ; if ( K == 0 K > N ) { cout << " Not ▁ Possible " << endl ; } else { cout << " The ▁ Subset ▁ Combinations ▁ are : ▁ " << endl ; PartitionSub ( arr , 0 , N , K , 0 , v ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; partKSubsets ( arr , N , K ) ; }
Count the number of Prime Cliques in an undirected graph | C ++ implementation to Count the number of Prime Cliques in an undirected graph ; Stores the vertices ; Graph ; Degree of the vertices ; To store the count of prime cliques ; Function to create Sieve to check primes ; false here indicates that it is not prime ; Condition if prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to check if the given set of vertices in store array is a clique or not ; Run a loop for all set of edges ; If any edge is missing ; Function to find the count of all the cliques having prime size ; Check if any vertices from i + 1 can be inserted ; Add the vertex to store ; If the graph is not a clique of size k then it cannot be a clique by adding another edge ; increase the count of prime cliques if the size of current clique is prime ; Check if another edge can be added ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; int store [ MAX ] , n ; int graph [ MAX ] [ MAX ] ; int d [ MAX ] ; int ans ; void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } bool is_clique ( int b ) { for ( int i = 1 ; i < b ; i ++ ) { for ( int j = i + 1 ; j < b ; j ++ ) if ( graph [ store [ i ] ] [ store [ j ] ] == 0 ) return false ; } return true ; } void primeCliques ( int i , int l , bool prime [ ] ) { for ( int j = i + 1 ; j <= n ; j ++ ) { store [ l ] = j ; if ( is_clique ( l + 1 ) ) { if ( prime [ l ] ) ans ++ ; primeCliques ( j , l + 1 , prime ) ; } } } int main ( ) { int edges [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 1 } , { 4 , 3 } , { 4 , 5 } , { 5 , 3 } } ; int size = sizeof ( edges ) / sizeof ( edges [ 0 ] ) ; n = 5 ; bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , n + 1 ) ; for ( int i = 0 ; i < size ; i ++ ) { graph [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = 1 ; graph [ edges [ i ] [ 1 ] ] [ edges [ i ] [ 0 ] ] = 1 ; d [ edges [ i ] [ 0 ] ] ++ ; d [ edges [ i ] [ 1 ] ] ++ ; } ans = 0 ; primeCliques ( 0 , 1 , prime ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Construct a Doubly linked linked list from 2D Matrix | C ++ program to construct a Doubly linked linked list from 2D Matrix ; define dimension of matrix ; struct node of doubly linked list with four pointer next , prev , up , down ; function to create a new node ; function to construct the doubly linked list ; Create Node with value contain in matrix at index ( i , j ) ; Assign address of curr into the prev pointer of temp ; Assign address of curr into the up pointer of temp ; Recursive call for next pointer ; Recursive call for down pointer ; Return newly constructed node whose all four node connected at it 's appropriate position ; Function to construct the doubly linked list ; function call for construct the doubly linked list ; function for displaying doubly linked list data ; pointer to move right ; pointer to move down ; loop till node -> down is not NULL ; loop till node -> right is not NULL ; driver code ; initialise matrix
#include <iostream> NEW_LINE using namespace std ; #define dim 3 NEW_LINE struct Node { int data ; Node * next ; Node * prev ; Node * up ; Node * down ; } ; Node * createNode ( int data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> next = NULL ; temp -> prev = NULL ; temp -> up = NULL ; temp -> down = NULL ; return temp ; } Node * constructDoublyListUtil ( int mtrx [ ] [ dim ] , int i , int j , Node * curr ) { if ( i >= dim j >= dim ) { return NULL ; } Node * temp = createNode ( mtrx [ i ] [ j ] ) ; temp -> prev = curr ; temp -> up = curr ; temp -> next = constructDoublyListUtil ( mtrx , i , j + 1 , temp ) ; temp -> down = constructDoublyListUtil ( mtrx , i + 1 , j , temp ) ; return temp ; } Node * constructDoublyList ( int mtrx [ ] [ dim ] ) { return constructDoublyListUtil ( mtrx , 0 , 0 , NULL ) ; } void display ( Node * head ) { Node * rPtr ; Node * dPtr = head ; while ( dPtr ) { rPtr = dPtr ; while ( rPtr ) { cout << rPtr -> data << " ▁ " ; rPtr = rPtr -> next ; } cout << " STRNEWLINE " ; dPtr = dPtr -> down ; } } int main ( ) { int mtrx [ dim ] [ dim ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; Node * list = constructDoublyList ( mtrx ) ; display ( list ) ; return 0 ; }
Count of exponential paths in a Binary Tree | C ++ program to find the count exponential paths in Binary Tree ; A Tree node ; Function to create a new node ; function to find x ; Take log10 of n ; Log ( n ) with base i ; Raising i to the power p ; function To check whether the given node equals to x ^ y for some y > 0 ; Take logx ( n ) with base x ; Utility function to count the exponent path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is not a number of pow ( x , y ) ; Increment count when encounter leaf node ; Left recursive call save the value of count ; Right recursive call and return value of count ; function to count exponential paths ; Driver Code ; create Tree ; retrieve the value of x ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int find_x ( int n ) { if ( n == 1 ) return 1 ; double num , den , p ; num = log10 ( n ) ; int x , no ; for ( int i = 2 ; i <= n ; i ++ ) { den = log10 ( i ) ; p = num / den ; no = ( int ) ( pow ( i , int ( p ) ) ) ; if ( abs ( no - n ) < 1e-6 ) { x = i ; break ; } } return x ; } bool is_key ( int n , int x ) { double p ; p = log10 ( n ) / log10 ( x ) ; int no = ( int ) ( pow ( x , int ( p ) ) ) ; if ( n == no ) return true ; return false ; } int evenPaths ( struct Node * node , int count , int x ) { if ( node == NULL || ! is_key ( node -> key , x ) ) { return count ; } if ( ! node -> left && ! node -> right ) { count ++ ; } count = evenPaths ( node -> left , count , x ) ; return evenPaths ( node -> right , count , x ) ; } int countExpPaths ( struct Node * node , int x ) { return evenPaths ( node , 0 , x ) ; } int main ( ) { Node * root = newNode ( 27 ) ; root -> left = newNode ( 9 ) ; root -> right = newNode ( 81 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 10 ) ; root -> right -> left = newNode ( 70 ) ; root -> right -> right = newNode ( 243 ) ; root -> right -> right -> left = newNode ( 81 ) ; root -> right -> right -> right = newNode ( 909 ) ; int x = find_x ( root -> key ) ; cout << countExpPaths ( root , x ) ; return 0 ; }
Number of pairs such that path between pairs has the two vertices A and B | C ++ program to find the number of pairs such that the path between every pair contains two given vertices ; Function to perform DFS on the given graph by fixing the a vertex ; To mark a particular vertex as visited ; Variable to store the count of the vertices which can be reached from a ; Performing the DFS by iterating over the visited array ; If the vertex is not visited and removing the vertex b ; Function to return the number of pairs such that path between any two pairs consists the given two vertices A and B ; Initializing the visited array and assigning it with 0 's ; Initially , the count of vertices is 0 ; Performing DFS by removing the vertex B ; Count the vertices which cannot be reached after removing the vertex B ; Again reinitializing the visited array ; Setting the count of vertices to 0 to perform the DFS again ; Performing the DFS by removing the vertex A ; Count the vertices which cannot be reached after removing the vertex A ; Multiplying both the vertices set ; Driver code ; Loop to store the graph
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1000001 ; int c , n , m , a , b ; void dfs ( int a , int b , vector < int > v [ ] , int vis [ ] ) { vis [ a ] = 1 ; c ++ ; for ( auto i : v [ a ] ) { if ( ! vis [ i ] && i != b ) dfs ( i , b , v , vis ) ; } } void Calculate ( vector < int > v [ ] ) { int vis [ n + 1 ] ; memset ( vis , 0 , sizeof ( vis ) ) ; c = 0 ; dfs ( a , b , v , vis ) ; int ans1 = n - c - 1 ; memset ( vis , 0 , sizeof ( vis ) ) ; c = 0 ; dfs ( b , a , v , vis ) ; int ans2 = n - c - 1 ; cout << ans1 * ans2 << " STRNEWLINE " ; } int main ( ) { n = 7 , m = 7 , a = 3 , b = 5 ; int edges [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } , { 4 , 5 } , { 5 , 6 } , { 6 , 7 } , { 7 , 5 } } ; vector < int > v [ n + 1 ] ; for ( int i = 0 ; i < m ; i ++ ) { v [ edges [ i ] [ 0 ] ] . push_back ( edges [ i ] [ 1 ] ) ; v [ edges [ i ] [ 1 ] ] . push_back ( edges [ i ] [ 0 ] ) ; } Calculate ( v ) ; return 0 ; }
Travelling Salesman Problem implementation using BackTracking | C ++ implementation of the approach ; Function to find the minimum weight Hamiltonian Cycle ; If last node is reached and it has a link to the starting node i . e the source then keep the minimum value out of the total cost of traversal and " ans " Finally return to check for more possible values ; BACKTRACKING STEP Loop to traverse the adjacency list of currPos node and increasing the count by 1 and cost by graph [ currPos ] [ i ] value ; Mark as visited ; Mark ith node as unvisited ; Driver code ; n is the number of nodes i . e . V ; Boolean array to check if a node has been visited or not ; Mark 0 th node as visited ; Find the minimum weight Hamiltonian Cycle ; ans is the minimum weight Hamiltonian Cycle
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 4 NEW_LINE void tsp ( int graph [ ] [ V ] , vector < bool > & v , int currPos , int n , int count , int cost , int & ans ) { if ( count == n && graph [ currPos ] [ 0 ] ) { ans = min ( ans , cost + graph [ currPos ] [ 0 ] ) ; return ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ! v [ i ] && graph [ currPos ] [ i ] ) { v [ i ] = true ; tsp ( graph , v , i , n , count + 1 , cost + graph [ currPos ] [ i ] , ans ) ; v [ i ] = false ; } } } ; int main ( ) { int n = 4 ; int graph [ ] [ V ] = { { 0 , 10 , 15 , 20 } , { 10 , 0 , 35 , 25 } , { 15 , 35 , 0 , 30 } , { 20 , 25 , 30 , 0 } } ; vector < bool > v ( n ) ; for ( int i = 0 ; i < n ; i ++ ) v [ i ] = false ; v [ 0 ] = true ; int ans = INT_MAX ; tsp ( graph , v , 0 , n , 1 , 0 , ans ) ; cout << ans ; return 0 ; }
Generate all the binary strings of N bits | C ++ implementation of the above approach : ; Function to print the output ; Function to generate all binary strings ; First assign "0" at ith position and try for all other permutations for remaining positions ; And then assign "1" at ith position and try for all other permutations for remaining positions ; Driver Code ; Print all binary strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printTheArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " ▁ " ; } cout << endl ; } void generateAllBinaryStrings ( int n , int arr [ ] , int i ) { if ( i == n ) { printTheArray ( arr , n ) ; return ; } arr [ i ] = 0 ; generateAllBinaryStrings ( n , arr , i + 1 ) ; arr [ i ] = 1 ; generateAllBinaryStrings ( n , arr , i + 1 ) ; } int main ( ) { int n = 4 ; int arr [ n ] ; generateAllBinaryStrings ( n , arr , 0 ) ; return 0 ; }
Print all the combinations of a string in lexicographical order | C ++ program to find all combinations of a string in lexicographical order ; function to print string ; Method to found all combination of string it is based in tree ; return if level is equal size of string ; if occurrence of char is 0 then skip the iteration of loop ; decrease the char occurrence by 1 ; store the char in result ; print the string till level ; call the function from level + 1 ; backtracking ; declare the map for store each char with occurrence ; initialize the input array with all unique char ; initialize the count array with occurrence the unique char ; temporary char array for store the result ; store the element of input array ; store the element of count array ; size of map ( no of unique char ) ; size of original string ; call function for print string combination ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printResult ( char * result , int len ) { for ( int i = 0 ; i <= len ; i ++ ) cout << result [ i ] ; cout << endl ; } void stringCombination ( char result [ ] , char str [ ] , int count [ ] , int level , int size , int length ) { if ( level == size ) return ; for ( int i = 0 ; i < length ; i ++ ) { if ( count [ i ] == 0 ) continue ; count [ i ] -- ; result [ level ] = str [ i ] ; printResult ( result , level ) ; stringCombination ( result , str , count , level + 1 , size , length ) ; count [ i ] ++ ; } } void combination ( string str ) { map < char , int > mp ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( mp . find ( str [ i ] ) != mp . end ( ) ) mp [ str [ i ] ] = mp [ str [ i ] ] + 1 ; else mp [ str [ i ] ] = 1 ; } char * input = new char [ mp . size ( ) ] ; int * count = new int [ mp . size ( ) ] ; char * result = new char [ str . size ( ) ] ; map < char , int > :: iterator it = mp . begin ( ) ; int i = 0 ; for ( it ; it != mp . end ( ) ; it ++ ) { input [ i ] = it -> first ; count [ i ] = it -> second ; i ++ ; } int length = mp . size ( ) ; int size = str . size ( ) ; stringCombination ( result , input , count , 0 , size , length ) ; } int main ( ) { string str = " ABC " ; combination ( str ) ; return 0 ; }
Combinations where every element appears twice and distance between appearances is equal to the value | C ++ program to find all combinations where every element appears twice and distance between appearances is equal to the value ; Find all combinations that satisfies given constraints ; if all elements are filled , print the solution ; try all possible combinations for element elem ; if position i and ( i + elem + 1 ) are not occupied in the vector ; place elem at position i and ( i + elem + 1 ) ; recurse for next element ; backtrack ( remove elem from position i and ( i + elem + 1 ) ) ; create a vector of double the size of given number with ; all its elements initialized by 1 ; start from element 1 ; Driver code ; given number
#include <bits/stdc++.h> NEW_LINE using namespace std ; void allCombinationsRec ( vector < int > & arr , int elem , int n ) { if ( elem > n ) { for ( int i : arr ) cout << i << " ▁ " ; cout << endl ; return ; } for ( int i = 0 ; i < 2 * n ; i ++ ) { if ( arr [ i ] == -1 && ( i + elem + 1 ) < 2 * n && arr [ i + elem + 1 ] == -1 ) { arr [ i ] = elem ; arr [ i + elem + 1 ] = elem ; allCombinationsRec ( arr , elem + 1 , n ) ; arr [ i ] = -1 ; arr [ i + elem + 1 ] = -1 ; } } } void allCombinations ( int n ) { vector < int > arr ( 2 * n , -1 ) ; int elem = 1 ; allCombinationsRec ( arr , elem , n ) ; } int main ( ) { int n = 3 ; allCombinations ( n ) ; return 0 ; }
Warnsdorff 's algorithm for Knight’s tour problem | C ++ program to for Kinight ' s ▁ tour ▁ problem ▁ using ▁ Warnsdorff ' s algorithm ; Move pattern on basis of the change of x coordinates and y coordinates respectively ; function restricts the knight to remain within the 8 x8 chessboard ; Checks whether a square is valid and empty or not ; Returns the number of empty squares adjacent to ( x , y ) ; Picks next point using Warnsdorff 's heuristic. Returns false if it is not possible to pick next point. ; Try all N adjacent of ( * x , * y ) starting from a random adjacent . Find the adjacent with minimum degree . ; IF we could not find a next cell ; Store coordinates of next point ; Mark next move ; Update next point ; displays the chessboard with all the legal knight 's moves ; If the knight ends on a square that is one knight 's move from the beginning square, then tour is closed ; Generates the legal moves using warnsdorff 's heuristics. Returns false if not possible ; Filling up the chessboard matrix with - 1 's ; Randome initial position ; Current points are same as initial points ; Keep picking next points using Warnsdorff 's heuristic ; Check if tour is closed ( Can end at starting point ) ; Driver code ; While we don 't get a solution
#include <bits/stdc++.h> NEW_LINE #define N 8 NEW_LINE static int cx [ N ] = { 1 , 1 , 2 , 2 , -1 , -1 , -2 , -2 } ; static int cy [ N ] = { 2 , -2 , 1 , -1 , 2 , -2 , 1 , -1 } ; bool limits ( int x , int y ) { return ( ( x >= 0 && y >= 0 ) && ( x < N && y < N ) ) ; } bool isempty ( int a [ ] , int x , int y ) { return ( limits ( x , y ) ) && ( a [ y * N + x ] < 0 ) ; } int getDegree ( int a [ ] , int x , int y ) { int count = 0 ; for ( int i = 0 ; i < N ; ++ i ) if ( isempty ( a , ( x + cx [ i ] ) , ( y + cy [ i ] ) ) ) count ++ ; return count ; } bool nextMove ( int a [ ] , int * x , int * y ) { int min_deg_idx = -1 , c , min_deg = ( N + 1 ) , nx , ny ; int start = rand ( ) % N ; for ( int count = 0 ; count < N ; ++ count ) { int i = ( start + count ) % N ; nx = * x + cx [ i ] ; ny = * y + cy [ i ] ; if ( ( isempty ( a , nx , ny ) ) & & ( c = getDegree ( a , nx , ny ) ) < min_deg ) { min_deg_idx = i ; min_deg = c ; } } if ( min_deg_idx == -1 ) return false ; nx = * x + cx [ min_deg_idx ] ; ny = * y + cy [ min_deg_idx ] ; a [ ny * N + nx ] = a [ ( * y ) * N + ( * x ) ] + 1 ; * x = nx ; * y = ny ; return true ; } void print ( int a [ ] ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) printf ( " % d TABSYMBOL " , a [ j * N + i ] ) ; printf ( " STRNEWLINE " ) ; } } bool neighbour ( int x , int y , int xx , int yy ) { for ( int i = 0 ; i < N ; ++ i ) if ( ( ( x + cx [ i ] ) == xx ) && ( ( y + cy [ i ] ) == yy ) ) return true ; return false ; } bool findClosedTour ( ) { int a [ N * N ] ; for ( int i = 0 ; i < N * N ; ++ i ) a [ i ] = -1 ; int sx = rand ( ) % N ; int sy = rand ( ) % N ; int x = sx , y = sy ; for ( int i = 0 ; i < N * N - 1 ; ++ i ) if ( nextMove ( a , & x , & y ) == 0 ) return false ; if ( ! neighbour ( x , y , sx , sy ) ) return false ; print ( a ) ; return true ; } int main ( ) { srand ( time ( NULL ) ) ; while ( ! findClosedTour ( ) ) { ; } return 0 ; }
Printing all solutions in N | CPP program for above approach ; Program to solve N Queens problem ; All_rows_filled is a bit mask having all N bits set ; If rowmask will have all bits set , means queen has been placed successfully in all rows and board is displayed ; We extract a bit mask ( safe ) by rowmask , ldmask and rdmask . all set bits of ' safe ' indicates the safe column index for queen placement of this iteration for row index ( row ) . ; Extracts the right - most set bit ( safe column index ) where queen can be placed for this row ; these bit masks will keep updated in each iteration for next row ; Reset right - most set bit to 0 so , next iteration will continue by placing the queen at another safe column index of this row ; Backtracking , replace ' Q ' by ' ▁ ' ; Driver Code ; Board size ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > result ; void solveBoard ( vector < vector < char > > & board , int row , int rowmask , int ldmask , int rdmask , int & ways ) { int n = board . size ( ) ; int all_rows_filled = ( 1 << n ) - 1 ; if ( rowmask == all_rows_filled ) { vector < int > v ; for ( int i = 0 ; i < board . size ( ) ; i ++ ) { for ( int j = 0 ; j < board . size ( ) ; j ++ ) { if ( board [ i ] [ j ] == ' Q ' ) v . push_back ( j + 1 ) ; } } result . push_back ( v ) ; return ; } int safe = all_rows_filled & ( ~ ( rowmask ldmask rdmask ) ) ; while ( safe ) { int p = safe & ( - safe ) ; int col = ( int ) log2 ( p ) ; board [ row ] [ col ] = ' Q ' ; solveBoard ( board , row + 1 , rowmask | p , ( ldmask p ) << 1 , ( rdmask p ) >> 1 , ways ) ; safe = safe & ( safe - 1 ) ; board [ row ] [ col ] = ' ▁ ' ; } return ; } int main ( ) { int n = 4 ; int ways = 0 ; vector < vector < char > > board ; for ( int i = 0 ; i < n ; i ++ ) { vector < char > tmp ; for ( int j = 0 ; j < n ; j ++ ) { tmp . push_back ( ' ▁ ' ) ; } board . push_back ( tmp ) ; } int rowmask = 0 , ldmask = 0 , rdmask = 0 ; int row = 0 ; result . clear ( ) ; solveBoard ( board , row , rowmask , ldmask , rdmask , ways ) ; sort ( result . begin ( ) , result . end ( ) ) ; for ( auto ar : result ) { cout << " [ " ; for ( auto it : ar ) cout << it << " ▁ " ; cout << " ] " ; } return 0 ; }
Find all distinct subsets of a given set using BitMasking Approach | C ++ program to find all subsets of given set . Any repeated subset is considered only once in the output ; Utility function to split the string using a delim . Refer - http : stackoverflow . com / questions / 236129 / split - a - string - in - c ; Function to find all subsets of given set . Any repeated subset is considered only once in the output ; Run counter i from 000. . 0 to 111. . 1 ; consider each element in the set ; Check if jth bit in the i is set . If the bit is set , we consider jth element from set ; if subset is encountered for the first time If we use set < string > , we can directly insert ; consider every subset ; split the subset and print its elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > split ( const string & s , char delim ) { vector < string > elems ; stringstream ss ( s ) ; string item ; while ( getline ( ss , item , delim ) ) elems . push_back ( item ) ; return elems ; } int printPowerSet ( int arr [ ] , int n ) { vector < string > list ; for ( int i = 0 ; i < ( int ) pow ( 2 , n ) ; i ++ ) { string subset = " " ; for ( int j = 0 ; j < n ; j ++ ) { if ( ( i & ( 1 << j ) ) != 0 ) subset += to_string ( arr [ j ] ) + " | " ; } if ( find ( list . begin ( ) , list . end ( ) , subset ) == list . end ( ) ) list . push_back ( subset ) ; } for ( string subset : list ) { vector < string > arr = split ( subset , ' ▁ ' ) ; for ( string str : arr ) cout << str << " ▁ " ; cout << endl ; } } int main ( ) { int arr [ ] = { 10 , 12 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPowerSet ( arr , n ) ; return 0 ; }
Fill two instances of all numbers from 1 to n in a specific way | A backtracking based C ++ Program to fill two instances of all numbers from 1 to n in a specific way ; A recursive utility function to fill two instances of numbers from 1 to n in res [ 0. .2 n - 1 ] . ' curr ' is current value of n . ; If current number becomes 0 , then all numbers are filled ; Try placing two instances of ' curr ' at all possible locations till solution is found ; Two ' curr ' should be placed at ' curr + 1' distance ; Plave two instances of ' curr ' ; Recur to check if the above placement leads to a solution ; If solution is not possible , then backtrack ; This function prints the result for input number ' n ' using fillUtil ( ) ; Create an array of size 2 n and initialize all elements in it as 0 ; If solution is possible , then print it . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool fillUtil ( int res [ ] , int curr , int n ) { if ( curr == 0 ) return true ; int i ; for ( i = 0 ; i < 2 * n - curr - 1 ; i ++ ) { if ( res [ i ] == 0 && res [ i + curr + 1 ] == 0 ) { res [ i ] = res [ i + curr + 1 ] = curr ; if ( fillUtil ( res , curr - 1 , n ) ) return true ; res [ i ] = res [ i + curr + 1 ] = 0 ; } } return false ; } void fill ( int n ) { int res [ 2 * n ] , i ; for ( i = 0 ; i < 2 * n ; i ++ ) res [ i ] = 0 ; if ( fillUtil ( res , n , n ) ) { for ( i = 0 ; i < 2 * n ; i ++ ) cout << res [ i ] << " ▁ " ; } else cout << " Not ▁ Possible " ; } int main ( ) { fill ( 7 ) ; 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 ; 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 } } ; 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 ; }
Fast Doubling method to find the Nth Fibonacci number | C ++ program to find the Nth Fibonacci number using Fast Doubling Method ; Function calculate the N - th fibanacci number using fast doubling method ; Base Condition ; Here a = F ( n ) ; Here b = F ( n + 1 ) ; As F ( 2 n ) = F ( n ) [ 2F ( n + 1 ) F ( n ) ] Here c = F ( 2 n ) ; As F ( 2 n + 1 ) = F ( n ) ^ 2 + F ( n + 1 ) ^ 2 Here d = F ( 2 n + 1 ) ; Check if N is odd or even ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int a , b , c , d ; #define MOD 1000000007 NEW_LINE void FastDoubling ( int n , int res [ ] ) { if ( n == 0 ) { res [ 0 ] = 0 ; res [ 1 ] = 1 ; return ; } FastDoubling ( ( n / 2 ) , res ) ; a = res [ 0 ] ; b = res [ 1 ] ; c = 2 * b - a ; if ( c < 0 ) c += MOD ; c = ( a * c ) % MOD ; d = ( a * a + b * b ) % MOD ; if ( n % 2 == 0 ) { res [ 0 ] = c ; res [ 1 ] = d ; } else { res [ 0 ] = d ; res [ 1 ] = c + d ; } } int main ( ) { int N = 6 ; int res [ 2 ] = { 0 } ; FastDoubling ( N , res ) ; cout << res [ 0 ] << " STRNEWLINE " ; return 0 ; }
Frequency of an integer in the given array using Divide and Conquer | C ++ implrmrntation of the approach ; Function to return the frequency of x in the subarray arr [ low ... high ] ; If the subarray is invalid or the element is not found ; If there 's only a single element which is equal to x ; Divide the array into two parts and then find the count of occurrences of x in both the parts ; Driver code
#include <iostream> NEW_LINE using namespace std ; int count ( int arr [ ] , int low , int high , int x ) { if ( ( low > high ) || ( low == high && arr [ low ] != x ) ) return 0 ; if ( low == high && arr [ low ] == x ) return 1 ; return count ( arr , low , ( low + high ) / 2 , x ) + count ( arr , 1 + ( low + high ) / 2 , high , x ) ; } int main ( ) { int arr [ ] = { 30 , 1 , 42 , 5 , 56 , 3 , 56 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int x = 56 ; cout << count ( arr , 0 , n - 1 , x ) ; return 0 ; }
Median of an unsorted array using Quick Select Algorithm | CPP program to find median of an array ; Utility function to swapping of element ; Returns the correct position of pivot element ; Picks a random pivot element between l and r and partitions arr [ l . . r ] around the randomly picked element using partition ( ) ; Utility function to find median ; if l < r ; Find the partition index ; If partition index = k , then we found the median of odd number element in arr [ ] ; If index = k - 1 , then we get a & b as middle element of arr [ ] ; If partitionIndex >= k then find the index in first half of the arr [ ] ; If partitionIndex <= k then find the index in second half of the arr [ ] ; Function to find Median ; If n is odd ; If n is even ; Print the Median of arr [ ] ; Driver program to test above methods
#include " bits / stdc + + . h " NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } int Partition ( int arr [ ] , int l , int r ) { int lst = arr [ r ] , i = l , j = l ; while ( j < r ) { if ( arr [ j ] < lst ) { swap ( & arr [ i ] , & arr [ j ] ) ; i ++ ; } j ++ ; } swap ( & arr [ i ] , & arr [ r ] ) ; return i ; } int randomPartition ( int arr [ ] , int l , int r ) { int n = r - l + 1 ; int pivot = rand ( ) % n ; swap ( & arr [ l + pivot ] , & arr [ r ] ) ; return Partition ( arr , l , r ) ; } void MedianUtil ( int arr [ ] , int l , int r , int k , int & a , int & b ) { if ( l <= r ) { int partitionIndex = randomPartition ( arr , l , r ) ; if ( partitionIndex == k ) { b = arr [ partitionIndex ] ; if ( a != -1 ) return ; } else if ( partitionIndex == k - 1 ) { a = arr [ partitionIndex ] ; if ( b != -1 ) return ; } if ( partitionIndex >= k ) return MedianUtil ( arr , l , partitionIndex - 1 , k , a , b ) ; else return MedianUtil ( arr , partitionIndex + 1 , r , k , a , b ) ; } return ; } void findMedian ( int arr [ ] , int n ) { int ans , a = -1 , b = -1 ; if ( n % 2 == 1 ) { MedianUtil ( arr , 0 , n - 1 , n / 2 , a , b ) ; ans = b ; } else { MedianUtil ( arr , 0 , n - 1 , n / 2 , a , b ) ; ans = ( a + b ) / 2 ; } cout << " Median ▁ = ▁ " << ans ; } int main ( ) { int arr [ ] = { 12 , 3 , 5 , 7 , 4 , 19 , 26 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMedian ( arr , n ) ; return 0 ; }
Largest number N which can be reduced to 0 in K steps | C ++ program to implement above approach ; Utility function to return the first digit of a number . ; Remove last digit from number till only one digit is left ; return the first digit ; Utility function that returns the count of numbers written down when starting from n ; Function to find the largest number N which can be reduced to 0 in K steps ; Get the sequence length of the mid point ; Until k sequence length is reached ; Update mid point ; Get count of the new mid point ; Update right to mid ; Update left to mid ; Increment mid point by one while count is equal to k to get the maximum value of mid point ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int firstDigit ( int n ) { while ( n >= 10 ) { n /= 10 ; } return n ; } int getCount ( int n ) { int count = 1 ; while ( n != 0 ) { int leadDigit = firstDigit ( n ) ; n -= leadDigit ; count ++ ; } return count ; } int getLargestNumber ( int k ) { int left = k ; int right = k * 10 ; int mid = ( left + right ) / 2 ; int len = getCount ( mid ) ; while ( len != k ) { mid = ( left + right ) / 2 ; len = getCount ( mid ) ; if ( len > k ) { right = mid ; } else { left = mid ; } } while ( len == k ) { if ( len != getCount ( mid + 1 ) ) { break ; } mid ++ ; } return ( mid ) ; } int main ( ) { int k = 3 ; cout << getLargestNumber ( k ) ; return 0 ; }
Check if point ( X , Y ) can be reached from origin ( 0 , 0 ) with jump of 1 and N perpendicularly simultaneously | C ++ program for the above approach ; Function to check if ( X , Y ) is reachable from ( 0 , 0 ) using the jumps of given type ; Case where source & destination are the same ; Check for even N ( X , Y ) is reachable or not ; If N is odd and parity of X and Y is different return , no valid sequence of jumps exist ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string checkReachability ( int N , int X , int Y ) { if ( X == 0 && Y == 0 ) { return " YES " ; } if ( N % 2 == 0 ) { return " YES " ; } else { if ( X % 2 != Y % 2 ) { return " NO " ; } else { return " YES " ; } } } int main ( ) { int N = 2 ; int X = 5 , Y = 4 ; cout << checkReachability ( N , X , Y ) ; return 0 ; }
Find three vertices in an N | C ++ program for the above approach ; Function to find three vertices that subtends an angle closest to A ; Stores the closest angle to A ; Stores the count of edge which subtend an angle of A ; Iterate in the range [ 1 , N - 2 ] ; Stores the angle subtended ; If absolute ( angle - A ) is less than absolute ( mi - A ) ; Update angle to mi , and also update i to ans ; Print the vertices ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE #define MAXN 1000000 NEW_LINE void closestsAngle ( int N , int A ) { double mi = INT_MAX ; int ans = 0 ; for ( int i = 1 ; i < N - 1 ; i ++ ) { double angle = 180.0 * i / N ; if ( fabs ( angle - A ) < fabs ( mi - A ) ) { mi = angle ; ans = i ; } } cout << 2 << ' ▁ ' << 1 << ' ▁ ' << 2 + ans ; } int main ( ) { int N = 3 , A = 15 ; closestsAngle ( N , A ) ; return 0 ; }
Area of a triangle with two vertices at midpoints of opposite sides of a square and the other vertex lying on vertex of a square | C ++ program for the above approach ; Function to find the area of the triangle that inscribed in square ; Stores the length of the first side of triangle ; Stores the length of the second side of triangle ; Stores the length of the third side of triangle ; Stores the area of the triangle ; Return the resultant area ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double areaOftriangle ( int side ) { double a = sqrt ( pow ( side / 2 , 2 ) + pow ( side / 2 , 2 ) ) ; double b = sqrt ( pow ( side , 2 ) + pow ( side / 2 , 2 ) ) ; double c = sqrt ( pow ( side , 2 ) + pow ( side / 2 , 2 ) ) ; double s = ( a + b + c ) / 2 ; double area = sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) ; return area ; } int main ( ) { int N = 10 ; cout << areaOftriangle ( N ) ; return 0 ; }
Equation of a straight line with perpendicular distance D from origin and an angle A between the perpendicular from origin and x | C ++ program for the approach ; Function to find equation of a line whose distance from origin and angle made by the perpendicular from origin with x - axis is given ; Convert angle from degree to radian ; Handle the special case ; Calculate the sin and cos of angle ; Print the equation of the line ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLine ( int distance , float degree ) { float x = degree * 3.14159 / 180 ; if ( degree > 90 ) { cout << " Not ▁ Possible " ; return ; } float result_1 = sin ( x ) ; float result_2 = cos ( x ) ; cout << fixed << setprecision ( 2 ) << result_2 << " x ▁ + " << result_1 << " y ▁ = ▁ " << distance ; } int main ( ) { int D = 10 ; float A = 30 ; findLine ( D , A ) ; return 0 ; }
Count number of coordinates from an array satisfying the given conditions | C ++ program for the above approach ; Function to count the number of coordinates from a given set that satisfies the given conditions ; Stores the count of central points ; Store the count of each x and y coordinates ; Find all possible pairs ; Initialize variables c1 , c2 , c3 , c4 to define the status of conditions ; Stores value of each point ; Check the conditions for each point by generating all possible pairs ; If arr [ j ] [ 0 ] > x and arr [ j ] [ 1 ] == y ; If arr [ j ] [ 0 ] < x and arr [ j ] [ 1 ] = = y ; If arr [ j ] [ 1 ] > y and arr [ j ] [ 0 ] == x ; If arr [ j ] [ 1 ] < y and arr [ j ] [ 0 ] = = x ; If all conditions satisfy then point is central point ; Increment the count by 1 ; Return the count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int centralPoints ( int arr [ ] [ 2 ] , int N ) { int count = 0 ; int c1 , c2 , c3 , c4 ; for ( int i = 0 ; i < N ; i ++ ) { c1 = 0 , c2 = 0 , c3 = 0 ; c4 = 0 ; int x = arr [ i ] [ 0 ] ; int y = arr [ i ] [ 1 ] ; for ( int j = 0 ; j < N ; j ++ ) { if ( arr [ j ] [ 0 ] > x && arr [ j ] [ 1 ] == y ) { c1 = 1 ; } if ( arr [ j ] [ 1 ] > y && arr [ j ] [ 0 ] == x ) { c2 = 1 ; } if ( arr [ j ] [ 0 ] < x && arr [ j ] [ 1 ] == y ) { c3 = 1 ; } if ( arr [ j ] [ 1 ] < y && arr [ j ] [ 0 ] == x ) { c4 = 1 ; } } if ( c1 + c2 + c3 + c4 == 4 ) { count ++ ; } } return count ; } int main ( ) { int arr [ 4 ] [ 2 ] = { { 1 , 0 } , { 2 , 0 } , { 1 , 1 } , { 1 , -1 } } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << centralPoints ( arr , N ) ; return 0 ; }
Displacement from origin after N moves of given distances in specified directions | C ++ program for the above approach ; Function to find the displacement from the origin and direction after performing the given set of moves ; Stores the distances travelled in the directions North , South , East , and West respectively ; Store the initial position of robot ; Traverse the array B [ ] ; If the current direction is North ; If the current direction is South ; If the current direction is East ; If the current direction is West ; Stores the total vertical displacement ; Stores the total horizontal displacement ; Find the displacement ; Print the displacement and direction after N moves ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void finalPosition ( char a [ ] , int b [ ] , int M ) { int n = 0 , s = 0 , e = 0 , w = 0 ; char p = ' N ' ; for ( int i = 0 ; i < M ; i ++ ) { if ( p == ' N ' ) { if ( a [ i ] == ' U ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' W ' ; w = w + b [ i ] ; } } else if ( p == ' S ' ) { if ( a [ i ] == ' U ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' E ' ; e = e + b [ i ] ; } } else if ( p == ' E ' ) { if ( a [ i ] == ' U ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' N ' ; n = n + b [ i ] ; } } else if ( p == ' W ' ) { if ( a [ i ] == ' U ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' S ' ; s = s + b [ i ] ; } } } int ver_disp = n - s ; int hor_disp = e - w ; int displacement = floor ( sqrt ( ( ver_disp * ver_disp ) + ( hor_disp * hor_disp ) ) ) ; cout << displacement << " ▁ " << p ; } int main ( ) { char A [ ] = { ' U ' , ' R ' , ' R ' , ' R ' , ' R ' } ; int B [ ] = { 1 , 1 , 1 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( B [ 0 ] ) ; finalPosition ( A , B , N ) ; return 0 ; }
Program to find Length of Latus Rectum of an Ellipse | C ++ program for the above approach ; Function to calculate the length of the latus rectum of an ellipse ; Length of major axis ; Length of minor axis ; Length of the latus rectum ; Driver Code ; Given lengths of semi - major and semi - minor axis ; Function call to calculate length of the latus rectum of a ellipse
#include <iostream> NEW_LINE using namespace std ; double lengthOfLatusRectum ( double A , double B ) { double major = 2.0 * A ; double minor = 2.0 * B ; double latus_rectum = ( minor * minor ) / major ; return latus_rectum ; } int main ( ) { double A = 3.0 , B = 2.0 ; cout << lengthOfLatusRectum ( A , B ) ; return 0 ; }
Program to find slant height of cone and pyramid | C ++ program for the above approach ; Function to calculate slant height of a cone ; Store the slant height of cone ; Print the result ; Function to find the slant height of a pyramid ; Store the slant height of pyramid ; Print the result ; Driver Code ; Dimensions of Cone ; Function Call for slant height of Cone ; Dimensions of Pyramid ; Function to calculate slant height of a pyramid
#include <bits/stdc++.h> NEW_LINE using namespace std ; void coneSlantHeight ( double cone_h , double cone_r ) { double slant_height_cone = sqrt ( pow ( cone_h , 2 ) + pow ( cone_r , 2 ) ) ; cout << " Slant ▁ height ▁ of ▁ cone ▁ is : ▁ " << slant_height_cone << ' ' ; } void pyramidSlantHeight ( double pyramid_h , double pyramid_s ) { double slant_height_pyramid = sqrt ( pow ( pyramid_s / 2 , 2 ) + pow ( pyramid_h , 2 ) ) ; cout << " Slant ▁ height ▁ of ▁ pyramid ▁ is : ▁ " << slant_height_pyramid << ' ' ; } int main ( ) { double H1 = 4.5 , R = 6 ; coneSlantHeight ( H1 , R ) ; double H2 = 4 , S = 4.8 ; pyramidSlantHeight ( H2 , S ) ; return 0 ; }