text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Maximum consecutive repeating character in string | C ++ program to find the maximum consecutive repeating character in given string ; function to find out the maximum repeating character in given string ; Find the maximum repeating character starting from str [ i ] ; Update result if required ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char maxRepeating ( string str ) { int len = str . length ( ) ; int count = 0 ; char res = str [ 0 ] ; for ( int i = 0 ; i < len ; i ++ ) { int cur_count = 1 ; for ( int j = i + 1 ; j < len ; j ++ ) { if ( str [ i ] != str [ j ] ) break ; cur_count ++ ; } if ( cur_count > count ) { count = cur_count ; res = str [ i ] ; } } return res ; } int main ( ) { string str = " aaaabbaaccde " ; cout << maxRepeating ( str ) ; return 0 ; } |
Sum of two large numbers | C ++ program to find sum of two large numbers . ; Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Reverse both of strings ; Do school mathematics , compute sum of current digits and carry ; Calculate carry for next step ; Add remaining digits of larger number ; Add remaining carry ; reverse resultant string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findSum ( string str1 , string str2 ) { if ( str1 . length ( ) > str2 . length ( ) ) swap ( str1 , str2 ) ; string str = " " ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; reverse ( str1 . begin ( ) , str1 . end ( ) ) ; reverse ( str2 . begin ( ) , str2 . end ( ) ) ; int carry = 0 ; for ( int i = 0 ; i < n1 ; i ++ ) { int sum = ( ( str1 [ i ] - '0' ) + ( str2 [ i ] - '0' ) + carry ) ; str . push_back ( sum % 10 + '0' ) ; carry = sum / 10 ; } for ( int i = n1 ; i < n2 ; i ++ ) { int sum = ( ( str2 [ i ] - '0' ) + carry ) ; str . push_back ( sum % 10 + '0' ) ; carry = sum / 10 ; } if ( carry ) str . push_back ( carry + '0' ) ; reverse ( str . begin ( ) , str . end ( ) ) ; return str ; } int main ( ) { string str1 = "12" ; string str2 = "198111" ; cout << findSum ( str1 , str2 ) ; return 0 ; } |
Sum of two large numbers | C ++ program to find sum of two large numbers . ; Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute sum of current digits and carry ; Add remaining digits of str2 [ ] ; Add remaining carry ; reverse resultant string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findSum ( string str1 , string str2 ) { if ( str1 . length ( ) > str2 . length ( ) ) swap ( str1 , str2 ) ; string str = " " ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; int diff = n2 - n1 ; int carry = 0 ; for ( int i = n1 - 1 ; i >= 0 ; i -- ) { int sum = ( ( str1 [ i ] - '0' ) + ( str2 [ i + diff ] - '0' ) + carry ) ; str . push_back ( sum % 10 + '0' ) ; carry = sum / 10 ; } for ( int i = n2 - n1 - 1 ; i >= 0 ; i -- ) { int sum = ( ( str2 [ i ] - '0' ) + carry ) ; str . push_back ( sum % 10 + '0' ) ; carry = sum / 10 ; } if ( carry ) str . push_back ( carry + '0' ) ; reverse ( str . begin ( ) , str . end ( ) ) ; return str ; } int main ( ) { string str1 = "12" ; string str2 = "198111" ; cout << findSum ( str1 , str2 ) ; return 0 ; } |
Palindrome pair in an array of words ( or strings ) | C ++ program to find if there is a pair that can form a palindrome . ; Utility function to check if a string is a palindrome ; compare each character from starting with its corresponding character from last ; Function to check if a palindrome pair exists ; Consider each pair one by one ; concatenate both strings ; check if the concatenated string is palindrome ; check for other combination of the two strings ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int len = str . length ( ) ; for ( int i = 0 ; i < len / 2 ; i ++ ) if ( str [ i ] != str [ len - i - 1 ] ) return false ; return true ; } bool checkPalindromePair ( vector < string > vect ) { for ( int i = 0 ; i < vect . size ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < vect . size ( ) ; j ++ ) { string check_str ; check_str = vect [ i ] + vect [ j ] ; if ( isPalindrome ( check_str ) ) return true ; check_str = vect [ j ] + vect [ i ] ; if ( isPalindrome ( check_str ) ) return true ; } } return false ; } int main ( ) { vector < string > vect = { " geekf " , " geeks " , " or " , " keeg " , " abc " , " bc " } ; checkPalindromePair ( vect ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Print consecutive characters together in a line | C ++ program to print consecutive characters together in a line . ; Driver code | #include <iostream> NEW_LINE using namespace std ; void print ( string str ) { cout << str [ 0 ] ; for ( int i = 1 ; str [ i ] != ' \0' ; i ++ ) { if ( ( str [ i ] == str [ i - 1 ] + 1 ) || ( str [ i ] == str [ i - 1 ] - 1 ) ) cout << str [ i ] ; else cout << " STRNEWLINE " << str [ i ] ; ; } } int main ( ) { string str = " ABCXYZACCD " ; print ( str ) ; return 0 ; } |
Efficiently check if a string has all unique characters without using any additional data structure | A space efficient C ++ program to check if all characters of string are unique . ; Returns true if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters using its 32 bits . ; If bit corresponding to current character is already set ; set bit in checker ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool areChractersUnique ( string str ) { int checker = 0 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { int val = ( str [ i ] - ' a ' ) ; if ( ( checker & ( 1 << val ) ) > 0 ) return false ; checker |= ( 1 << val ) ; } return true ; } int main ( ) { string s = " aaabbccdaa " ; if ( areChractersUnique ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count of words whose i | C ++ program to count words whose ith letter is either ( i - 1 ) th , ith , or ( i + 1 ) th letter of given word . ; Return the count of words . ; If word contain single letter , return 1. ; Checking for first letter . ; Traversing the string and multiplying for combinations . ; If all three letters are same . ; If two letter are distinct . ; If all three letter are distinct . ; Checking for last letter . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWords ( char str [ ] , int len ) { int count = 1 ; if ( len == 1 ) return count ; if ( str [ 0 ] == str [ 1 ] ) count *= 1 ; else count *= 2 ; for ( int j = 1 ; j < len - 1 ; j ++ ) { if ( str [ j ] == str [ j - 1 ] && str [ j ] == str [ j + 1 ] ) count *= 1 ; else if ( str [ j ] == str [ j - 1 ] str [ j ] == str [ j + 1 ] str [ j - 1 ] == str [ j + 1 ] ) count *= 2 ; else count *= 3 ; } if ( str [ len - 1 ] == str [ len - 2 ] ) count *= 1 ; else count *= 2 ; return count ; } int main ( ) { char str [ ] = " abc " ; int len = strlen ( str ) ; cout << countWords ( str , len ) << endl ; return 0 ; } |
Maximum and minimum sums from two numbers with digit replacements | C ++ program to find maximum and minimum possible sums of two numbers that we can get if replacing digit from 5 to 6 and vice versa are allowed . ; Find new value of x after replacing digit " from " to " to " ; Required digit found , replace it ; Returns maximum and minimum possible sums of x1 and x2 if digit replacements are allowed . ; We always get minimum sum if we replace 6 with 5. ; We always get maximum sum if we replace 5 with 6. ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int replaceDig ( int x , int from , int to ) { int result = 0 ; int multiply = 1 ; while ( x > 0 ) { int reminder = x % 10 ; if ( reminder == from ) result = result + to * multiply ; else result = result + reminder * multiply ; multiply *= 10 ; x = x / 10 ; } return result ; } void calculateMinMaxSum ( int x1 , int x2 ) { int minSum = replaceDig ( x1 , 6 , 5 ) + replaceDig ( x2 , 6 , 5 ) ; int maxSum = replaceDig ( x1 , 5 , 6 ) + replaceDig ( x2 , 5 , 6 ) ; cout << " Minimum β sum β = β " << minSum ; cout << " nMaximum β sum β = β " << maxSum ; } int main ( ) { int x1 = 5466 , x2 = 4555 ; calculateMinMaxSum ( x1 , x2 ) ; return 0 ; } |
Queries on substring palindrome formation | C ++ program to Queries on substring palindrome formation . ; Query type 1 : update string position i with character x . ; Print " Yes " if range [ L . . R ] can form palindrome , else print " No " . ; Find the frequency of each character in S [ L ... R ] . ; Checking if more than one character have frequency greater than 1. ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void qType1 ( int l , int x , char str [ ] ) { str [ l - 1 ] = x ; } void qType2 ( int l , int r , char str [ ] ) { int freq [ 27 ] = { 0 } ; for ( int i = l - 1 ; i <= r - 1 ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; int count = 0 ; for ( int j = 0 ; j < 26 ; j ++ ) if ( freq [ j ] % 2 ) count ++ ; ( count <= 1 ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int n = strlen ( str ) ; qType1 ( 4 , ' g ' , str ) ; qType2 ( 1 , 4 , str ) ; qType2 ( 2 , 3 , str ) ; qType1 ( 10 , ' t ' , str ) ; qType2 ( 10 , 11 , str ) ; return 0 ; } |
Queries on substring palindrome formation | C ++ program to Queries on substring palindrome formation . ; Return the frequency of the character in the i - th prefix . ; Updating the BIT ; Query to update the character in the string . ; Adding - 1 at L position ; Updating the character ; Adding + 1 at R position ; Query to find if rearrangement of character in range L ... R can form palindrome ; Checking on the first character of the string S . ; Checking if frequency of character is even or odd . ; Creating the Binary Index Tree of all alphabet ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define max 1000 NEW_LINE using namespace std ; int getFrequency ( int tree [ max ] [ 27 ] , int idx , int i ) { int sum = 0 ; while ( idx > 0 ) { sum += tree [ idx ] [ i ] ; idx -= ( idx & - idx ) ; } return sum ; } void update ( int tree [ max ] [ 27 ] , int idx , int val , int i ) { while ( idx <= max ) { tree [ idx ] [ i ] += val ; idx += ( idx & - idx ) ; } } void qType1 ( int tree [ max ] [ 27 ] , int l , int x , char str [ ] ) { update ( tree , l , -1 , str [ l - 1 ] - 97 + 1 ) ; str [ l - 1 ] = x ; update ( tree , l , 1 , str [ l - 1 ] - 97 + 1 ) ; } void qType2 ( int tree [ max ] [ 27 ] , int l , int r , char str [ ] ) { int count = 0 ; for ( int i = 1 ; i <= 26 ; i ++ ) { if ( l == 1 ) { if ( getFrequency ( tree , r , i ) % 2 == 1 ) count ++ ; } else { if ( ( getFrequency ( tree , r , i ) - getFrequency ( tree , l - 1 , i ) ) % 2 == 1 ) count ++ ; } } ( count <= 1 ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; } void buildBIT ( int tree [ max ] [ 27 ] , char str [ ] , int n ) { memset ( tree , 0 , sizeof ( tree ) ) ; for ( int i = 0 ; i < n ; i ++ ) update ( tree , i + 1 , 1 , str [ i ] - 97 + 1 ) ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int n = strlen ( str ) ; int tree [ max ] [ 27 ] ; buildBIT ( tree , str , n ) ; qType1 ( tree , 4 , ' g ' , str ) ; qType2 ( tree , 1 , 4 , str ) ; qType2 ( tree , 2 , 3 , str ) ; qType1 ( tree , 10 , ' t ' , str ) ; qType2 ( tree , 10 , 11 , str ) ; return 0 ; } |
Partition a number into two divisible parts | C ++ program to check if a string can be splitted into two strings such that one is divisible by ' a ' and other is divisible by ' b ' . ; Finds if it is possible to partition str into two parts such that first part is divisible by a and second part is divisible by b . ; Create an array of size len + 1 and initialize it with 0. Store remainders from left to right when divided by ' a ' ; Compute remainders from right to left when divided by ' b ' ; Find a point that can partition a number ; If split is not possible at this point ; We can split at i if one of the following two is true . a ) All characters after str [ i ] are 0 b ) String after str [ i ] is divisible by b , i . e . , str [ i + 1. . n - 1 ] is divisible by b . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findDivision ( string & str , int a , int b ) { int len = str . length ( ) ; vector < int > lr ( len + 1 , 0 ) ; lr [ 0 ] = ( str [ 0 ] - '0' ) % a ; for ( int i = 1 ; i < len ; i ++ ) lr [ i ] = ( ( lr [ i - 1 ] * 10 ) % a + ( str [ i ] - '0' ) ) % a ; vector < int > rl ( len + 1 , 0 ) ; rl [ len - 1 ] = ( str [ len - 1 ] - '0' ) % b ; int power10 = 10 ; for ( int i = len - 2 ; i >= 0 ; i -- ) { rl [ i ] = ( rl [ i + 1 ] + ( str [ i ] - '0' ) * power10 ) % b ; power10 = ( power10 * 10 ) % b ; } for ( int i = 0 ; i < len - 1 ; i ++ ) { if ( lr [ i ] != 0 ) continue ; if ( rl [ i + 1 ] == 0 ) { cout << " YES STRNEWLINE " ; for ( int k = 0 ; k <= i ; k ++ ) cout << str [ k ] ; cout << " , β " ; for ( int k = i + 1 ; k < len ; k ++ ) cout << str [ k ] ; return ; } } cout << " NO STRNEWLINE " ; } int main ( ) { string str = "123" ; int a = 12 , b = 3 ; findDivision ( str , a , b ) ; return 0 ; } |
Efficient method for 2 's complement of a binary string | An efficient C ++ program to find 2 's complement ; Function to find two 's complement ; Traverse the string to get first '1' from the last of string ; If there exists no '1' concatenate 1 at the starting of string ; Continue traversal after the position of first '1' ; Just flip the values ; return the modified string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findTwoscomplement ( string str ) { int n = str . length ( ) ; int i ; for ( i = n - 1 ; i >= 0 ; i -- ) if ( str [ i ] == '1' ) break ; if ( i == -1 ) return '1' + str ; for ( int k = i - 1 ; k >= 0 ; k -- ) { if ( str [ k ] == '1' ) str [ k ] = '0' ; else str [ k ] = '1' ; } return str ; ; } int main ( ) { string str = "00000101" ; cout << findTwoscomplement ( str ) ; return 0 ; } |
Check length of a string is equal to the number appended at its last | C ++ program to check if size of string is appended at the end or not . ; Function to find if given number is equal to length or not ; Traverse string from end and find the number stored at the end . x is used to store power of 10. ; Check if number is equal to string length except that number 's digits ; Drivers code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isequal ( string str ) { int n = str . length ( ) ; int num = 0 , x = 1 , i = n - 1 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( '0' <= str [ i ] && str [ i ] <= '9' ) { num = ( str [ i ] - '0' ) * x + num ; x = x * 10 ; if ( num >= n ) return false ; } else break ; } return num == i + 1 ; } int main ( ) { string str = " geeksforgeeks13" ; isequal ( str ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Check if two strings are k | CPP program for the above approach ; Function to check k anagram of two strings ; First Condition : If both the strings have different length , then they cannot form anagram ; Converting str1 to Character Array arr1 ; Converting str2 to Character Array arr2 ; Sort arr1 in increasing order ; Sort arr2 in increasing order ; Iterate till str1 . length ( ) ; Condition if arr1 [ i ] is not equal to arr2 [ i ] then add it to list ; Condition to check if strings for K - anagram or not ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool kAnagrams ( string str1 , string str2 , int k ) { int flag = 0 ; if ( str1 . length ( ) != str2 . length ( ) ) return false ; int n = str1 . length ( ) ; char arr1 [ n ] ; char arr2 [ n ] ; strcpy ( arr1 , str1 . c_str ( ) ) ; strcpy ( arr2 , str2 . c_str ( ) ) ; sort ( arr1 , arr1 + n ) ; sort ( arr2 , arr2 + n ) ; vector < char > list ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( arr1 [ i ] != arr2 [ i ] ) { list . push_back ( arr2 [ i ] ) ; } } if ( list . size ( ) <= k ) flag = 1 ; if ( flag == 1 ) return true ; else return false ; } int main ( ) { string str1 = " anagram " , str2 = " grammar " ; int k = 3 ; kAnagrams ( str1 , str2 , k ) ; if ( kAnagrams ( str1 , str2 , k ) == true ) cout << " Yes " ; else cout << " No " ; } |
Minimum number of characters to be removed to make a binary string alternate | C ++ program to find minimum number of characters to be removed to make a string alternate . ; Returns count of minimum characters to be removed to make s alternate . ; if two alternating characters of string are same ; result ++ ; then need to delete a character ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countToMake0lternate ( const string & s ) { int result = 0 ; for ( int i = 0 ; i < ( s . length ( ) - 1 ) ; i ++ ) if ( s [ i ] == s [ i + 1 ] ) return result ; } int main ( ) { cout << countToMake0lternate ( "000111" ) << endl ; cout << countToMake0lternate ( "11111" ) << endl ; cout << countToMake0lternate ( "01010101" ) << endl ; return 0 ; } |
Convert to a string that is repetition of a substring of k length | C ++ program to check if a string can be converted to a string that has repeated substrings of length k . ; Returns true if str can be converted to a string with k repeated substrings after replacing k characters . ; Length of string must be a multiple of k ; Map to store strings of length k and their counts ; If string is already a repetition of k substrings , return true . ; If number of distinct substrings is not 2 , then not possible to replace a string . ; One of the two distinct must appear exactly once . Either the first entry appears once , or it appears n / k - 1 times to make other substring appear once . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkString ( string str , long k ) { int n = str . length ( ) ; if ( n % k != 0 ) return false ; unordered_map < string , int > mp ; for ( int i = 0 ; i < n ; i += k ) mp [ str . substr ( i , k ) ] ++ ; if ( mp . size ( ) == 1 ) return true ; if ( mp . size ( ) != 2 ) return false ; if ( ( mp . begin ( ) -> second == ( n / k - 1 ) ) || mp . begin ( ) -> second == 1 ) return true ; return false ; } int main ( ) { checkString ( " abababcd " , 2 ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Group all occurrences of characters according to first appearance | C ++ program to print all occurrences of every character together . ; Since only lower case characters are there ; Function to print the string ; Initialize counts of all characters as 0 ; Count occurrences of all characters in string ; Starts traversing the string ; Print the character till its count in hash array ; Make this character 's count value as 0. ; Driver code | # include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void printGrouped ( string str ) { int n = str . length ( ) ; int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) { while ( count [ str [ i ] - ' a ' ] -- ) cout << str [ i ] ; count [ str [ i ] - ' a ' ] = 0 ; } } int main ( ) { string str = " geeksforgeeks " ; printGrouped ( str ) ; return 0 ; } |
Sort a string according to the order defined by another string | C ++ program to sort a string according to the order defined by a pattern string ; Sort str according to the order defined by pattern . ; Create a count array store count of characters in str . ; Count number of occurrences of each character in str . ; Traverse the pattern and print every characters same number of times as it appears in str . This loop takes O ( m + n ) time where m is length of pattern and n is length of str . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void sortByPattern ( string & str , string pat ) { int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) count [ str [ i ] - ' a ' ] ++ ; int index = 0 ; for ( int i = 0 ; i < pat . length ( ) ; i ++ ) for ( int j = 0 ; j < count [ pat [ i ] - ' a ' ] ; j ++ ) str [ index ++ ] = pat [ i ] ; } int main ( ) { string pat = " bca " ; string str = " abc " ; sortByPattern ( str , pat ) ; cout << str ; return 0 ; } |
Smallest Palindrome after replacement | C ++ program to get lexicographically smallest palindrome string ; Utility method to check str is possible palindrome after ignoring . ; If both left and right character are not dot and they are not equal also , then it is not possible to make this string a palindrome ; Returns lexicographically smallest palindrom string , if possible ; loop through character of string ; if one of character is dot , replace dot with other character ; if both character are dot , then replace them with smallest character ' a ' ; return the result ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossiblePalindrome ( string str ) { int n = str . length ( ) ; for ( int i = 0 ; i < n / 2 ; i ++ ) { if ( str [ i ] != ' . ' && str [ n - i - 1 ] != ' . ' && str [ i ] != str [ n - i - 1 ] ) return false ; } return true ; } string smallestPalindrome ( string str ) { if ( ! isPossiblePalindrome ( str ) ) return " Not β Possible " ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' . ' ) { if ( str [ n - i - 1 ] != ' . ' ) str [ i ] = str [ n - i - 1 ] ; else str [ i ] = str [ n - i - 1 ] = ' a ' ; } } return str ; } int main ( ) { string str = " ab . . e . c . a " ; cout << smallestPalindrome ( str ) << endl ; return 0 ; } |
Number of flips to make binary string alternate | Set 1 | C / C ++ program to find minimum number of flip to make binary string alternate ; Utility method to flip a character ; Utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; Driver code to test above method | #include <bits/stdc++.h> NEW_LINE using namespace std ; char flip ( char ch ) { return ( ch == '0' ) ? '1' : '0' ; } int getFlipWithStartingCharcter ( string str , char expected ) { int flipCount = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != expected ) flipCount ++ ; expected = flip ( expected ) ; } return flipCount ; } int minFlipToMakeStringAlternate ( string str ) { return min ( getFlipWithStartingCharcter ( str , '0' ) , getFlipWithStartingCharcter ( str , '1' ) ) ; } int main ( ) { string str = "0001010111" ; cout << minFlipToMakeStringAlternate ( str ) ; return 0 ; } |
Remainder with 7 for large numbers | C ++ program to find remainder of a large number when divided by 7. ; Function which returns Remainder after dividing the number by 7 ; This series is used to find remainder with 7 ; Index of next element in series ; Traverse num from end ; Find current digit of nun ; Add next term to result ; Move to next term in series ; Make sure that result never goes beyond 7. ; Make sure that remainder is positive ; Driver program | #include <iostream> NEW_LINE using namespace std ; int remainderWith7 ( string num ) { int series [ ] = { 1 , 3 , 2 , -1 , -3 , -2 } ; int series_index = 0 ; for ( int i = num . size ( ) - 1 ; i >= 0 ; i -- ) { int digit = num [ i ] - '0' ; result += digit * series [ series_index ] ; series_index = ( series_index + 1 ) % 6 ; result %= 7 ; } if ( result < 0 ) result = ( result + 7 ) % 7 ; return result ; } int main ( ) { string str = "12345" ; cout << " Remainder β with β 7 β is β " << remainderWith7 ( str ) ; return 0 ; } |
Check if a string can become empty by recursively deleting a given sub | C ++ Program to check if a string can be converted to an empty string by deleting given sub - string from any position , any number of times . ; Returns true if str can be made empty by recursively removing sub_str . ; idx : to store starting index of sub - string found in the original string ; Erasing the found sub - string from the original string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBecomeEmpty ( string str , string sub_str ) { while ( str . size ( ) > 0 ) { int idx = str . find ( sub_str ) ; if ( idx == -1 ) break ; str . erase ( idx , sub_str . size ( ) ) ; } return ( str . size ( ) == 0 ) ; } int main ( ) { string str = " GEEGEEKSKS " , sub_str = " GEEKS " ; if ( canBecomeEmpty ( str , sub_str ) ) cout << " Yes " else cout << " No " return 0 ; } |
Perfect reversible string | C ++ program to check if a string is perfect reversible or nor ; This function basically checks if string is palindrome or not ; iterate from left and right ; Driver program to run the case | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isReversible ( string str ) { int i = 0 , j = str . length ( ) - 1 ; while ( i < j ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; j -- ; } return true ; } int main ( ) { string str = " aba " ; if ( isReversible ( str ) ) cout << " YES " ; else cout << " NO " ; return 0 ; } |
Check if string follows order of characters defined by a pattern or not | Set 3 | C ++ program to find if a string follows order defined by a given pattern . ; Returns true if characters of str follow order defined by a given ptr . ; Initialize all orders as - 1 ; Assign an order to pattern characters according to their appearance in pattern ; give the pattern characters order ; increment the order ; Now one by check if string characters follow above order ; If order of this character is less than order of previous , return false . ; Update last_order for next iteration ; return that str followed pat ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int CHAR_SIZE = 256 ; bool checkPattern ( string str , string pat ) { vector < int > label ( CHAR_SIZE , -1 ) ; int order = 1 ; for ( int i = 0 ; i < pat . length ( ) ; i ++ ) { label [ pat [ i ] ] = order ; order ++ ; } int last_order = -1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( label [ str [ i ] ] != -1 ) { if ( label [ str [ i ] ] < last_order ) return false ; last_order = label [ str [ i ] ] ; } } return true ; } int main ( ) { string str = " engineers β rock " ; string pattern = " gsr " ; cout << boolalpha << checkPattern ( str , pattern ) ; return 0 ; } |
Find k 'th character of decrypted string | Set 1 | C ++ program to find K 'th character in decrypted string ; Function to find K 'th character in Encoded String ; expand string variable is used to store final string after decompressing string str ; string temp ; Current substring int freq = 0 ; Count of current substring ; read characters until you find a number or end of string ; push character in temp ; read number for how many times string temp will be repeated in decompressed string ; generating frequency of temp ; now append string temp into expand equal to its frequency ; this condition is to handle the case when string str is ended with alphabets not with numeric value ; Driver program to test the string | #include <bits/stdc++.h> NEW_LINE using namespace std ; char encodedChar ( string str , int k ) { string expand = " " ; for ( int i = 0 ; str [ i ] != ' \0' ; ) { while ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { temp . push_back ( str [ i ] ) ; i ++ ; } while ( str [ i ] >= '1' && str [ i ] <= '9' ) { freq = freq * 10 + str [ i ] - '0' ; i ++ ; } for ( int j = 1 ; j <= freq ; j ++ ) expand . append ( temp ) ; } if ( freq == 0 ) expand . append ( temp ) ; return expand [ k - 1 ] ; } int main ( ) { string str = " ab4c12ed3" ; int k = 21 ; cout << encodedChar ( str , k ) << endl ; return 0 ; } |
Converting Decimal Number lying between 1 to 3999 to Roman Numerals | C ++ Program for above approach ; Function to calculate roman equivalent ; storing roman values of digits from 0 - 9 when placed at different places ; Converting to roman ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string intToRoman ( int num ) { string m [ ] = { " " , " M " , " MM " , " MMM " } ; string c [ ] = { " " , " C " , " CC " , " CCC " , " CD " , " D " , " DC " , " DCC " , " DCCC " , " CM " } ; string x [ ] = { " " , " X " , " XX " , " XXX " , " XL " , " L " , " LX " , " LXX " , " LXXX " , " XC " } ; string i [ ] = { " " , " I " , " II " , " III " , " IV " , " V " , " VI " , " VII " , " VIII " , " IX " } ; string thousands = m [ num / 1000 ] ; string hundereds = c [ ( num % 1000 ) / 100 ] ; string tens = x [ ( num % 100 ) / 10 ] ; string ones = i [ num % 10 ] ; string ans = thousands + hundereds + tens + ones ; return ans ; } int main ( ) { int number = 3549 ; cout << intToRoman ( number ) ; return 0 ; } |
Converting Roman Numerals to Decimal lying between 1 to 3999 | Program to convert Roman Numerals to Numbers ; This function returns value of a Roman symbol ; If present value is less than next value , subtract present from next value and add the resultant to the sum variable . ; Driver Code ; Considering inputs given are valid | #include <bits/stdc++.h> NEW_LINE using namespace std ; int romanToDecimal ( string & str ) { map < char , int > m ; m . insert ( { ' I ' , 1 } ) ; m . insert ( { ' V ' , 5 } ) ; m . insert ( { ' X ' , 10 } ) ; m . insert ( { ' L ' , 50 } ) ; m . insert ( { ' C ' , 100 } ) ; m . insert ( { ' D ' , 500 } ) ; m . insert ( { ' M ' , 1000 } ) ; int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( m [ str [ i ] ] < m [ str [ i + 1 ] ] ) { sum += m [ str [ i + 1 ] ] - m [ str [ i ] ] ; i ++ ; continue ; } sum += m [ str [ i ] ] ; } return sum ; } int main ( ) { string str = " MCMIV " ; cout << " Integer β form β of β Roman β Numeral β is β " << romanToDecimal ( str ) << endl ; return 0 ; } |
Longest Common Prefix using Binary Search | 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 ; We will do an in - place binary search on the first string of the array in the range 0 to index ; Same as ( low + high ) / 2 , but avoids overflow for large low and high ; If all the strings in the input array contains this prefix then append this substring to our answer ; And then go for the right part ; else Go for the left part ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinLength ( string arr [ ] , int n ) { int min = INT_MAX ; for ( int i = 0 ; i <= n - 1 ; i ++ ) if ( arr [ i ] . length ( ) < min ) min = arr [ i ] . length ( ) ; return ( min ) ; } bool allContainsPrefix ( string arr [ ] , int n , string str , int start , int end ) { for ( int i = 0 ; i <= n - 1 ; i ++ ) for ( int j = start ; j <= end ; j ++ ) if ( arr [ i ] [ j ] != str [ j ] ) return ( false ) ; return ( true ) ; } string commonPrefix ( string arr [ ] , int n ) { int index = findMinLength ( arr , n ) ; int low = 0 , high = index ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( allContainsPrefix ( arr , n , arr [ 0 ] , low , mid ) ) { prefix = prefix + arr [ 0 ] . substr ( low , mid - low + 1 ) ; low = mid + 1 ; } high = mid - 1 ; } return ( prefix ) ; } 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 ) ; } |
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 ] &= ~ ( 1 << 5 ) ; return in ; } int main ( ) { string str = " geeksforgeeks " ; cout << to_upper ( str ) ; return 0 ; } |
Longest Common Prefix using Divide and Conquer Algorithm | A C ++ Program to find the longest common prefix ; A Utility Function to find the common prefix between strings - str1 and str2 ; A Divide and Conquer based function to find the longest common prefix . This is similar to the merge sort technique ; Same as ( low + high ) / 2 , but avoids overflow for large low and high ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string commonPrefixUtil ( string str1 , string str2 ) { string result ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; for ( int i = 0 , j = 0 ; i <= n1 - 1 && j <= n2 - 1 ; i ++ , j ++ ) { if ( str1 [ i ] != str2 [ j ] ) break ; result . push_back ( str1 [ i ] ) ; } return ( result ) ; } string commonPrefix ( string arr [ ] , int low , int high ) { if ( low == high ) return ( arr [ low ] ) ; if ( high > low ) { int mid = low + ( high - low ) / 2 ; string str1 = commonPrefix ( arr , low , mid ) ; string str2 = commonPrefix ( arr , mid + 1 , high ) ; return ( commonPrefixUtil ( str1 , str2 ) ) ; } } int main ( ) { string arr [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string ans = commonPrefix ( arr , 0 , n - 1 ) ; if ( ans . length ( ) ) cout << " The β longest β common β prefix β is β " << ans ; else cout << " There β is β no β common β prefix " ; return ( 0 ) ; } |
Longest Common Prefix using Word by Word Matching | A C ++ Program to find the longest common prefix ; A Utility Function to find the common prefix between strings - str1 and str2 ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string commonPrefixUtil ( string str1 , string str2 ) { string result ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; for ( int i = 0 , j = 0 ; i <= n1 - 1 && j <= n2 - 1 ; i ++ , j ++ ) { if ( str1 [ i ] != str2 [ j ] ) break ; result . push_back ( str1 [ i ] ) ; } return ( result ) ; } string commonPrefix ( string arr [ ] , int n ) { string prefix = arr [ 0 ] ; for ( int i = 1 ; i <= n - 1 ; i ++ ) prefix = commonPrefixUtil ( prefix , arr [ i ] ) ; return ( prefix ) ; } int main ( ) { string arr [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string ans = commonPrefix ( arr , n ) ; if ( ans . length ( ) ) printf ( " The β longest β common β prefix β is β - β % s " , ans . c_str ( ) ) ; else printf ( " There β is β no β common β prefix " ) ; return ( 0 ) ; } |
Find all strings formed from characters mapped to digits of a number | C ++ program to find all strings formed from a given number where each digit maps to given characters . ; Function to find all strings formed from a given number where each digit maps to given characters . ; vector of strings to store output ; stores index of first occurrence of the digits in input ; maintains index of current digit considered ; for each digit ; store index of first occurrence of the digit in the map ; clear vector contents for future use ; do for each character thats maps to the digit ; for first digit , simply push all its mapped characters in the output list ; from second digit onwards ; for each string in output list append current character to it . ; convert current character to string ; Imp - If this is not the first occurrence of the digit , use same character as used in its first occurrence ; store strings formed by current digit ; nothing more needed to be done if this is not the first occurrence of the digit ; replace contents of output list with temp list ; Driver program ; vector to store the mappings ; vector to store input number ; print all possible strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > findCombinations ( vector < int > input , vector < char > table [ ] ) { vector < string > out , temp ; unordered_map < int , int > mp ; int index = 0 ; for ( int d : input ) { if ( mp . find ( d ) == mp . end ( ) ) mp [ d ] = index ; temp . clear ( ) ; for ( int i = 0 ; i < table [ d - 1 ] . size ( ) ; i ++ ) { if ( index == 0 ) { string s ( 1 , table [ d - 1 ] . at ( i ) ) ; out . push_back ( s ) ; } if ( index > 0 ) { for ( string str : out ) { string s ( 1 , table [ d - 1 ] . at ( i ) ) ; if ( mp [ d ] != index ) s = str [ mp [ d ] ] ; str = str + s ; temp . push_back ( str ) ; } if ( mp [ d ] != index ) break ; } } if ( index > 0 ) out = temp ; index ++ ; } return out ; } int main ( ) { vector < char > table [ ] = { { ' A ' , ' B ' , ' C ' } , { ' D ' , ' E ' , ' F ' } , { ' G ' , ' H ' , ' I ' } , { ' J ' , ' K ' , ' L ' } , { ' M ' , ' N ' , ' O ' } , { ' P ' , ' Q ' , ' R ' } , { ' S ' , ' T ' , ' U ' } , { ' V ' , ' W ' , ' X ' } , { ' Y ' , ' Z ' } } ; vector < int > input = { 1 , 2 , 1 } ; vector < string > out = findCombinations ( input , table ) ; for ( string it : out ) cout << it << " β " ; return 0 ; } |
1 ' s β and β 2' s complement of a Binary Number | C ++ program to print 1 ' s β and β 2' s complement of a binary number ; Returns '0' for '1' and '1' for '0' ; Print 1 ' s β and β 2' s complement of binary number represented by " bin " ; for ones complement flip every bit ; for two 's complement go from right to left in ones complement and if we get 1 make, we make them 0 and keep going left when we get first 0, make that 1 and go out of loop ; If No break : all are 1 as in 111 or 11111 ; in such case , add extra 1 at beginning ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; char flip ( char c ) { return ( c == '0' ) ? '1' : '0' ; } void printOneAndTwosComplement ( string bin ) { int n = bin . length ( ) ; int i ; string ones , twos ; ones = twos = " " ; for ( i = 0 ; i < n ; i ++ ) ones += flip ( bin [ i ] ) ; twos = ones ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( ones [ i ] == '1' ) twos [ i ] = '0' ; else { twos [ i ] = '1' ; break ; } } if ( i == -1 ) twos = '1' + twos ; cout << "1 ' s β complement : β " << ones << endl ; cout << "2 ' s β complement : β " << twos << endl ; } int main ( ) { string bin = "1100" ; printOneAndTwosComplement ( bin ) ; return 0 ; } |
Print Concatenation of Zig | C ++ Program for above approach ; Function for zig - zag Concatenation ; Check is n is less or equal to 1 ; Iterate rowNum from 0 to n - 1 ; Iterate i till s . length ( ) - 1 ; Check is rowNum is 0 or n - 1 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string zigZagConcat ( string s , int n ) { if ( n <= 1 ) { return s ; } string result = " " ; for ( int rowNum = 0 ; rowNum < n ; rowNum ++ ) { int i = rowNum ; bool up = true ; while ( i < s . length ( ) ) { result += s [ i ] ; if ( rowNum == 0 rowNum == n - 1 ) { i += ( 2 * n - 2 ) ; } else { if ( up ) { i += ( 2 * ( n - rowNum ) - 2 ) ; } else { i += rowNum * 2 ; } up ^= true ; } } } return result ; } int main ( ) { string str = " GEEKSFORGEEKS " ; int n = 3 ; cout << zigZagConcat ( str , n ) ; } |
Print string of odd length in ' X ' format | CPP program to print cross pattern ; Function to print given string in cross pattern ; i and j are the indexes of characters to be displayed in the ith iteration i = 0 initially and go upto length of string j = length of string initially in each iteration of i , we increment i and decrement j , we print character only of k == i or k == j ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void pattern ( string str , int len ) { for ( int i = 0 ; i < len ; i ++ ) { int j = len - 1 - i ; for ( int k = 0 ; k < len ; k ++ ) { if ( k == i k == j ) cout << str [ k ] ; else cout << " β " ; } cout << endl ; } } int main ( ) { string str = " geeksforgeeks " ; int len = str . size ( ) ; pattern ( str , len ) ; return 0 ; } |
Recursively print all sentences that can be formed from list of word lists | C ++ program to print all possible sentences from a list of word list ; A recursive function to print all possible sentences that can be formed from a list of word list ; Add current word to output array ; If this is last word of current output sentence , then print the output sentence ; Recur for next row ; A wrapper over printUtil ( ) ; Create an array to store sentence ; Consider all words for first row as starting points and print all sentences ; Driver program to test above functions | #include <iostream> NEW_LINE #include <string> NEW_LINE #define R 3 NEW_LINE #define C 3 NEW_LINE using namespace std ; void printUtil ( string arr [ R ] [ C ] , int m , int n , string output [ R ] ) { output [ m ] = arr [ m ] [ n ] ; if ( m == R - 1 ) { for ( int i = 0 ; i < R ; i ++ ) cout << output [ i ] << " β " ; cout << endl ; return ; } for ( int i = 0 ; i < C ; i ++ ) if ( arr [ m + 1 ] [ i ] != " " ) printUtil ( arr , m + 1 , i , output ) ; } void print ( string arr [ R ] [ C ] ) { string output [ R ] ; for ( int i = 0 ; i < C ; i ++ ) if ( arr [ 0 ] [ i ] != " " ) printUtil ( arr , 0 , i , output ) ; } int main ( ) { string arr [ R ] [ C ] = { { " you " , " we " } , { " have " , " are " } , { " sleep " , " eat " , " drink " } } ; print ( arr ) ; return 0 ; } |
Check if characters of a given string can be rearranged to form a palindrome | C ++ implementation to check if characters of a given string can be rearranged to form a palindrome ; function to check whether characters of a string can form a palindrome ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; Count odd occurring characters ; Return true if odd count is 0 or 1 , ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE bool canFormPalindrome ( string str ) { int count [ NO_OF_CHARS ] = { 0 } ; for ( int i = 0 ; str [ i ] ; i ++ ) count [ str [ i ] ] ++ ; int odd = 0 ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) { if ( count [ i ] & 1 ) odd ++ ; if ( odd > 1 ) return false ; } return true ; } int main ( ) { canFormPalindrome ( " geeksforgeeks " ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; canFormPalindrome ( " geeksogeeks " ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; } |
Recursively remove all adjacent duplicates | C ++ Program for above approach ; Recursively removes adjacent duplicates from str and returns new string . las_removed is a pointer to last_removed character ; If length of string is 1 or 0 ; Recursively remove all the adjacent characters formed by removing the adjacent characters ; Have to check whether this is the repeated character that matches the last char of the parent String ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicates ( string s , char ch ) { if ( s . length ( ) <= 1 ) { return s ; } int i = 0 ; while ( i < s . length ( ) ) { if ( i + 1 < s . length ( ) && s [ i ] == s [ i + 1 ] ) { int j = i ; while ( j + 1 < s . length ( ) && s [ j ] == s [ j + 1 ] ) { j ++ ; } char lastChar = i > 0 ? s [ i - 1 ] : ch ; string remStr = removeDuplicates ( s . substr ( j + 1 , s . length ( ) ) , lastChar ) ; s = s . substr ( 0 , i ) ; int k = s . length ( ) , l = 0 ; while ( remStr . length ( ) > 0 && s . length ( ) > 0 && remStr [ 0 ] == s [ s . length ( ) - 1 ] ) { while ( remStr . length ( ) > 0 && remStr [ 0 ] != ch && remStr [ 0 ] == s [ s . length ( ) - 1 ] ) { remStr = remStr . substr ( 1 , remStr . length ( ) ) ; } s = s . substr ( 0 , s . length ( ) - 1 ) ; } s = s + remStr ; i = j ; } else { i ++ ; } } return s ; } int main ( ) { string str1 = " mississipie " ; cout << removeDuplicates ( str1 , ' β ' ) << endl ; string str2 = " ocvvcolop " ; cout << removeDuplicates ( str2 , ' β ' ) << endl ; } |
Write your own atoi ( ) | | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int val ; char strn1 [ ] = "12546" ; val = atoi ( strn1 ) ; cout << " String β value β = β " << strn1 << endl ; cout << " Integer β value β = β " << val << endl ; char strn2 [ ] = " GeeksforGeeks " ; val = atoi ( strn2 ) ; cout << " String β value β = β " << strn2 << endl ; cout << " Integer β value β = β " << val << endl ; return ( 0 ) ; } |
Generate n | C ++ program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; Base case ; Recursive case ; Append 0 to the first half ; Append 1 to the second half ; Function to generate the Gray code of N bits ; print contents of arr ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > generateGray ( int n ) { if ( n <= 0 ) return { "0" } ; if ( n == 1 ) { return { "0" , "1" } ; } vector < string > recAns = generateGray ( n - 1 ) ; vector < string > mainAns ; for ( int i = 0 ; i < recAns . size ( ) ; i ++ ) { string s = recAns [ i ] ; mainAns . push_back ( "0" + s ) ; } for ( int i = recAns . size ( ) - 1 ; i >= 0 ; i -- ) { string s = recAns [ i ] ; mainAns . push_back ( "1" + s ) ; } return mainAns ; } void generateGrayarr ( int n ) { vector < string > arr ; arr = generateGray ( n ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << endl ; } int main ( ) { generateGrayarr ( 3 ) ; return 0 ; } |
Write your own strcmp that ignores cases | ; implementation of strcmp that ignores cases ; If characters are same or inverting the 6 th bit makes them same ; Compare the last ( or first mismatching in case of not same ) characters ; Set the 6 th bit in both , then compare ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int ic_strcmp ( string s1 , string s2 ) { int i ; for ( i = 0 ; s1 [ i ] && s2 [ i ] ; ++ i ) { if ( s1 [ i ] == s2 [ i ] || ( s1 [ i ] ^ 32 ) == s2 [ i ] ) continue ; else break ; } if ( s1 [ i ] == s2 [ i ] ) return 0 ; if ( ( s1 [ i ] 32 ) < ( s2 [ i ] 32 ) ) return -1 ; return 1 ; } int main ( ) { cout << " ret : β " << ic_strcmp ( " Geeks " , " apple " ) << endl ; cout << " ret : β " << ic_strcmp ( " " , " ABCD " ) << endl ; cout << " ret : β " << ic_strcmp ( " ABCD " , " z " ) << endl ; cout << " ret : β " << ic_strcmp ( " ABCD " , " abcdEghe " ) << endl ; cout << " ret : β " << ic_strcmp ( " GeeksForGeeks " , " gEEksFORGeEKs " ) << endl ; cout << " ret : β " << ic_strcmp ( " GeeksForGeeks " , " geeksForGeeks " ) << endl ; 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 whether two strings are anagram of each other ; Create 2 count arrays 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 " ; Compare count arrays ; 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 count1 [ NO_OF_CHARS ] = { 0 } ; int count2 [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count1 [ str1 [ i ] ] ++ ; count2 [ str2 [ i ] ] ++ ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count1 [ i ] != count2 [ 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 ; } |
Find the smallest window in a string containing all characters of another string | C ++ program to find smallest window containing all characters of a pattern . ; Function to find smallest window containing all characters of ' pat ' ; Check if string ' s β length β β is β less β than β pattern ' s length . If yes then no such window can exist ; Store occurrence ofs characters of pattern ; Start traversing the string Count of characters ; Count occurrence of characters of string ; If string ' s β char β matches β with β β pattern ' s char then increment count ; if all the characters are matched ; Try to minimize the window ; update window size ; If no window found ; Return substring starting from start_index and length min_len ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int no_of_chars = 256 ; string findSubString ( string str , string pat ) { int len1 = str . length ( ) ; int len2 = pat . length ( ) ; if ( len1 < len2 ) { cout << " No β such β window β exists " ; return " " ; } int hash_pat [ no_of_chars ] = { 0 } ; int hash_str [ no_of_chars ] = { 0 } ; for ( int i = 0 ; i < len2 ; i ++ ) hash_pat [ pat [ i ] ] ++ ; int start = 0 , start_index = -1 , min_len = INT_MAX ; int count = 0 ; for ( int j = 0 ; j < len1 ; j ++ ) { hash_str [ str [ j ] ] ++ ; if ( hash_str [ str [ j ] ] <= hash_pat [ str [ j ] ] ) count ++ ; if ( count == len2 ) { while ( hash_str [ str [ start ] ] > hash_pat [ str [ start ] ] hash_pat [ str [ start ] ] == 0 ) { if ( hash_str [ str [ start ] ] > hash_pat [ str [ start ] ] ) hash_str [ str [ start ] ] -- ; start ++ ; } int len_window = j - start + 1 ; if ( min_len > len_window ) { min_len = len_window ; start_index = start ; } } } if ( start_index == -1 ) { cout << " No β such β window β exists " ; return " " ; } return str . substr ( start_index , min_len ) ; } int main ( ) { string str = " this β is β a β test β string " ; string pat = " tist " ; cout << " Smallest β window β is β : β STRNEWLINE " << findSubString ( str , pat ) ; return 0 ; } |
Remove characters from the first string which are present in the second string | C ++ program to remove duplicates ; we extract every character of string string 2 ; we find char exit or not ; if char exit we simply remove that char ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeChars ( string string1 , string string2 ) { for ( auto i : string2 ) { while ( find ( string1 . begin ( ) , string1 . end ( ) , i ) != string1 . end ( ) ) { auto itr = find ( string1 . begin ( ) , string1 . end ( ) , i ) ; string1 . erase ( itr ) ; } } return string1 ; } int main ( ) { string string1 , string2 ; string1 = " geeksforgeeks " ; string2 = " mask " ; cout << removeChars ( string1 , string2 ) << endl ; ; return 0 ; } |
Remove duplicates from a given string | CPP program to remove duplicate character from character array and print in sorted order ; Used as index in the modified string ; Traverse through all characters ; Check if str [ i ] is present before it ; If not present , then add it to result . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char * removeDuplicate ( char str [ ] , int n ) { int index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < i ; j ++ ) if ( str [ i ] == str [ j ] ) break ; if ( j == i ) str [ index ++ ] = str [ i ] ; } return str ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; cout << removeDuplicate ( str , n ) ; return 0 ; } |
Remove duplicates from a given string | access time in unordered_map on is O ( 1 ) generally if no collisions occur and therefore it helps us check if an element exists in a string in O ( 1 ) time complexity with constant space . ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char * removeDuplicates ( char * s , int n ) { unordered_map < char , int > exists ; int index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( exists [ s [ i ] ] == 0 ) { s [ index ++ ] = s [ i ] ; exists [ s [ i ] ] ++ ; } } return s ; } int main ( ) { char s [ ] = " geeksforgeeks " ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; cout << removeDuplicates ( s , n ) << endl ; return 0 ; } |
Print all Knight 's tour possible from a starting point on NxN chessboard | C ++ program of the above approach ; Stores the 8 possible combinations of moves that the knight can follow ; Function to find if ( i , j ) is a valid cell for the knight to move and it exists within the chessboard ; Stores whether there exist any valid path ; Recursive function to iterate through all the paths that the knight can follow ; Mark the current square of the chessboard ; If the number of visited squares are equal to the total number of sqares ; Print the current state of ChessBoard ; Backtrack to the previous move ; Iterate through all the eight possible moves for a knight ; Stores the new position of the knight after a move ; If the new position is a valid position recursively call for the next move ; Backtrack to the previous move ; Driver Code ; If no valid sequence of moves exist | #include <bits/stdc++.h> NEW_LINE using namespace std ; int DirX [ ] = { 2 , 1 , -1 , -2 , -2 , -1 , 1 , 2 } ; int DirY [ ] = { 1 , 2 , 2 , 1 , -1 , -2 , -2 , -1 } ; bool isSafe ( int i , int j , int n , vector < vector < int > > & Board ) { return ( i >= 0 and j >= 0 and i < n and j < n and Board [ i ] [ j ] == 0 ) ; } bool isPossible = false ; void knightTour ( vector < vector < int > > & ChessBoard , int N , int x , int y , int visited = 1 ) { ChessBoard [ x ] [ y ] = visited ; if ( visited == N * N ) { isPossible = true ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { cout << ChessBoard [ i ] [ j ] << " β " ; } cout << endl ; } cout << endl ; ChessBoard [ x ] [ y ] = 0 ; return ; } for ( int i = 0 ; i < 8 ; i ++ ) { int newX = x + DirX [ i ] ; int newY = y + DirY [ i ] ; if ( isSafe ( newX , newY , N , ChessBoard ) && ! ChessBoard [ newX ] [ newY ] ) { knightTour ( ChessBoard , N , newX , newY , visited + 1 ) ; } } ChessBoard [ x ] [ y ] = 0 ; } int main ( ) { vector < vector < int > > ChessBoard ( 5 , vector < int > ( 5 , 0 ) ) ; int N = ChessBoard . size ( ) ; int X = 1 ; int Y = 1 ; knightTour ( ChessBoard , N , X - 1 , Y - 1 ) ; if ( ! isPossible ) { cout << -1 ; } return 0 ; } |
Check if it β s possible to completely fill every container with same ball | C ++ program for above approach ; A boolean function that returns true if it 's possible to completely fill the container else return false ; Base Case ; Backtracking ; Function to check the conditions ; Storing frequencies ; Function Call for backtracking ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool getans ( int i , vector < int > v , vector < int > q ) { if ( i == q . size ( ) ) return true ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v [ j ] >= q [ i ] ) { v [ j ] -= q [ i ] ; if ( getans ( i + 1 , v , q ) ) { return true ; } v [ j ] += q [ i ] ; } } return false ; } void Check ( vector < int > c , vector < int > b ) { map < int , int > m ; for ( int i = 0 ; i < b . size ( ) ; i ++ ) { m [ b [ i ] ] ++ ; } vector < int > v ; for ( auto i : m ) { v . push_back ( i . second ) ; } bool check = getans ( 0 , v , c ) ; if ( check ) cout << " YES " << endl ; else cout << " NO " << endl ; } int main ( ) { vector < int > c = { 1 , 3 , 3 } ; vector < int > b = { 2 , 2 , 2 , 2 , 4 , 4 , 4 } ; Check ( c , b ) ; return 0 ; } |
Maximum Bitwise XOR of node values of an Acyclic Graph made up of N given vertices using M edges | C ++ program for the above approach ; Function to find the maximum Bitwise XOR of any subset of the array of size K ; Number of node must K + 1 for K edges ; Stores the maximum Bitwise XOR ; Generate all subsets of the array ; __builtin_popcount ( ) returns the number of sets bits in an integer ; Initialize current xor as 0 ; If jth bit is set in i then include jth element in the current xor ; Update the maximum Bitwise XOR obtained so far ; Return the maximum XOR ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumXOR ( int arr [ ] , int n , int K ) { K ++ ; int maxXor = INT_MIN ; for ( int i = 0 ; i < ( 1 << n ) ; i ++ ) { if ( __builtin_popcount ( i ) == K ) { int cur_xor = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) cur_xor = cur_xor ^ arr [ j ] ; } maxXor = max ( maxXor , cur_xor ) ; } } return maxXor ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int M = 2 ; cout << maximumXOR ( arr , N , M ) ; return 0 ; } |
Tower of Hanoi | Set 2 | C ++ program for the above approach ; Function to print order of movement of N disks across three rods to place all disks on the third rod from the first - rod using binary representation ; Iterate over the range [ 0 , 2 ^ N - 1 ] ; Print the movement of the current rod ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void TowerOfHanoi ( int N ) { for ( int x = 1 ; x <= pow ( 2 , N ) - 1 ; x ++ ) { cout << " Move β from β Rod β " << ( ( x & x - 1 ) % 3 + 1 ) << " β to β Rod β " << ( ( ( x x - 1 ) + 1 ) % 3 + 1 ) << endl ; } } int main ( ) { int N = 3 ; TowerOfHanoi ( N ) ; return 0 ; } |
Check if a path exists from a given cell to any boundary element of the Matrix with sum of elements not exceeding K | C ++ program for the above approach ; Function to check if it is valid to move to the given index or not ; Otherwise return false ; Function to check if there exists a path from the cell ( X , Y ) of the matrix to any boundary cell with sum of elements at most K or not ; Base Case ; If K >= board [ X ] [ Y ] ; Stores the current element ; Mark the current cell as visited ; Visit all the adjacent cells ; Mark the cell unvisited ; Return false ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( vector < vector < int > > & board , int i , int j , int K ) { if ( board [ i ] [ j ] <= K ) { return true ; } return false ; } bool findPath ( vector < vector < int > > & board , int X , int Y , int M , int N , int K ) { if ( X < 0 X == M Y < 0 Y == N ) { return true ; } if ( isValid ( board , X , Y , K ) ) { int board_XY = board [ X ] [ Y ] ; board [ X ] [ Y ] = INT_MAX ; if ( findPath ( board , X + 1 , Y , M , N , K - board_XY ) || findPath ( board , X - 1 , Y , M , N , K - board_XY ) || findPath ( board , X , Y + 1 , M , N , K - board_XY ) || findPath ( board , X , Y - 1 , M , N , K - board_XY ) ) { return true ; } board [ X ] [ Y ] = board_XY ; } return false ; } int main ( ) { vector < vector < int > > grid = { { 25 , 5 , 25 , 25 , 25 , 25 } , { 25 , 1 , 1 , 5 , 12 , 25 } , { 25 , 1 , 12 , 0 , 15 , 25 } , { 22 , 1 , 11 , 2 , 19 , 15 } , { 25 , 2 , 2 , 1 , 12 , 15 } , { 25 , 9 , 10 , 1 , 11 , 25 } , { 25 , 25 , 25 , 25 , 25 , 25 } } ; int K = 17 ; int M = grid . size ( ) ; int N = grid [ 0 ] . size ( ) ; int X = 2 , Y = 3 ; if ( findPath ( grid , X , Y , M , N , K ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
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 sum of 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 the sum of all the subsets from an array whose sum is a perfect number ; Stores the total number of subsets , i . e . 2 ^ n ; Consider all numbers from 0 to 2 ^ n - 1 ; Consider array elements from positions of set bits in the binary representation of n ; If sum of chosen elements is a perfect number ; 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 n ) { long long total = 1 << n ; for ( long long i = 0 ; i < total ; i ++ ) { long long sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) if ( i & ( 1 << j ) ) sum += arr [ j ] ; if ( isPerfect ( sum ) ) { cout << sum << " β " ; } } } int main ( ) { int arr [ ] = { 5 , 4 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; subsetSum ( arr , N ) ; return 0 ; } |
Pen Distribution Problem | C ++ implementation of the above approach ; Recursive function to play Game ; Box is empty , Game Over ! or Both have quit , Game Over ! ; P1 moves ; P2 moves ; Increment X ; Switch moves between P1 and P2 ; Function to find the number of pens remaining in the box and calculate score for each player ; Score of P1 ; Score of P2 ; Initialized to zero ; Move = 0 , P1 ' s β turn β β Move β = β 1 , β P2' s turn ; Has P1 quit ; Has P2 quit ; Recursively continue the game ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int & N , int & P1 , int & P2 , int & X , bool Move , bool QuitP1 , bool QuitP2 ) { if ( N == 0 or ( QuitP1 and QuitP2 ) ) { cout << " Number β of β pens β remaining " << " β in β the β box : β " << N << endl ; cout << " Number β of β pens β collected " << " β by β P1 : β " << P1 << endl ; cout << " Number β of β pens β collected " << " β by β P2 : β " << P2 << endl ; return ; } if ( Move == 0 and QuitP1 == false ) { int req_P1 = pow ( 2 , X ) ; if ( req_P1 <= N ) { P1 += req_P1 ; N -= req_P1 ; } else { QuitP1 = true ; } } else if ( Move == 1 and QuitP2 == false ) { int req_P2 = pow ( 3 , X ) ; if ( req_P2 <= N ) { P2 += req_P2 ; N -= req_P2 ; } else { QuitP2 = true ; } } X ++ ; Move = ( ( Move == 1 ) ? 0 : 1 ) ; solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) ; } void PenGame ( int N ) { int P1 = 0 ; int P2 = 0 ; int X = 0 ; bool Move = 0 ; bool QuitP1 = 0 ; bool QuitP2 = 0 ; solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) ; } int main ( ) { int N = 22 ; PenGame ( N ) ; return 0 ; } |
Print all possible K | C ++ program to implement the above approach ; Function to print all subsequences of length K from N natural numbers whose sum equal to N ; Base case ; Iterate over the range [ 1 , N ] ; Insert i into temp ; Pop i from temp ; Utility function to print all subsequences of length K with sum equal to N ; Store all subsequences of length K from N natural numbers ; Store current subsequence of length K from N natural numbers ; Stores total count of subsequences ; Print all subsequences ; Treaverse all subsequences ; Print current subsequence ; If current element is last element of subsequence ; If current subsequence is last subsequence from n natural numbers ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findSub ( vector < vector < int > > & res , int sum , int K , int N , vector < int > & temp ) { if ( K == 0 && sum == 0 ) { res . push_back ( temp ) ; return ; } if ( sum <= 0 K <= 0 ) { return ; } for ( int i = 1 ; i <= N ; i ++ ) { temp . push_back ( i ) ; findSub ( res , sum - i , K - 1 , N , temp ) ; temp . pop_back ( ) ; } } void UtilPrintSubsequncesOfKSumN ( int N , int K ) { vector < vector < int > > res ; vector < int > temp ; findSub ( res , N , K , N , temp ) ; int sz = res . size ( ) ; cout << " { β " ; for ( int i = 0 ; i < sz ; i ++ ) { cout << " { β " ; for ( int j = 0 ; j < K ; j ++ ) { if ( j == K - 1 ) cout << res [ i ] [ j ] << " β " ; else cout << res [ i ] [ j ] << " , β " ; } if ( i == sz - 1 ) cout << " } " ; else cout << " } , β " ; } cout << " β } " ; } int main ( ) { int N = 4 ; int K = 2 ; UtilPrintSubsequncesOfKSumN ( N , K ) ; } |
Generate all N digit numbers having absolute difference as K between adjacent digits | C ++ program for the above approach ; Function that recursively finds the possible numbers and append into ans ; Base Case ; Check the sum of last digit and k less than or equal to 9 or not ; If k == 0 , then subtraction and addition does not make any difference Hence , subtraction is skipped ; Function to call checkUntil function for every integer from 1 to 9 ; check_util function recursively store all numbers starting from i ; Function to print the all numbers which satisfy the conditions ; Driver Code ; Given N and K ; To store the result ; Function Call ; Print Resultant Numbers | #include <bits/stdc++.h> NEW_LINE using namespace std ; void checkUntil ( int num , int K , int N , vector < int > & ans ) { if ( N == 1 ) { ans . push_back ( num ) ; return ; } if ( ( num % 10 + K ) <= 9 ) checkUntil ( 10 * num + ( num % 10 + K ) , K , N - 1 , ans ) ; if ( K ) { if ( ( num % 10 - K ) >= 0 ) checkUntil ( 10 * num + num % 10 - K , K , N - 1 , ans ) ; } } void check ( int K , int N , vector < int > & ans ) { for ( int i = 1 ; i <= 9 ; i ++ ) { checkUntil ( i , K , N , ans ) ; } } void print ( vector < int > & ans ) { for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] << " , β " ; } } int main ( ) { int N = 4 , K = 8 ; vector < int > ans ; check ( K , N , ans ) ; print ( ans ) ; return 0 ; } |
Minimum Cost Path in a directed graph via given set of intermediate nodes | C ++ Program to implement the above approach ; Stores minimum - cost of path from source ; Function to Perform BFS on graph g starting from vertex v ; If destination is reached ; Set flag to true ; Visit all the intermediate nodes ; If any intermediate node is not visited ; If all intermediate nodes are visited ; Update the minSum ; Mark the current node visited ; Traverse adjacent nodes ; Mark the neighbour visited ; Find minimum cost path considering the neighbour as the source ; Mark the neighbour unvisited ; Mark the source unvisited ; Driver Code ; Stores the graph ; Number of nodes ; Source ; Destination ; Keeps a check on visited and unvisited nodes ; Stores intemediate nodes ; If no path is found | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minSum = INT_MAX ; void getMinPathSum ( unordered_map < int , vector < pair < int , int > > > & graph , vector < bool > & visited , vector < int > necessary , int src , int dest , int currSum ) { if ( src == dest ) { bool flag = true ; for ( int i : necessary ) { if ( ! visited [ i ] ) { flag = false ; break ; } } if ( flag ) minSum = min ( minSum , currSum ) ; return ; } else { visited [ src ] = true ; for ( auto node : graph [ src ] ) { if ( ! visited [ node . first ] ) { visited [ node . first ] = true ; getMinPathSum ( graph , visited , necessary , node . first , dest , currSum + node . second ) ; visited [ node . first ] = false ; } } visited [ src ] = false ; } } int main ( ) { unordered_map < int , vector < pair < int , int > > > graph ; graph [ 0 ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 2 } } ; graph [ 1 ] = { { 4 , 4 } , { 0 , 1 } } ; graph [ 2 ] = { { 4 , 5 } , { 5 , 6 } } ; graph [ 3 ] = { { 5 , 7 } , { 0 , 1 } } ; graph [ 4 ] = { { 6 , 4 } } ; graph [ 5 ] = { { 6 , 2 } } ; graph [ 6 ] = { { 7 , 11 } } ; int n = 7 ; int source = 0 ; int dest = 6 ; vector < bool > visited ( n , false ) ; vector < int > necessary { 2 , 4 } ; getMinPathSum ( graph , visited , necessary , source , dest , 0 ) ; if ( minSum == INT_MAX ) cout << " - 1 STRNEWLINE " ; else cout << minSum << ' ' ; return 0 ; } |
Unique subsequences of length K with given sum | C ++ program for the above approach ; Function to find all the subsequences of a given length and having sum S ; Termination condition ; Add value to sum ; Check if the resultant sum equals to target sum ; If true ; Print resultant array ; End this recursion stack ; Check all the combinations using backtracking ; Check all the combinations using backtracking ; Driver Code ; Given array ; To store the subsequence ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void comb ( int * arr , int len , int r , int ipos , int * op , int opos , int sum ) { if ( opos == r ) { int sum2 = 0 ; for ( int i = 0 ; i < opos ; i ++ ) { sum2 = sum2 + op [ i ] ; } if ( sum == sum2 ) { for ( int i = 0 ; i < opos ; i ++ ) cout << op [ i ] << " , β " ; cout << endl ; } return ; } if ( ipos < len ) { comb ( arr , len , r , ipos + 1 , op , opos , sum ) ; op [ opos ] = arr [ ipos ] ; comb ( arr , len , r , ipos + 1 , op , opos + 1 , sum ) ; } } int main ( ) { int arr [ ] = { 4 , 6 , 8 , 2 , 12 } ; int K = 3 ; int S = 20 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int op [ N ] = { 0 } ; comb ( arr , N , K , 0 , op , 0 , S ) ; return 0 ; } |
Traverse the matrix in Diagonally Bottum | C ++ implementation to traverse the matrix in the bottom - up fashion using Recursion ; Recursive function to traverse the matrix Diagonally Bottom - up ; Static variable for changing Row and column ; Flag variable for handling Bottum up diagonal traversing ; Base Condition ; Condition when to traverse Bottom Diagonal of the matrix ; Print matrix cell value ; Recursive function to traverse The matrix diagonally ; Recursive function to change diagonal ; Driver Code ; Initialize the 5 x 5 matrix ; Function call for traversing matrix | #include <iostream> NEW_LINE using namespace std ; bool traverseMatrixDiagonally ( int m [ ] [ 5 ] , int i , int j , int row , int col ) { static int k1 = 0 , k2 = 0 ; static bool flag = true ; if ( i >= row j >= col ) { if ( flag ) { int a = k1 ; k1 = k2 ; k2 = a ; flag = ! flag ; k1 ++ ; } else { int a = k1 ; k1 = k2 ; k2 = a ; flag = ! flag ; } cout << endl ; return false ; } cout << m [ i ] [ j ] << " β " ; if ( traverseMatrixDiagonally ( m , i + 1 , j + 1 , row , col ) ) { return true ; } if ( traverseMatrixDiagonally ( m , k1 , k2 , row , col ) ) { return true ; } return true ; } int main ( ) { int mtrx [ 5 ] [ 5 ] = { { 10 , 11 , 12 , 13 , 14 } , { 15 , 16 , 17 , 18 , 19 } , { 20 , 21 , 22 , 23 , 24 } , { 25 , 26 , 27 , 28 , 29 } , { 30 , 31 , 32 , 33 , 34 } } ; traverseMatrixDiagonally ( mtrx , 0 , 0 , 5 , 5 ) ; } |
Minimum colors required such that edges forming cycle do not have same color | C ++ implementation to find the minimum colors required to such that edges forming cycle don 't have same color ; Variable to store the graph ; To store that the vertex is visited or not ; Boolean Value to store that graph contains cycle or not ; Variable to store the color of the edges of the graph ; Function to traverse graph using DFS Traversal ; Loop to iterate for all edges from the source vertex ; If the vertex is not visited ; Condition to check cross and forward edges of the graph ; Presence of Back Edge ; Driver Code ; Loop to run DFS Traversal on vertex which is not visited ; Loop to print the colors of the edges | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 5 , m = 7 ; vector < pair < int , int > > g [ m ] ; int col [ n ] ; bool cyc ; int res [ m ] ; void dfs ( int v ) { col [ v ] = 1 ; for ( auto p : g [ v ] ) { int to = p . first , id = p . second ; if ( col [ to ] == 0 ) { dfs ( to ) ; res [ id ] = 1 ; } else if ( col [ to ] == 2 ) { res [ id ] = 1 ; } else { res [ id ] = 2 ; cyc = true ; } } col [ v ] = 2 ; } int main ( ) { g [ 0 ] . push_back ( make_pair ( 1 , 0 ) ) ; g [ 0 ] . push_back ( make_pair ( 2 , 1 ) ) ; g [ 1 ] . push_back ( make_pair ( 2 , 2 ) ) ; g [ 1 ] . push_back ( make_pair ( 3 , 3 ) ) ; g [ 2 ] . push_back ( make_pair ( 3 , 4 ) ) ; g [ 3 ] . push_back ( make_pair ( 4 , 5 ) ) ; g [ 4 ] . push_back ( make_pair ( 2 , 6 ) ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( col [ i ] == 0 ) { dfs ( i ) ; } } cout << ( cyc ? 2 : 1 ) << endl ; for ( int i = 0 ; i < m ; ++ i ) { cout << res [ i ] << ' β ' ; } return 0 ; } |
Perfect Sum Problem | C ++ implementation of the above approach ; Function to print the subsets whose sum is equal to the given target K ; Create the new array with size equal to array set [ ] to create binary array as per n ( decimal number ) ; Convert the array into binary array ; Calculate the sum of this subset ; Check whether sum is equal to target if it is equal , then print the subset ; Function to find the subsets with sum K ; Calculate the total no . of subsets ; Run loop till total no . of subsets and call the function for each subset ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void sumSubsets ( vector < int > set , int n , int target ) { int x [ set . size ( ) ] ; int j = set . size ( ) - 1 ; while ( n > 0 ) { x [ j ] = n % 2 ; n = n / 2 ; j -- ; } int sum = 0 ; for ( int i = 0 ; i < set . size ( ) ; i ++ ) if ( x [ i ] == 1 ) sum = sum + set [ i ] ; if ( sum == target ) { cout << ( " { " ) ; for ( int i = 0 ; i < set . size ( ) ; i ++ ) if ( x [ i ] == 1 ) cout << set [ i ] << " , β " ; cout << ( " } , β " ) ; } } void findSubsets ( vector < int > arr , int K ) { int x = pow ( 2 , arr . size ( ) ) ; for ( int i = 1 ; i < x ; i ++ ) sumSubsets ( arr , i , K ) ; } int main ( ) { vector < int > arr = { 5 , 10 , 12 , 13 , 15 , 18 } ; int K = 30 ; findSubsets ( arr , K ) ; return 0 ; } |
Sum of subsets of all the subsets of an array | O ( N ) | C ++ implementation of the approach ; To store factorial values ; Function to return ncr ; Function to return the required sum ; Initialising factorial ; Multiplier ; Finding the value of multipler according to the formula ; To store the final answer ; Calculate the final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxN 10 NEW_LINE int fact [ maxN ] ; int ncr ( int n , int r ) { return ( fact [ n ] / fact [ r ] ) / fact [ n - r ] ; } int findSum ( int * arr , int n ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) fact [ i ] = i * fact [ i - 1 ] ; int mul = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) mul += ( int ) pow ( 2 , i ) * ncr ( n - 1 , i ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += mul * arr [ i ] ; return ans ; } int main ( ) { int arr [ ] = { 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findSum ( arr , n ) ; return 0 ; } |
Count number of ways to reach destination in a maze | C ++ implementation of the approach ; Function to return the count of possible paths in a maze [ R ] [ C ] from ( 0 , 0 ) to ( R - 1 , C - 1 ) that do not pass through any of the marked cells ; If the initial cell is blocked , there is no way of moving anywhere ; Initializing the leftmost column ; If we encounter a blocked cell in leftmost row , there is no way of visiting any cell directly below it . ; Similarly initialize the topmost row ; If we encounter a blocked cell in bottommost row , there is no way of visiting any cell directly below it . ; The only difference is that if a cell is - 1 , simply ignore it else recursively compute count value maze [ i ] [ j ] ; If blockage is found , ignore this cell ; If we can reach maze [ i ] [ j ] from maze [ i - 1 ] [ j ] then increment count . ; If we can reach maze [ i ] [ j ] from maze [ i ] [ j - 1 ] then increment count . ; If the final cell is blocked , output 0 , otherwise the answer ; Function to return the count of all possible paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) ; We have to calculate m + n - 2 C n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! ; Function to return the total count of paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) that pass through at least one of the marked cells ; Total count of paths - Total paths that do not pass through any of the marked cell ; return answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 4 NEW_LINE #define C 4 NEW_LINE int countPaths ( int maze [ ] [ C ] ) { if ( maze [ 0 ] [ 0 ] == -1 ) return 0 ; for ( int i = 0 ; i < R ; i ++ ) { if ( maze [ i ] [ 0 ] == 0 ) maze [ i ] [ 0 ] = 1 ; else break ; } for ( int i = 1 ; i < C ; i ++ ) { if ( maze [ 0 ] [ i ] == 0 ) maze [ 0 ] [ i ] = 1 ; else break ; } for ( int i = 1 ; i < R ; i ++ ) { for ( int j = 1 ; j < C ; j ++ ) { if ( maze [ i ] [ j ] == -1 ) continue ; if ( maze [ i - 1 ] [ j ] > 0 ) maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i - 1 ] [ j ] ) ; if ( maze [ i ] [ j - 1 ] > 0 ) maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i ] [ j - 1 ] ) ; } } return ( maze [ R - 1 ] [ C - 1 ] > 0 ) ? maze [ R - 1 ] [ C - 1 ] : 0 ; } int numberOfPaths ( int m , int n ) { int path = 1 ; for ( int i = n ; i < ( m + n - 1 ) ; i ++ ) { path *= i ; path /= ( i - n + 1 ) ; } return path ; } int solve ( int maze [ ] [ C ] ) { int ans = numberOfPaths ( R , C ) - countPaths ( maze ) ; return ans ; } int main ( ) { int maze [ R ] [ C ] = { { 0 , 0 , 0 , 0 } , { 0 , -1 , 0 , 0 } , { -1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; cout << solve ( maze ) ; return 0 ; } |
Rat in a Maze with multiple steps or jump allowed | C / C ++ program to solve Rat in a Maze problem using backtracking ; Maze size ; A utility function to print solution matrix sol [ N ] [ N ] ; A utility function to check if x , y is valid index for N * N maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return true and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return true ; Check if maze [ x ] [ y ] is valid ; mark x , y as part of solution path ; Move forward in x direction ; Move forward in x direction ; If moving in x direction doesn 't give solution then Move down in y direction ; If none of the above movements work then BACKTRACK : unmark x , y as part of solution path ; driver program to test above function | #include <stdio.h> NEW_LINE #define N 4 NEW_LINE bool solveMazeUtil ( int maze [ N ] [ N ] , int x , int y , int sol [ N ] [ N ] ) ; void printSolution ( int sol [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) printf ( " β % d β " , sol [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } bool isSafe ( int maze [ N ] [ N ] , int x , int y ) { if ( x >= 0 && x < N && y >= 0 && y < N && maze [ x ] [ y ] != 0 ) return true ; return false ; } bool solveMaze ( int maze [ N ] [ N ] ) { int sol [ N ] [ N ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( solveMazeUtil ( maze , 0 , 0 , sol ) == false ) { printf ( " Solution β doesn ' t β exist " ) ; return false ; } printSolution ( sol ) ; return true ; } bool solveMazeUtil ( int maze [ N ] [ N ] , int x , int y , int sol [ N ] [ N ] ) { if ( x == N - 1 && y == N - 1 ) { sol [ x ] [ y ] = 1 ; return true ; } if ( isSafe ( maze , x , y ) == true ) { sol [ x ] [ y ] = 1 ; for ( int i = 1 ; i <= maze [ x ] [ y ] && i < N ; i ++ ) { if ( solveMazeUtil ( maze , x + i , y , sol ) == true ) return true ; if ( solveMazeUtil ( maze , x , y + i , sol ) == true ) return true ; } sol [ x ] [ y ] = 0 ; return false ; } return false ; } int main ( ) { int maze [ N ] [ N ] = { { 2 , 1 , 0 , 0 } , { 3 , 0 , 0 , 1 } , { 0 , 1 , 0 , 1 } , { 0 , 0 , 0 , 1 } } ; solveMaze ( maze ) ; return 0 ; } |
Prime numbers after prime P with sum S | CPP Program to print all N primes after prime P whose sum equals S ; vector to store prime and N primes whose sum equals given S ; function to check prime number ; square root of x ; since 1 is not prime number ; if any factor is found return false ; no factor found ; function to display N primes whose sum equals S ; function to evaluate all possible N primes whose sum equals S ; if total equals S And total is reached using N primes ; display the N primes ; if total is greater than S or if index has reached last element ; add prime [ index ] to set vector ; include the ( index ) th prime to total ; remove element from set vector ; exclude ( index ) th prime ; function to generate all primes ; all primes less than S itself ; if i is prime add it to prime vector ; if primes are less than N ; Driver Code | #include <iostream> NEW_LINE #include <vector> NEW_LINE #include <cmath> NEW_LINE using namespace std ; vector < int > set ; vector < int > prime ; bool isPrime ( int x ) { int sqroot = sqrt ( x ) ; bool flag = true ; if ( x == 1 ) return false ; for ( int i = 2 ; i <= sqroot ; i ++ ) if ( x % i == 0 ) return false ; return true ; } void display ( ) { int length = set . size ( ) ; for ( int i = 0 ; i < length ; i ++ ) cout << set [ i ] << " β " ; cout << " STRNEWLINE " ; } void primeSum ( int total , int N , int S , int index ) { if ( total == S && set . size ( ) == N ) { display ( ) ; return ; } if ( total > S || index == prime . size ( ) ) return ; set . push_back ( prime [ index ] ) ; primeSum ( total + prime [ index ] , N , S , index + 1 ) ; set . pop_back ( ) ; primeSum ( total , N , S , index + 1 ) ; } void allPrime ( int N , int S , int P ) { for ( int i = P + 1 ; i <= S ; i ++ ) { if ( isPrime ( i ) ) prime . push_back ( i ) ; } if ( prime . size ( ) < N ) return ; primeSum ( 0 , N , S , 0 ) ; } int main ( ) { int S = 54 , N = 2 , P = 3 ; allPrime ( N , S , P ) ; return 0 ; } |
A backtracking approach to generate n bit Gray Codes | CPP program to find the gray sequence of n bits . ; we have 2 choices for each of the n bits either we can include i . e invert the bit or we can exclude the bit i . e we can leave the number as it is . ; base case when we run out bits to process we simply include it in gray code sequence . ; ignore the bit . ; invert the bit . ; returns the vector containing the gray code sequence of n bits . ; num is passed by reference to keep track of current code . ; Driver function . | #include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void grayCodeUtil ( vector < int > & res , int n , int & num ) { if ( n == 0 ) { res . push_back ( num ) ; return ; } grayCodeUtil ( res , n - 1 , num ) ; num = num ^ ( 1 << ( n - 1 ) ) ; grayCodeUtil ( res , n - 1 , num ) ; } vector < int > grayCodes ( int n ) { vector < int > res ; int num = 0 ; grayCodeUtil ( res , n , num ) ; return res ; } int main ( ) { int n = 3 ; vector < int > code = grayCodes ( n ) ; for ( int i = 0 ; i < code . size ( ) ; i ++ ) cout << code [ i ] << endl ; return 0 ; } |
Partition of a set into K subsets with equal sum | C ++ program to check whether an array can be partitioned into K subsets of equal sum ; * array - given input array subsetSum array - sum to store each subset of the array taken - boolean array to check whether element is taken into sum partition or not K - number of partitions needed N - total number of element in array curIdx - current subsetSum index limitIdx - lastIdx from where array element should be taken ; current index ( K - 2 ) represents ( K - 1 ) subsets of equal sum last partition will already remain with sum ' subset ' ; recursive call for next subsetition ; start from limitIdx and include elements into current partition ; if already taken , continue ; if temp is less than subset then only include the element and call recursively ; mark the element and include into current partition sum ; after recursive call unmark the element and remove from subsetition sum ; Method returns true if arr can be partitioned into K subsets with equal sum ; If K is 1 , then complete array will be our answer ; If total number of partitions are more than N , then division is not possible ; if array sum is not divisible by K then we can 't divide array into K partitions ; the sum of each subset should be subset ( = sum / K ) ; Initialize sum of each subset from 0 ; mark all elements as not taken ; initialize first subsubset sum as last element of array and mark that as taken ; call recursive method to check K - substitution condition ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isKPartitionPossibleRec ( int arr [ ] , int subsetSum [ ] , bool taken [ ] , int subset , int K , int N , int curIdx , int limitIdx ) { if ( subsetSum [ curIdx ] == subset ) { if ( curIdx == K - 2 ) return true ; return isKPartitionPossibleRec ( arr , subsetSum , taken , subset , K , N , curIdx + 1 , N - 1 ) ; } for ( int i = limitIdx ; i >= 0 ; i -- ) { if ( taken [ i ] ) continue ; int tmp = subsetSum [ curIdx ] + arr [ i ] ; if ( tmp <= subset ) { taken [ i ] = true ; subsetSum [ curIdx ] += arr [ i ] ; bool nxt = isKPartitionPossibleRec ( arr , subsetSum , taken , subset , K , N , curIdx , i - 1 ) ; taken [ i ] = false ; subsetSum [ curIdx ] -= arr [ i ] ; if ( nxt ) return true ; } } return false ; } bool isKPartitionPossible ( int arr [ ] , int N , int K ) { if ( K == 1 ) return true ; if ( N < K ) return false ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; if ( sum % K != 0 ) return false ; int subset = sum / K ; int subsetSum [ K ] ; bool taken [ N ] ; for ( int i = 0 ; i < K ; i ++ ) subsetSum [ i ] = 0 ; for ( int i = 0 ; i < N ; i ++ ) taken [ i ] = false ; subsetSum [ 0 ] = arr [ N - 1 ] ; taken [ N - 1 ] = true ; return isKPartitionPossibleRec ( arr , subsetSum , taken , subset , K , N , 0 , N - 1 ) ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 5 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; if ( isKPartitionPossible ( arr , N , K ) ) cout << " Partitions β into β equal β sum β is β possible . STRNEWLINE " ; else cout << " Partitions β into β equal β sum β is β not β possible . STRNEWLINE " ; } |
Remove Invalid Parentheses | C / C ++ program to remove invalid parenthesis ; method checks if character is parenthesis ( openor closed ) ; method returns true if string contains valid parenthesis ; method to remove invalid parenthesis ; visit set to ignore already visited string ; queue to maintain BFS ; pushing given string as starting node into queue ; If answer is found , make level true so that valid string of only that level are processed . ; Removing parenthesis from str and pushing into queue , if not visited already ; Driver code to check above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isParenthesis ( char c ) { return ( ( c == ' ( ' ) || ( c == ' ) ' ) ) ; } bool isValidString ( string str ) { int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ( ' ) cnt ++ ; else if ( str [ i ] == ' ) ' ) cnt -- ; if ( cnt < 0 ) return false ; } return ( cnt == 0 ) ; } void removeInvalidParenthesis ( string str ) { if ( str . empty ( ) ) return ; set < string > visit ; queue < string > q ; string temp ; bool level ; q . push ( str ) ; visit . insert ( str ) ; while ( ! q . empty ( ) ) { str = q . front ( ) ; q . pop ( ) ; if ( isValidString ( str ) ) { cout << str << endl ; level = true ; } if ( level ) continue ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! isParenthesis ( str [ i ] ) ) continue ; temp = str . substr ( 0 , i ) + str . substr ( i + 1 ) ; if ( visit . find ( temp ) == visit . end ( ) ) { q . push ( temp ) ; visit . insert ( temp ) ; } } } } int main ( ) { string expression = " ( ) ( ) ) ( ) " ; removeInvalidParenthesis ( expression ) ; expression = " ( ) v ) " ; removeInvalidParenthesis ( expression ) ; return 0 ; } |
N Queen Problem | Backtracking | C / C ++ program to solve N Queen Problem using backtracking ; ld is an array where its indices indicate row - col + N - 1 ( N - 1 ) is for shifting the difference to store negative indices ; rd is an array where its indices indicate row + col and used to check whether a queen can be placed on right diagonal or not ; column array where its indices indicates column and used to check whether a queen can be placed in that row or not ; A utility function to print solution ; A recursive utility function to solve N Queen problem ; base case : If all queens are placed then return true ; Consider this column and try placing this queen in all rows one by one ; A check if a queen can be placed on board [ row ] [ col ] . We just need to check ld [ row - col + n - 1 ] and rd [ row + coln ] where ld and rd are for left and right diagonal respectively ; Place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; board [ i ] [ col ] = 0 ; BACKTRACK ; If the queen cannot be placed in any row in this colum col then return false ; This function solves the N Queen problem using Backtracking . It mainly uses solveNQUtil ( ) to solve the problem . It returns false if queens cannot be placed , otherwise , return true and prints placement of queens in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; driver program to test above function | #define N 4 NEW_LINE #include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE int ld [ 30 ] = { 0 } ; int rd [ 30 ] = { 0 } ; int cl [ 30 ] = { 0 } ; void printSolution ( int board [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) printf ( " β % d β " , board [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } bool solveNQUtil ( int board [ N ] [ N ] , int col ) { if ( col >= N ) return true ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( ld [ i - col + N - 1 ] != 1 && rd [ i + col ] != 1 ) && cl [ i ] != 1 ) { board [ i ] [ col ] = 1 ; ld [ i - col + N - 1 ] = rd [ i + col ] = cl [ i ] = 1 ; if ( solveNQUtil ( board , col + 1 ) ) return true ; ld [ i - col + N - 1 ] = rd [ i + col ] = cl [ i ] = 0 ; } } return false ; } bool solveNQ ( ) { int board [ N ] [ N ] = { { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 } } ; if ( solveNQUtil ( board , 0 ) == false ) { printf ( " Solution β does β not β exist " ) ; return false ; } printSolution ( board ) ; return true ; } int main ( ) { solveNQ ( ) ; return 0 ; } |
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Code in cpp to tell if there exists a pair in array whose sum results in x . ; Function to print pairs ; initializing the rem values with 0 's. ; Perform the remainder operation only if the element is x , as numbers greater than x can 't be used to get a sum x. Updating the count of remainders. ; Traversing the remainder list from start to middle to find pairs ; The elements with remainders i and x - i will result to a sum of x . Once we get two elements which add up to x , we print x and break . ; Once we reach middle of remainder array , we have to do operations based on x . ; if x is even and we have more than 1 elements with remainder x / 2 , then we will have two distinct elements which add up to x . if we dont have more than 1 element , print " No " . ; When x is odd we continue the same process which we did in previous loop . ; Driver Code ; Function calling | #include <iostream> NEW_LINE using namespace std ; void printPairs ( int a [ ] , int n , int x ) { int i ; int rem [ x ] ; for ( i = 0 ; i < x ; i ++ ) { rem [ i ] = 0 ; } for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] < x ) { rem [ a [ i ] % x ] ++ ; } } for ( i = 1 ; i < x / 2 ; i ++ ) { if ( rem [ i ] > 0 && rem [ x - i ] > 0 ) { cout << " Yes " << " STRNEWLINE " ; break ; } } if ( i >= x / 2 ) { if ( x % 2 == 0 ) { if ( rem [ x / 2 ] > 1 ) { cout << " Yes " << " STRNEWLINE " ; } else { cout << " No " << " STRNEWLINE " ; } } else { if ( rem [ x / 2 ] > 0 && rem [ x - x / 2 ] > 0 ) { cout << " Yes " << " STRNEWLINE " ; } else { cout << " No " << " STRNEWLINE " ; } } } } int main ( ) { int A [ ] = { 1 , 4 , 45 , 6 , 10 , 8 } ; int n = 16 ; int arr_size = sizeof ( A ) / sizeof ( A [ 0 ] ) ; printPairs ( A , arr_size , n ) ; return 0 ; } |
Find remainder when a number A raised to N factorial is divided by P | C ++ program for above approach ; Function to calculate factorial of a Number ; Calculating factorial ; Returning factorial ; Function to calculate resultant remainder ; Function call to calculate factorial of n ; Calculating remainder ; Returning resultant remainder ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int fact ( long long int n ) { long long int ans = 1 ; for ( long long int i = 2 ; i <= n ; i ++ ) ans *= i ; return ans ; } long long int remainder ( long long int n , long long int a , long long int p ) { long long int len = fact ( n ) ; long long int ans = 1 ; for ( long long int i = 1 ; i <= len ; i ++ ) ans = ( ans * a ) % p ; return ans ; } int main ( ) { long long int A = 2 , N = 1 , P = 2 ; cout << remainder ( N , A , P ) << endl ; } |
Check if a number N can be expressed in base B | C ++ program for the above approach ; Function to check if a number N can be expressed in base B ; Check if n is greater than 0 ; Initialize a boolean variable ; Check if digit is 0 or 1 ; Subtract the appropriate power of B from it and increment higher digit ; Driver Code ; Given Number N and base B ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int n , int w ) { vector < int > a ( 105 ) ; int p = 0 ; while ( n > 0 ) { a [ p ++ ] = n % w ; n /= w ; } bool flag = true ; for ( int i = 0 ; i <= 100 ; i ++ ) { if ( a [ i ] == 0 a [ i ] == 1 ) continue ; else if ( a [ i ] == w a [ i ] == w - 1 ) a [ i + 1 ] ++ ; else flag = false ; } return flag ; } int main ( ) { int B = 3 , N = 7 ; if ( check ( N , B ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count of groups among N people having only one leader in each group | C ++ program for the above approach ; Function to find 2 ^ x using modular exponentiation ; Base cases ; If B is even ; If B is odd ; Function to count the number of ways to form the group having one leader ; Find 2 ^ ( N - 1 ) using modular exponentiation ; Count total ways ; Print the total ways ; Driver Code ; Given N number of peoples ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long mod = 1000000007 ; int exponentMod ( int A , int B ) { if ( A == 0 ) return 0 ; if ( B == 0 ) return 1 ; long long y ; if ( B % 2 == 0 ) { y = exponentMod ( A , B / 2 ) ; y = ( y * y ) % mod ; } else { y = A % mod ; y = ( y * exponentMod ( A , B - 1 ) % mod ) % mod ; } return ( int ) ( ( y + mod ) % mod ) ; } void countWays ( int N ) { long long select = exponentMod ( 2 , N - 1 ) ; long long ways = ( ( N % mod ) * ( select % mod ) ) ; ways %= mod ; cout << ways ; } int main ( ) { int N = 5 ; countWays ( N ) ; } |
Array range queries to find the number of perfect square elements with updates | C ++ program to find number of perfect square numbers in a subarray and performing updates ; Function to check if a number is a perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; A utility function to get the middle index from corner indexes . ; where st -- > Pointer to segment tree index -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node i . e . st [ index ] qs & qe -- > Starting and ending indexes of query range ; If segment of this node is a part of given range , then return the number of perfect square numbers in the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; where st , si , ss & se are same as getSumUtil ( ) i -- > index of the element to be updated . This index is in input array . diff -- > Value to be added to all nodes which have i in range ; Base Case : If the input index lies outside the range of this segment ; If the input index is in range of this node , then update the value of the node and its children ; Function to update a value in the input array and segment tree . It uses updateValueUtil ( ) to update the value in segment tree ; Check for erroneous input index ; Update the value in array ; Case 1 : Old and new values both are perfect square numbers ; Case 2 : Old and new values both not perfect square numbers ; Case 3 : Old value was perfect square , new value is not a perfect square ; Case 4 : Old value was non - perfect square , new_val is perfect square ; Update values of nodes in segment tree ; Return no . of perfect square numbers in range from index qs ( query start ) to qe ( query end ) . It mainly uses queryUtil ( ) ; Recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , check if it is perfect square number then store 1 in the segment tree else store 0 and return ; if arr [ ss ] is a perfect square number ; If there are more than one elements , then recur for left and right subtrees and store the sum of the two values in this node ; Function to construct a segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Allocate memory for segment tree Height of segment tree ; Maximum size of segment tree ; Fill the allocated memory st ; Return the constructed segment tree ; Driver Code ; Build segment tree from given array ; Query 1 : Query ( start = 0 , end = 4 ) ; Query 2 : Update ( i = 3 , x = 11 ) , i . e Update a [ i ] to x ; Query 3 : Query ( start = 0 , end = 4 ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE bool isPerfectSquare ( long long int x ) { long double sr = sqrt ( x ) ; return ( ( sr - floor ( sr ) ) == 0 ) ? true : false ; } int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } int queryUtil ( int * st , int ss , int se , int qs , int qe , int index ) { if ( qs <= ss && qe >= se ) return st [ index ] ; if ( se < qs ss > qe ) return 0 ; int mid = getMid ( ss , se ) ; return queryUtil ( st , ss , mid , qs , qe , 2 * index + 1 ) + queryUtil ( st , mid + 1 , se , qs , qe , 2 * index + 2 ) ; } void updateValueUtil ( int * st , int ss , int se , int i , int diff , int si ) { if ( i < ss i > se ) return ; st [ si ] = st [ si ] + diff ; if ( se != ss ) { int mid = getMid ( ss , se ) ; updateValueUtil ( st , ss , mid , i , diff , 2 * si + 1 ) ; updateValueUtil ( st , mid + 1 , se , i , diff , 2 * si + 2 ) ; } } void updateValue ( int arr [ ] , int * st , int n , int i , int new_val ) { if ( i < 0 i > n - 1 ) { printf ( " Invalid β Input " ) ; return ; } int diff , oldValue ; oldValue = arr [ i ] ; arr [ i ] = new_val ; if ( isPerfectSquare ( oldValue ) && isPerfectSquare ( new_val ) ) return ; if ( ! isPerfectSquare ( oldValue ) && ! isPerfectSquare ( new_val ) ) return ; if ( isPerfectSquare ( oldValue ) && ! isPerfectSquare ( new_val ) ) { diff = -1 ; } if ( ! isPerfectSquare ( oldValue ) && ! isPerfectSquare ( new_val ) ) { diff = 1 ; } updateValueUtil ( st , 0 , n - 1 , i , diff , 0 ) ; } void query ( int * st , int n , int qs , int qe ) { int perfectSquareInRange = queryUtil ( st , 0 , n - 1 , qs , qe , 0 ) ; cout << perfectSquareInRange << " STRNEWLINE " ; } int constructSTUtil ( int arr [ ] , int ss , int se , int * st , int si ) { if ( ss == se ) { if ( isPerfectSquare ( arr [ ss ] ) ) st [ si ] = 1 ; else st [ si ] = 0 ; return st [ si ] ; } int mid = getMid ( ss , se ) ; st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ; return st [ si ] ; } int * constructST ( int arr [ ] , int n ) { int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int * st = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } int main ( ) { int arr [ ] = { 16 , 15 , 8 , 9 , 14 , 25 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * st = constructST ( arr , n ) ; int start = 0 ; int end = 4 ; query ( st , n , start , end ) ; int i = 3 ; int x = 11 ; updateValue ( arr , st , n , i , x ) ; start = 0 ; end = 4 ; query ( st , n , start , end ) ; return 0 ; } |
Find the element having maximum set bits in the given range for Q queries | C ++ implementation to find maximum set bits value in a range ; Structure to store two values in one node ; Function that returns the count of set bits in a number ; Parity will store the count of set bits ; Function to build the segment tree ; Condition to check if there is only one element in the array ; If there are more than one elements , then recur for left and right subtrees ; Condition to check the maximum set bits is greater in two subtrees ; Condition when maximum set bits are equal in both subtrees ; Function to do the range query in the segment tree ; If segment of this node is outside the given range , then return the minimum value . ; If segment of this node is a part of given range , then return the node of the segment ; If left segment of this node falls out of range , then recur in the right side of the tree ; If right segment of this node falls out of range , then recur in the left side of the tree ; If a part of this segment overlaps with the given range ; Returns the value ; Driver code ; Calculates the length of array ; Build Segment Tree ; Find the max set bits value between 1 st and 4 th index of array ; Find the max set bits value between 0 th and 2 nd index of array | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int value ; int max_set_bits ; } ; Node tree [ 4 * 10000 ] ; int setBits ( int x ) { int parity = 0 ; while ( x != 0 ) { if ( x & 1 ) parity ++ ; x = x >> 1 ; } return parity ; } void buildSegmentTree ( int a [ ] , int index , int beg , int end ) { if ( beg == end ) { tree [ index ] . value = a [ beg ] ; tree [ index ] . max_set_bits = setBits ( a [ beg ] ) ; } else { int mid = ( beg + end ) / 2 ; buildSegmentTree ( a , 2 * index + 1 , beg , mid ) ; buildSegmentTree ( a , 2 * index + 2 , mid + 1 , end ) ; if ( tree [ 2 * index + 1 ] . max_set_bits > tree [ 2 * index + 2 ] . max_set_bits ) { tree [ index ] . max_set_bits = tree [ 2 * index + 1 ] . max_set_bits ; tree [ index ] . value = tree [ 2 * index + 1 ] . value ; } else if ( tree [ 2 * index + 2 ] . max_set_bits > tree [ 2 * index + 1 ] . max_set_bits ) { tree [ index ] . max_set_bits = tree [ 2 * index + 2 ] . max_set_bits ; tree [ index ] . value = tree [ 2 * index + 2 ] . value ; } else { tree [ index ] . max_set_bits = tree [ 2 * index + 2 ] . max_set_bits ; tree [ index ] . value = max ( tree [ 2 * index + 2 ] . value , tree [ 2 * index + 1 ] . value ) ; } } } Node query ( int index , int beg , int end , int l , int r ) { Node result ; result . value = result . max_set_bits = -1 ; if ( beg > r end < l ) return result ; if ( beg >= l && end <= r ) return tree [ index ] ; int mid = ( beg + end ) / 2 ; if ( l > mid ) return query ( 2 * index + 2 , mid + 1 , end , l , r ) ; if ( r <= mid ) return query ( 2 * index + 1 , beg , mid , l , r ) ; Node left = query ( 2 * index + 1 , beg , mid , l , r ) ; Node right = query ( 2 * index + 2 , mid + 1 , end , l , r ) ; if ( left . max_set_bits > right . max_set_bits ) { result . max_set_bits = left . max_set_bits ; result . value = left . value ; } else if ( right . max_set_bits > left . max_set_bits ) { result . max_set_bits = right . max_set_bits ; result . value = right . value ; } else { result . max_set_bits = left . max_set_bits ; result . value = max ( right . value , left . value ) ; } return result ; } int main ( ) { int a [ ] = { 18 , 9 , 8 , 15 , 14 , 5 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; buildSegmentTree ( a , 0 , 0 , N - 1 ) ; cout << query ( 0 , 0 , N - 1 , 1 , 4 ) . value << endl ; cout << query ( 0 , 0 , N - 1 , 0 , 2 ) . value << endl ; return 0 ; } |
Array range queries to find the maximum Fibonacci number with updates | CPP code for range maximum query and updates ; A utility function to get the middle index of given range . ; Function to create hash table to check Fibonacci numbers ; A recursive function to get the sum of values in given range of the array . The following are parameters for this function . st -> Pointer to segment tree node -> Index of current node in the segment tree . ss & se -> Starting and ending indexes of the segment represented by current node , i . e . , st [ node ] l & r -> Starting and ending indexes of range query ; If segment of this node is completely part of given range , then return the max of segment ; If segment of this node does not belong to given range ; If segment of this node is partially the part of given range ; A recursive function to update the nodes which have the given index in their range . The following are parameters st , ss and se are same as defined above index -> index of the element to be updated . ; update value in array and in segment tree ; Return max of elements in range from index l ( query start ) to r ( query end ) . ; Check for erroneous input values ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the max of values in this node ; Function to construct segment tree from given array . This function allocates memory for segment tree . ; Height of segment tree ; Maximum size of segment tree ; Allocate memory ; Fill the allocated memory st ; Return the constructed segment tree ; Driver code ; find the largest node value in the array ; creating a set containing all fibonacci numbers upto the maximum data value in the array ; Build segment tree from given array ; Print max of values in array from index 1 to 3 ; Update : set arr [ 1 ] = 8 and update corresponding segment tree nodes . ; Find max after the value is updated | #include <bits/stdc++.h> NEW_LINE using namespace std ; set < int > fibonacci ; int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } void createHash ( int maxElement ) { int prev = 0 , curr = 1 ; fibonacci . insert ( prev ) ; fibonacci . insert ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; fibonacci . insert ( temp ) ; prev = curr ; curr = temp ; } } int MaxUtil ( int * st , int ss , int se , int l , int r , int node ) { if ( l <= ss && r >= se ) return st [ node ] ; if ( se < l ss > r ) return -1 ; int mid = getMid ( ss , se ) ; return max ( MaxUtil ( st , ss , mid , l , r , 2 * node + 1 ) , MaxUtil ( st , mid + 1 , se , l , r , 2 * node + 2 ) ) ; } void updateValue ( int arr [ ] , int * st , int ss , int se , int index , int value , int node ) { if ( index < ss index > se ) { cout << " Invalid β Input " << endl ; return ; } if ( ss == se ) { arr [ index ] = value ; if ( fibonacci . find ( value ) != fibonacci . end ( ) ) st [ node ] = value ; else st [ node ] = -1 ; } else { int mid = getMid ( ss , se ) ; if ( index >= ss && index <= mid ) updateValue ( arr , st , ss , mid , index , value , 2 * node + 1 ) ; else updateValue ( arr , st , mid + 1 , se , index , value , 2 * node + 2 ) ; st [ node ] = max ( st [ 2 * node + 1 ] , st [ 2 * node + 2 ] ) ; } return ; } int getMax ( int * st , int n , int l , int r ) { if ( l < 0 r > n - 1 l > r ) { printf ( " Invalid β Input " ) ; return -1 ; } return MaxUtil ( st , 0 , n - 1 , l , r , 0 ) ; } int constructSTUtil ( int arr [ ] , int ss , int se , int * st , int si ) { if ( ss == se ) { if ( fibonacci . find ( arr [ ss ] ) != fibonacci . end ( ) ) st [ si ] = arr [ ss ] ; else st [ si ] = -1 ; return st [ si ] ; } int mid = getMid ( ss , se ) ; st [ si ] = max ( constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) , constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ) ; return st [ si ] ; } int * constructST ( int arr [ ] , int n ) { int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int * st = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , st , 0 ) ; return st ; } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 7 , 9 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int maxEle = * max_element ( arr , arr + n ) ; createHash ( maxEle ) ; int * st = constructST ( arr , n ) ; cout << " Maximum β fibonacci β number " << " β in β given β range β = β " << getMax ( st , n , 1 , 3 ) << endl ; updateValue ( arr , st , 0 , n - 1 , 3 , 8 , 0 ) ; cout << " Updated β Maximum β Fibonacci " << " β number β in β given β range β = β " << getMax ( st , n , 1 , 3 ) << endl ; return 0 ; } |
Range Update Queries to XOR with 1 in a Binary Array . | C ++ program for the given problem ; Class for each node in the segment tree ; A utility function for merging two nodes ; utility function for updating a node ; A recursive function that constructs Segment Tree for given string ; If start is equal to end then insert the array element ; Build the segment tree for range qs to mid ; Build the segment tree for range mid + 1 to qe ; merge the two child nodes to obtain the parent node ; Query in a range qs to qe ; If the range lies in this segment ; If the range is out of the bounds of this segment ; Else query for the right and left child node of this subtree and merge them ; range update using lazy prpagation ; If the range is out of the bounds of this segment ; If the range lies in this segment ; Else query for the right and left child node of this subtree and merge them ; Driver code ; Build the segment tree ; Query of Type 2 in the range 3 to 7 ; Query of Type 3 in the range 2 to 5 ; Query of Type 1 in the range 1 to 4 ; Query of Type 4 in the range 3 to 7 ; Query of Type 5 in the range 4 to 9 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lazy [ 100001 ] ; class node { public : int l1 , r1 , l0 , r0 ; int min0 , max0 , min1 , max1 ; node ( ) { l1 = r1 = l0 = r0 = -1 ; max1 = max0 = INT_MIN ; min1 = min0 = INT_MAX ; } } seg [ 100001 ] ; node MergeUtil ( node l , node r ) { node x ; x . l0 = ( l . l0 != -1 ) ? l . l0 : r . l0 ; x . r0 = ( r . r0 != -1 ) ? r . r0 : l . r0 ; x . l1 = ( l . l1 != -1 ) ? l . l1 : r . l1 ; x . r1 = ( r . r1 != -1 ) ? r . r1 : l . r1 ; x . min0 = min ( l . min0 , r . min0 ) ; if ( l . r0 != -1 && r . l0 != -1 ) x . min0 = min ( x . min0 , r . l0 - l . r0 ) ; x . min1 = min ( l . min1 , r . min1 ) ; if ( l . r1 != -1 && r . l1 != -1 ) x . min1 = min ( x . min1 , r . l1 - l . r1 ) ; x . max0 = max ( l . max0 , r . max0 ) ; if ( l . l0 != -1 && r . r0 != -1 ) x . max0 = max ( x . max0 , r . r0 - l . l0 ) ; x . max1 = max ( l . max1 , r . max1 ) ; if ( l . l1 != -1 && r . r1 != -1 ) x . max1 = max ( x . max1 , r . r1 - l . l1 ) ; return x ; } node UpdateUtil ( node x ) { swap ( x . l0 , x . l1 ) ; swap ( x . r0 , x . r1 ) ; swap ( x . min1 , x . min0 ) ; swap ( x . max0 , x . max1 ) ; return x ; } void Build ( int qs , int qe , int ind , int arr [ ] ) { if ( qs == qe ) { if ( arr [ qs ] == 1 ) { seg [ ind ] . l1 = seg [ ind ] . r1 = qs ; } else { seg [ ind ] . l0 = seg [ ind ] . r0 = qs ; } lazy [ ind ] = 0 ; return ; } int mid = ( qs + qe ) >> 1 ; Build ( qs , mid , ind << 1 , arr ) ; Build ( mid + 1 , qe , ind << 1 1 , arr ) ; seg [ ind ] = MergeUtil ( seg [ ind << 1 ] , seg [ ind << 1 1 ] ) ; } node Query ( int qs , int qe , int ns , int ne , int ind ) { if ( lazy [ ind ] != 0 ) { seg [ ind ] = UpdateUtil ( seg [ ind ] ) ; if ( ns != ne ) { lazy [ ind * 2 ] ^= lazy [ ind ] ; lazy [ ind * 2 + 1 ] ^= lazy [ ind ] ; } lazy [ ind ] = 0 ; } node x ; if ( qs <= ns && qe >= ne ) return seg [ ind ] ; if ( ne < qs ns > qe ns > ne ) return x ; int mid = ( ns + ne ) >> 1 ; node l = Query ( qs , qe , ns , mid , ind << 1 ) ; node r = Query ( qs , qe , mid + 1 , ne , ind << 1 1 ) ; x = MergeUtil ( l , r ) ; return x ; } void RangeUpdate ( int us , int ue , int ns , int ne , int ind ) { if ( lazy [ ind ] != 0 ) { seg [ ind ] = UpdateUtil ( seg [ ind ] ) ; if ( ns != ne ) { lazy [ ind * 2 ] ^= lazy [ ind ] ; lazy [ ind * 2 + 1 ] ^= lazy [ ind ] ; } lazy [ ind ] = 0 ; } if ( ns > ne ns > ue ne < us ) return ; if ( ns >= us && ne <= ue ) { seg [ ind ] = UpdateUtil ( seg [ ind ] ) ; if ( ns != ne ) { lazy [ ind * 2 ] ^= 1 ; lazy [ ind * 2 + 1 ] ^= 1 ; } return ; } int mid = ( ns + ne ) >> 1 ; RangeUpdate ( us , ue , ns , mid , ind << 1 ) ; RangeUpdate ( us , ue , mid + 1 , ne , ind << 1 1 ) ; node l = seg [ ind << 1 ] , r = seg [ ind << 1 1 ] ; seg [ ind ] = MergeUtil ( l , r ) ; } int main ( ) { int arr [ ] = { 1 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Build ( 0 , n - 1 , 1 , arr ) ; node ans = Query ( 3 , 7 , 0 , n - 1 , 1 ) ; cout << ans . min1 << " STRNEWLINE " ; ans = Query ( 2 , 5 , 0 , n - 1 , 1 ) ; cout << ans . max1 << " STRNEWLINE " ; RangeUpdate ( 1 , 4 , 0 , n - 1 , 1 ) ; ans = Query ( 3 , 7 , 0 , n - 1 , 1 ) ; cout << ans . min0 << " STRNEWLINE " ; ans = Query ( 4 , 9 , 0 , n - 1 , 1 ) ; cout << ans . max0 << " STRNEWLINE " ; return 0 ; } |
Expected number of moves to reach the end of a board | Matrix Exponentiation | C ++ implementation of the approach ; Function to multiply two 7 * 7 matrix ; Function to perform matrix exponentiation ; 7 * 7 identity matrix ; Loop to find the power ; Function to return the required count ; Base cases ; Multiplier matrix ; Finding the required multiplier i . e mul ^ ( X - 6 ) ; Final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE #define maxSize 50 NEW_LINE using namespace std ; vector < vector < double > > matrix_product ( vector < vector < double > > a , vector < vector < double > > b ) { vector < vector < double > > c ( 7 ) ; for ( int i = 0 ; i < 7 ; i ++ ) c [ i ] . resize ( 7 , 0 ) ; for ( int i = 0 ; i < 7 ; i ++ ) for ( int j = 0 ; j < 7 ; j ++ ) for ( int k = 0 ; k < 7 ; k ++ ) c [ i ] [ j ] += a [ i ] [ k ] * b [ k ] [ j ] ; return c ; } vector < vector < double > > mul_expo ( vector < vector < double > > mul , int p ) { vector < vector < double > > s = { { 1 , 0 , 0 , 0 , 0 , 0 , 0 } , { 0 , 1 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 } } ; while ( p != 1 ) { if ( p % 2 == 1 ) s = matrix_product ( s , mul ) ; mul = matrix_product ( mul , mul ) ; p /= 2 ; } return matrix_product ( mul , s ) ; } double expectedSteps ( int x ) { if ( x == 0 ) return 0 ; if ( x <= 6 ) return 6 ; vector < vector < double > > mul = { { ( double ) 7 / 6 , 1 , 0 , 0 , 0 , 0 , 0 } , { 0 , 0 , 1 , 0 , 0 , 0 , 0 } , { 0 , 0 , 0 , 1 , 0 , 0 , 0 } , { 0 , 0 , 0 , 0 , 1 , 0 , 0 } , { 0 , 0 , 0 , 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 0 , 0 , 0 , 1 } , { ( double ) -1 / 6 , 0 , 0 , 0 , 0 , 0 , 0 } } ; mul = mul_expo ( mul , x - 6 ) ; return ( mul [ 0 ] [ 0 ] + mul [ 1 ] [ 0 ] + mul [ 2 ] [ 0 ] + mul [ 3 ] [ 0 ] + mul [ 4 ] [ 0 ] + mul [ 5 ] [ 0 ] ) * 6 ; } int main ( ) { int n = 10 ; cout << expectedSteps ( n - 1 ) ; return 0 ; } |
Place the prisoners into cells to maximize the minimum difference between any two | C ++ implementation of the approach ; Function that returns true if the prisoners can be placed such that the minimum distance between any two prisoners is at least sep ; Considering the first prisoner is placed at 1 st cell ; If the first prisoner is placed at the first cell then the last_prisoner_placed will be the first prisoner placed and that will be in cell [ 0 ] ; Checking if the prisoner can be placed at ith cell or not ; If all the prisoners got placed then return true ; Function to return the maximized distance ; Sort the array so that binary search can be applied on it ; Minimum possible distance for the search space ; Maximum possible distance for the search space ; To store the result ; Binary search ; If the prisoners can be placed such that the minimum distance between any two prisoners is at least mid ; Update the answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canPlace ( int a [ ] , int n , int p , int sep ) { int prisoners_placed = 1 ; int last_prisoner_placed = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { int current_cell = a [ i ] ; if ( current_cell - last_prisoner_placed >= sep ) { prisoners_placed ++ ; last_prisoner_placed = current_cell ; if ( prisoners_placed == p ) { return true ; } } } return false ; } int maxDistance ( int cell [ ] , int n , int p ) { sort ( cell , cell + n ) ; int start = 0 ; int end = cell [ n - 1 ] - cell [ 0 ] ; int ans = 0 ; while ( start <= end ) { int mid = start + ( ( end - start ) / 2 ) ; if ( canPlace ( cell , n , p , mid ) ) { ans = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } return ans ; } int main ( ) { int cell [ ] = { 1 , 2 , 8 , 4 , 9 } ; int n = sizeof ( cell ) / sizeof ( int ) ; int p = 3 ; cout << maxDistance ( cell , n , p ) ; return 0 ; } |
Find N in the given matrix that follows a pattern | C ++ implementation of the approach ; Function to return the row and the column of the given integer ; Binary search for the row number ; Condition to get the maximum x that satisfies the criteria ; Binary search for the column number ; Condition to get the maximum y that satisfies the criteria ; Get the row and the column number ; Return the pair ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > solve ( int n ) { int low = 1 , high = 1e4 , x = n , p = 0 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = ( mid * ( mid + 1 ) ) / 2 ; if ( x - sum >= 1 ) { p = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } int start = 1 , end = 1e4 , y = 1 , q = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int sum = ( mid * ( mid + 1 ) ) / 2 ; if ( y + sum <= n ) { q = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } x = x - ( p * ( p + 1 ) ) / 2 ; y = y + ( q * ( q + 1 ) ) / 2 ; int r = x ; int c = q + 1 - n + y ; pair < int , int > ans = { r , c } ; return ans ; } int main ( ) { int n = 5 ; pair < int , int > p = solve ( n ) ; cout << p . first << " β " << p . second ; return 0 ; } |
Find the count of distinct numbers in a range | C ++ Program to find the distinct elements in a range ; Function to perform queries in a range ; No overlap ; Totally Overlap ; Partial Overlap ; Finding the Answer for the left Child ; Finding the Answer for the right Child ; Combining the BitMasks ; Function to perform update operation in the Segment seg ; Forming the BitMask ; Updating the left Child ; Updating the right Child ; Updating the BitMask ; Building the Segment Tree ; Building the Initial BitMask ; Building the left seg tree ; Building the right seg tree ; Forming the BitMask ; Utility Function to answer the queries ; Counting the set bits which denote the distinct elements ; Updating the value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long query ( int start , int end , int left , int right , int node , long long seg [ ] ) { if ( end < left start > right ) { return 0 ; } else if ( start >= left && end <= right ) { return seg [ node ] ; } else { int mid = ( start + end ) / 2 ; long long leftChild = query ( start , mid , left , right , 2 * node , seg ) ; long long rightChild = query ( mid + 1 , end , left , right , 2 * node + 1 , seg ) ; return ( leftChild rightChild ) ; } } void update ( int left , int right , int index , int Value , int node , int ar [ ] , long long seg [ ] ) { if ( left == right ) { ar [ index ] = Value ; seg [ node ] = ( 1LL << Value ) ; return ; } int mid = ( left + right ) / 2 ; if ( index > mid ) { update ( mid + 1 , right , index , Value , 2 * node + 1 , ar , seg ) ; } else { update ( left , mid , index , Value , 2 * node , ar , seg ) ; } seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) ; } void build ( int left , int right , int node , int ar [ ] , long long seg [ ] ) { if ( left == right ) { seg [ node ] = ( 1LL << ar [ left ] ) ; return ; } int mid = ( left + right ) / 2 ; build ( left , mid , 2 * node , ar , seg ) ; build ( mid + 1 , right , 2 * node + 1 , ar , seg ) ; seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) ; } void getDistinctCount ( vector < vector < int > > & queries , int ar [ ] , long long seg [ ] , int n ) { for ( int i = 0 ; i < queries . size ( ) ; i ++ ) { int op = queries [ i ] [ 0 ] ; if ( op == 2 ) { int l = queries [ i ] [ 1 ] , r = queries [ i ] [ 2 ] ; long long tempMask = query ( 0 , n - 1 , l - 1 , r - 1 , 1 , seg ) ; int countOfBits = 0 ; for ( int i = 63 ; i >= 0 ; i -- ) { if ( tempMask & ( 1LL << i ) ) { countOfBits ++ ; } } cout << countOfBits << ' ' ; } else { int index = queries [ i ] [ 1 ] ; int val = queries [ i ] [ 2 ] ; update ( 0 , n - 1 , index - 1 , val , 1 , ar , seg ) ; } } } int main ( ) { int n = 7 ; int ar [ ] = { 1 , 2 , 1 , 3 , 1 , 2 , 1 } ; long long seg [ 4 * n ] = { 0 } ; build ( 0 , n - 1 , 1 , ar , seg ) ; int q = 5 ; vector < vector < int > > queries = { { 2 , 1 , 4 } , { 1 , 4 , 2 } , { 1 , 5 , 2 } , { 2 , 4 , 6 } , { 2 , 1 , 7 } } ; getDistinctCount ( queries , ar , seg , n ) ; return 0 ; } |
Smallest subarray with GCD as 1 | Segment Tree | C ++ implementation of the approach ; Array to store segment - tree ; Function to build segment - tree to answer range GCD queries ; Base - case ; Mid element of the range ; Merging the result of left and right sub - tree ; Function to perform range GCD queries ; Base - cases ; Mid - element ; Calling left and right child ; Function to find the required length ; Building the segment tree ; Two pointer variables ; To store the final answer ; Looping ; Incrementing j till we don 't get a gcd value of 1 ; Updating the final answer ; Incrementing i ; Updating j ; Returning the final answer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxLen 30 NEW_LINE int seg [ 3 * maxLen ] ; int build ( int l , int r , int in , int * arr ) { if ( l == r ) return seg [ in ] = arr [ l ] ; int mid = ( l + r ) / 2 ; return seg [ in ] = __gcd ( build ( l , mid , 2 * in + 1 , arr ) , build ( mid + 1 , r , 2 * in + 2 , arr ) ) ; } int query ( int l , int r , int l1 , int r1 , int in ) { if ( l1 <= l and r <= r1 ) return seg [ in ] ; if ( l > r1 or r < l1 ) return 0 ; int mid = ( l + r ) / 2 ; return __gcd ( query ( l , mid , l1 , r1 , 2 * in + 1 ) , query ( mid + 1 , r , l1 , r1 , 2 * in + 2 ) ) ; } int findLen ( int * arr , int n ) { build ( 0 , n - 1 , 0 , arr ) ; int i = 0 , j = 0 ; int ans = INT_MAX ; while ( i < n ) { while ( j < n and query ( 0 , n - 1 , i , j , 0 ) != 1 ) j ++ ; if ( j == n ) break ; ans = min ( ( j - i + 1 ) , ans ) ; i ++ ; j = max ( j , i ) ; } if ( ans == INT_MAX ) return -1 ; else return ans ; } int main ( ) { int arr [ ] = { 2 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << findLen ( arr , n ) ; return 0 ; } |
Find an N x N grid whose xor of every row and column is equal | C ++ implementation of the approach ; Function to find the n x n matrix that satisfies the given condition ; Initialize x to 0 ; Divide the n x n matrix into n / 4 matrices for each of the n / 4 rows where each matrix is of size 4 x 4 ; Print the generated matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findGrid ( int n ) { int arr [ n ] [ n ] ; int x = 0 ; for ( int i = 0 ; i < n / 4 ; i ++ ) { for ( int j = 0 ; j < n / 4 ; j ++ ) { for ( int k = 0 ; k < 4 ; k ++ ) { for ( int l = 0 ; l < 4 ; l ++ ) { arr [ i * 4 + k ] [ j * 4 + l ] = x ; x ++ ; } } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { cout << arr [ i ] [ j ] << " β " ; } cout << " STRNEWLINE " ; } } int main ( ) { int n = 4 ; findGrid ( n ) ; return 0 ; } |
Cartesian tree from inorder traversal | Segment Tree | C ++ implementation of the approach ; Node of the BST ; Array to store segment tree ; Function to create segment - tree to answer range - max query ; Base case ; Maximum index in left range ; Maximum index in right range ; If value at l1 > r1 ; Else ; Returning the maximum in range ; Function to answer range max query ; Base cases ; Maximum in left range ; Maximum in right range ; l1 = - 1 means left range was out - side required range ; Returning the maximum among two ranges ; Function to print the inorder traversal of the binary tree ; Base case ; Traversing the left sub - tree ; Printing current node ; Traversing the right sub - tree ; Function to build cartesian tree ; Base case ; Maximum in the range ; Creating current node ; Creating left sub - tree ; Creating right sub - tree ; Returning current node ; Driver code ; In - order traversal of cartesian tree ; Size of the array ; Building the segment tree ; Building and printing cartesian tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxLen 30 NEW_LINE struct node { int data ; node * left ; node * right ; node ( int data ) { left = NULL ; right = NULL ; this -> data = data ; } } ; int segtree [ maxLen * 4 ] ; int buildTree ( int l , int r , int i , int * arr ) { if ( l == r ) { segtree [ i ] = l ; return l ; } int l1 = buildTree ( l , ( l + r ) / 2 , 2 * i + 1 , arr ) ; int r1 = buildTree ( ( l + r ) / 2 + 1 , r , 2 * i + 2 , arr ) ; if ( arr [ l1 ] > arr [ r1 ] ) segtree [ i ] = l1 ; else segtree [ i ] = r1 ; return segtree [ i ] ; } int rangeMax ( int l , int r , int rl , int rr , int i , int * arr ) { if ( r < rl l > rr ) return -1 ; if ( l >= rl and r <= rr ) return segtree [ i ] ; int l1 = rangeMax ( l , ( l + r ) / 2 , rl , rr , 2 * i + 1 , arr ) ; int r1 = rangeMax ( ( l + r ) / 2 + 1 , r , rl , rr , 2 * i + 2 , arr ) ; if ( l1 == -1 ) return r1 ; if ( r1 == -1 ) return l1 ; if ( arr [ l1 ] > arr [ r1 ] ) return l1 ; else return r1 ; } void inorder ( node * curr ) { if ( curr == NULL ) return ; inorder ( curr -> left ) ; cout << curr -> data << " β " ; inorder ( curr -> right ) ; } node * createCartesianTree ( int l , int r , int * arr , int n ) { if ( r < l ) return NULL ; int m = rangeMax ( 0 , n - 1 , l , r , 0 , arr ) ; node * curr = new node ( arr [ m ] ) ; curr -> left = createCartesianTree ( l , m - 1 , arr , n ) ; curr -> right = createCartesianTree ( m + 1 , r , arr , n ) ; return curr ; } int main ( ) { int arr [ ] = { 8 , 11 , 21 , 100 , 5 , 70 , 55 } ; int n = sizeof ( arr ) / sizeof ( int ) ; buildTree ( 0 , n - 1 , 0 , arr ) ; inorder ( createCartesianTree ( 0 , n - 1 , arr , n ) ) ; } |
Kth smallest element in the array using constant space when array can 't be modified | C ++ implementation of the approach ; Function to return the kth smallest element from the array ; Minimum and maximum element from the array ; Modified binary search ; To store the count of elements from the array which are less than mid and the elements which are equal to mid ; If mid is the kth smallest ; If the required element is less than mid ; If the required element is greater than mid ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int kthSmallest ( int * arr , int k , int n ) { int low = * min_element ( arr , arr + n ) ; int high = * max_element ( arr , arr + n ) ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; int countless = 0 , countequal = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( arr [ i ] < mid ) ++ countless ; else if ( arr [ i ] == mid ) ++ countequal ; } if ( countless < k && ( countless + countequal ) >= k ) { return mid ; } else if ( countless >= k ) { high = mid - 1 ; } else if ( countless < k && countless + countequal < k ) { low = mid + 1 ; } } } int main ( ) { int arr [ ] = { 7 , 10 , 4 , 3 , 20 , 15 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 3 ; cout << kthSmallest ( arr , k , n ) ; return 0 ; } |
Interactive Problems in Competitive Programming | ; Iterating from lower_bound to upper_bound ; Input the response from the judge | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int lower_bound = 2 ; int upper_bound = 10 ; for ( int i = lower_bound ; i <= upper_bound ; i ++ ) { cout << i << endl ; int response ; cin >> response ; if ( response == 0 ) { cout << " Number β guessed β is β : " << i ; break ; } } return 0 ; } |
Lazy Propagation in Segment Tree | Set 2 | C ++ implementation of the approach ; To store segment tree ; To store pending updates ; si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue ; If lazy value is non - zero for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before making new updates . Because this value may be used by parent after recursive calls ( See last line of this function ) ; Make pending updates using value stored in lazy nodes ; Checking if it is not leaf node because if it is leaf node then we cannot go further ; We can postpone updating children we don 't need their new values now. Since we are not yet updating children of si, we need to set lazy flags for the children ; Set the lazy value for current node as 0 as it has been updated ; Out of range ; Current segment is fully in range ; Add the difference to current node ; Same logic for checking leaf node or not ; This is where we store values in lazy nodes , rather than updating the segment tree itelf Since we don 't need these updated values now we postpone updates by storing values in lazy[] ; If not completely in range , but overlaps recur for children ; And use the result of children calls to update this node ; Function to update a range of values in segment tree us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue ; A recursive function to get the max of values in given a range of the array . The following are the parameters for this function si -- > Index of the current node in the segment tree Initially , 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node i . e . , tree [ si ] qs & qe -- > Starting and ending indexes of query range ; If lazy flag is set for current node of segment tree then there are some pending updates . So we need to make sure that the pending updates are done before processing the sub sum query ; Make pending updates to this node . Note that this node represents sum of elements in arr [ ss . . se ] and all these elements must be increased by lazy [ si ] ; Checking if it is not leaf node because if it is leaf node then we cannot go further ; Since we are not yet updating children os si , we need to set lazy values for the children ; Unset the lazy value for current node as it has been updated ; Out of range ; If this segment lies in range ; If a part of this segment overlaps with the given range ; Return max of elements in range from index qs ( querystart ) to qe ( query end ) . It mainly uses getSumUtil ( ) ; Check for erroneous input values ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st . ; out of range as ss can never be greater than se ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the sum of values in this node ; Function to construct a segment tree from a given array This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Fill the allocated memory st ; Driver code ; Build segment tree from given array ; Add 4 to all nodes in index range [ 0 , 3 ] ; Print maximum element in index range [ 1 , 4 ] | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE int tree [ MAX ] = { 0 } ; int lazy [ MAX ] = { 0 } ; void updateRangeUtil ( int si , int ss , int se , int us , int ue , int diff ) { if ( lazy [ si ] != 0 ) { tree [ si ] += lazy [ si ] ; if ( ss != se ) { lazy [ si * 2 + 1 ] += lazy [ si ] ; lazy [ si * 2 + 2 ] += lazy [ si ] ; } lazy [ si ] = 0 ; } if ( ss > se ss > ue se < us ) return ; if ( ss >= us && se <= ue ) { tree [ si ] += diff ; if ( ss != se ) { lazy [ si * 2 + 1 ] += diff ; lazy [ si * 2 + 2 ] += diff ; } return ; } int mid = ( ss + se ) / 2 ; updateRangeUtil ( si * 2 + 1 , ss , mid , us , ue , diff ) ; updateRangeUtil ( si * 2 + 2 , mid + 1 , se , us , ue , diff ) ; tree [ si ] = max ( tree [ si * 2 + 1 ] , tree [ si * 2 + 2 ] ) ; } void updateRange ( int n , int us , int ue , int diff ) { updateRangeUtil ( 0 , 0 , n - 1 , us , ue , diff ) ; } int getMaxUtil ( int ss , int se , int qs , int qe , int si ) { if ( lazy [ si ] != 0 ) { tree [ si ] += lazy [ si ] ; if ( ss != se ) { lazy [ si * 2 + 1 ] += lazy [ si ] ; lazy [ si * 2 + 2 ] += lazy [ si ] ; } lazy [ si ] = 0 ; } if ( ss > se ss > qe se < qs ) return 0 ; if ( ss >= qs && se <= qe ) return tree [ si ] ; int mid = ( ss + se ) / 2 ; return max ( getSumUtil ( ss , mid , qs , qe , 2 * si + 1 ) , getSumUtil ( mid + 1 , se , qs , qe , 2 * si + 2 ) ) ; } int getMax ( int n , int qs , int qe ) { if ( qs < 0 qe > n - 1 qs > qe ) { printf ( " Invalid β Input " ) ; return -1 ; } return getSumUtil ( 0 , n - 1 , qs , qe , 0 ) ; } void constructSTUtil ( int arr [ ] , int ss , int se , int si ) { if ( ss > se ) return ; if ( ss == se ) { tree [ si ] = arr [ ss ] ; return ; } int mid = ( ss + se ) / 2 ; constructSTUtil ( arr , ss , mid , si * 2 + 1 ) ; constructSTUtil ( arr , mid + 1 , se , si * 2 + 2 ) ; tree [ si ] = max ( tree [ si * 2 + 1 ] , tree [ si * 2 + 2 ] ) ; } void constructST ( int arr [ ] , int n ) { constructSTUtil ( arr , 0 , n - 1 , 0 ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; constructST ( arr , n ) ; updateRange ( n , 0 , 3 , 4 ) ; cout << getSum ( n , 1 , 4 ) ; return 0 ; } |
Find 2 ^ ( 2 ^ A ) % B | C ++ implementation of the approach ; Function to return 2 ^ ( 2 ^ A ) % B ; Base case , 2 ^ ( 2 ^ 1 ) % B = 4 % B ; Driver code ; Print 2 ^ ( 2 ^ A ) % B | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll F ( ll A , ll B ) { if ( A == 1 ) return ( 4 % B ) ; else { ll temp = F ( A - 1 , B ) ; return ( temp * temp ) % B ; } } int main ( ) { ll A = 25 , B = 50 ; cout << F ( A , B ) ; return 0 ; } |
Sum of i * countDigits ( i ) ^ 2 for all i in range [ L , R ] | C ++ implementation of the approach ; Function to return the required sum ; If range is valid ; Sum of AP ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MOD 1000000007 NEW_LINE int rangeSum ( int l , int r ) { int a = 1 , b = 9 , res = 0 ; for ( int i = 1 ; i <= 10 ; i ++ ) { int L = max ( l , a ) ; int R = min ( r , b ) ; if ( L <= R ) { int sum = ( L + R ) * ( R - L + 1 ) / 2 ; res += ( i * i ) * ( sum % MOD ) ; res %= MOD ; } a = a * 10 ; b = b * 10 + 9 ; } return res ; } int main ( ) { int l = 98 , r = 102 ; cout << rangeSum ( l , r ) ; return 0 ; } |
Generate a random permutation of elements from range [ L , R ] ( Divide and Conquer ) | C ++ implementation of the approach ; To store the random permutation ; Utility function to print the generated permutation ; Function to return a random number between x and y ; Recursive function to generate the random permutation ; Base condition ; Random number returned from the function ; Inserting random number in vector ; Recursion call for [ l , n - 1 ] ; Recursion call for [ n + 1 , r ] ; Driver code ; Generate permutation ; Print the generated permutation | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > permutation ; void printPermutation ( ) { for ( auto i : permutation ) cout << i << " β " ; } int give_random_number ( int l , int r ) { int x = rand ( ) % ( r - l + 1 ) + l ; return x ; } void generate_random_permutation ( int l , int r ) { if ( l > r ) return ; int n = give_random_number ( l , r ) ; permutation . push_back ( n ) ; generate_random_permutation ( l , n - 1 ) ; generate_random_permutation ( n + 1 , r ) ; } int main ( ) { int l = 5 ; int r = 15 ; generate_random_permutation ( l , r ) ; printPermutation ( ) ; return 0 ; } |
Minimum number N such that total set bits of all numbers from 1 to N is at | C ++ implementation of the above approach ; Function to count sum of set bits of all numbers till N ; Function to find the minimum number ; Binary search for the lowest number ; Find mid number ; Check if it is atleast x ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF 99999 NEW_LINE #define size 10 NEW_LINE int getSetBitsFromOneToN ( int N ) { int two = 2 , ans = 0 ; int n = N ; while ( n ) { ans += ( N / two ) * ( two >> 1 ) ; if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 ; two <<= 1 ; n >>= 1 ; } return ans ; } int findMinimum ( int x ) { int low = 0 , high = 100000 ; int ans = high ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( getSetBitsFromOneToN ( mid ) >= x ) { ans = min ( ans , mid ) ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } int main ( ) { int x = 20 ; cout << findMinimum ( x ) ; return 0 ; } |
Range and Update Sum Queries with Factorial | CPP program to calculate sum of factorials in an interval and update with two types of operations ; Modulus ; Maximum size of input array ; Size for factorial array ; structure for queries with members type , leftIndex , rightIndex of the query ; function for updating the value ; function for calculating the required sum between two indexes ; function to return answer to queries ; Precomputing factorials ; Declaring a Set ; inserting indexes of those numbers which are lesser than 40 ; update query of the 1 st type ; find the left index of query in the set using binary search ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to its new value ; if updated value becomes greater than or equal to 40 remove it from the set ; increment the index ; update query of the 2 nd type ; update the value to its new value ; If the value is less than 40 , insert it into set , otherwise remove it ; sum query of the 3 rd type ; Driver Code to test above functions ; input array using 1 - based indexing ; declaring array of structure of type queries ; answer the Queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MOD = 1e9 ; const int MAX = 100 ; const int SZ = 40 ; int BIT [ MAX + 1 ] , fact [ SZ + 1 ] ; struct queries { int type , l , r ; } ; void update ( int x , int val , int n ) { for ( x ; x <= n ; x += x & - x ) BIT [ x ] += val ; } int sum ( int x ) { int s = 0 ; for ( x ; x > 0 ; x -= x & - x ) s += BIT [ x ] ; return s ; } void answerQueries ( int arr [ ] , queries que [ ] , int n , int q ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i < 41 ; i ++ ) fact [ i ] = ( fact [ i - 1 ] * i ) % MOD ; set < int > s ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < 40 ) { s . insert ( i ) ; update ( i , fact [ arr [ i ] ] , n ) ; } else update ( i , 0 , n ) ; } for ( int i = 0 ; i < q ; i ++ ) { if ( que [ i ] . type == 1 ) { while ( true ) { auto it = s . lower_bound ( que [ i ] . l ) ; if ( it == s . end ( ) * it > que [ i ] . r ) break ; que [ i ] . l = * it ; int val = arr [ * it ] + 1 ; update ( * it , fact [ val ] - fact [ arr [ * it ] ] , n ) ; arr [ * it ] ++ ; if ( arr [ * it ] >= 40 ) s . erase ( * it ) ; que [ i ] . l ++ ; } } else if ( que [ i ] . type == 2 ) { int idx = que [ i ] . l ; int val = que [ i ] . r ; update ( idx , fact [ val ] - fact [ arr [ idx ] ] , n ) ; arr [ idx ] = val ; if ( val < 40 ) s . insert ( idx ) ; else s . erase ( idx ) ; } else cout << ( sum ( que [ i ] . r ) - sum ( que [ i ] . l - 1 ) ) << endl ; } } int main ( ) { int q = 6 ; int arr [ ] = { 0 , 1 , 2 , 1 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; queries que [ q + 1 ] ; que [ 0 ] . type = 3 , que [ 0 ] . l = 1 , que [ 0 ] . r = 5 ; que [ 1 ] . type = 1 , que [ 1 ] . l = 1 , que [ 1 ] . r = 3 ; que [ 2 ] . type = 2 , que [ 2 ] . l = 2 , que [ 2 ] . r = 4 ; que [ 3 ] . type = 3 , que [ 3 ] . l = 2 , que [ 3 ] . r = 4 ; que [ 4 ] . type = 1 , que [ 4 ] . l = 2 , que [ 4 ] . r = 5 ; que [ 5 ] . type = 3 , que [ 5 ] . l = 1 , que [ 5 ] . r = 5 ; answerQueries ( arr , que , n , q ) ; return 0 ; } |
Numbers whose factorials end with n zeros | Binary search based CPP program to find numbers with n trailing zeros . ; Function to calculate trailing zeros ; binary search for first number with n trailing zeros ; Print all numbers after low with n trailing zeros . ; Print result ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int trailingZeroes ( int n ) { int cnt = 0 ; while ( n > 0 ) { n /= 5 ; cnt += n ; } return cnt ; } void binarySearch ( int n ) { int low = 0 ; while ( low < high ) { int mid = ( low + high ) / 2 ; int count = trailingZeroes ( mid ) ; if ( count < n ) low = mid + 1 ; else high = mid ; } vector < int > result ; while ( trailingZeroes ( low ) == n ) { result . push_back ( low ) ; low ++ ; } for ( int i = 0 ; i < result . size ( ) ; i ++ ) cout << result [ i ] << " β " ; } int main ( ) { int n = 2 ; binarySearch ( n ) ; return 0 ; } |
Number of days after which tank will become empty | C / C ++ code to find number of days after which tank will become empty ; Utility method to get sum of first n numbers ; Method returns minimum number of days after which tank will become empty ; if water filling is more than capacity then after C days only tank will become empty ; initialize binary search variable ; loop until low is less than high ; if cumulate sum is greater than ( C - l ) then search on left side ; if ( C - l ) is more then search on right side ; final answer will be obtained by adding l to binary search result ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getCumulateSum ( int n ) { return ( n * ( n + 1 ) ) / 2 ; } int minDaysToEmpty ( int C , int l ) { if ( C <= l ) return C ; int lo = 0 ; int hi = 1e4 ; int mid ; while ( lo < hi ) { mid = ( lo + hi ) / 2 ; if ( getCumulateSum ( mid ) >= ( C - l ) ) hi = mid ; else lo = mid + 1 ; } return ( l + lo ) ; } int main ( ) { int C = 5 ; int l = 2 ; cout << minDaysToEmpty ( C , l ) << endl ; return 0 ; } |
Number of days after which tank will become empty | C / C ++ code to find number of days after which tank will become empty ; Method returns minimum number of days after which tank will become empty ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDaysToEmpty ( int C , int l ) { if ( l >= C ) return C ; double eq_root = ( std :: sqrt ( 1 + 8 * ( C - l ) ) - 1 ) / 2 ; return std :: ceil ( eq_root ) + l ; } int main ( ) { cout << minDaysToEmpty ( 5 , 2 ) << endl ; cout << minDaysToEmpty ( 6514683 , 4965 ) << endl ; return 0 ; } |
K | Program to find kth element from two sorted arrays ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int kth ( int arr1 [ ] , int arr2 [ ] , int m , int n , int k ) { int sorted1 [ m + n ] ; int i = 0 , j = 0 , d = 0 ; while ( i < m && j < n ) { if ( arr1 [ i ] < arr2 [ j ] ) sorted1 [ d ++ ] = arr1 [ i ++ ] ; else sorted1 [ d ++ ] = arr2 [ j ++ ] ; } while ( i < m ) sorted1 [ d ++ ] = arr1 [ i ++ ] ; while ( j < n ) sorted1 [ d ++ ] = arr2 [ j ++ ] ; return sorted1 [ k - 1 ] ; } int main ( ) { int arr1 [ 5 ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ 4 ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; cout << kth ( arr1 , arr2 , 5 , 4 , k ) ; return 0 ; } |
K | Program to find k - th element from two sorted arrays | #include <iostream> NEW_LINE using namespace std ; int kth ( int * arr1 , int * arr2 , int * end1 , int * end2 , int k ) { if ( arr1 == end1 ) return arr2 [ k ] ; if ( arr2 == end2 ) return arr1 [ k ] ; int mid1 = ( end1 - arr1 ) / 2 ; int mid2 = ( end2 - arr2 ) / 2 ; if ( mid1 + mid2 < k ) { if ( arr1 [ mid1 ] > arr2 [ mid2 ] ) return kth ( arr1 , arr2 + mid2 + 1 , end1 , end2 , k - mid2 - 1 ) ; else return kth ( arr1 + mid1 + 1 , arr2 , end1 , end2 , k - mid1 - 1 ) ; } else { if ( arr1 [ mid1 ] > arr2 [ mid2 ] ) return kth ( arr1 , arr2 , arr1 + mid1 , end2 , k ) ; else return kth ( arr1 , arr2 , end1 , arr2 + mid2 , k ) ; } } int main ( ) { int arr1 [ 5 ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ 4 ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; cout << kth ( arr1 , arr2 , arr1 + 5 , arr2 + 4 , k - 1 ) ; return 0 ; } |
K | C ++ Program to find kth element from two sorted arrays ; In case we have reached end of array 1 ; In case we have reached end of array 2 ; k should never reach 0 or exceed sizes of arrays ; Compare first elements of arrays and return ; Size of array 1 is less than k / 2 ; Last element of array 1 is not kth We can directly return the ( k - m ) th element in array 2 ; Size of array 2 is less than k / 2 ; Normal comparison , move starting index of one array k / 2 to the right ; Driver code | #include <iostream> NEW_LINE using namespace std ; int kth ( int arr1 [ ] , int arr2 [ ] , int m , int n , int k , int st1 = 0 , int st2 = 0 ) { if ( st1 == m ) return arr2 [ st2 + k - 1 ] ; if ( st2 == n ) return arr1 [ st1 + k - 1 ] ; if ( k == 0 || k > ( m - st1 ) + ( n - st2 ) ) return -1 ; if ( k == 1 ) return ( arr1 [ st1 ] < arr2 [ st2 ] ) ? arr1 [ st1 ] : arr2 [ st2 ] ; int curr = k / 2 ; if ( curr - 1 >= m - st1 ) { if ( arr1 [ m - 1 ] < arr2 [ st2 + curr - 1 ] ) return arr2 [ st2 + ( k - ( m - st1 ) - 1 ) ] ; else return kth ( arr1 , arr2 , m , n , k - curr , st1 , st2 + curr ) ; } if ( curr - 1 >= n - st2 ) { if ( arr2 [ n - 1 ] < arr1 [ st1 + curr - 1 ] ) return arr1 [ st1 + ( k - ( n - st2 ) - 1 ) ] ; else return kth ( arr1 , arr2 , m , n , k - curr , st1 + curr , st2 ) ; } else { if ( arr1 [ curr + st1 - 1 ] < arr2 [ curr + st2 - 1 ] ) return kth ( arr1 , arr2 , m , n , k - curr , st1 + curr , st2 ) ; else return kth ( arr1 , arr2 , m , n , k - curr , st1 , st2 + curr ) ; } } int main ( ) { int arr1 [ 5 ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ 4 ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; cout << kth ( arr1 , arr2 , 5 , 4 , k ) ; return 0 ; } |
K | C ++ Program to find kth element from two sorted arrays Time Complexity : O ( log k ) ; let m <= n ; Check if arr1 is empty returning k - th element of arr2 ; Check if k = 1 return minimum of first two elements of both arrays ; Now the divide and conquer part ; Now we need to find only k - j th element since we have found out the lowest j ; Now we need to find only k - i th element since we have found out the lowest i ; Driver code | #include <iostream> NEW_LINE using namespace std ; int kth ( int arr1 [ ] , int m , int arr2 [ ] , int n , int k ) { if ( k > ( m + n ) k < 1 ) return -1 ; if ( m > n ) return kth ( arr2 , n , arr1 , m , k ) ; if ( m == 0 ) return arr2 [ k - 1 ] ; if ( k == 1 ) return min ( arr1 [ 0 ] , arr2 [ 0 ] ) ; int i = min ( m , k / 2 ) , j = min ( n , k / 2 ) ; if ( arr1 [ i - 1 ] > arr2 [ j - 1 ] ) return kth ( arr1 , m , arr2 + j , n - j , k - j ) ; else return kth ( arr1 + i , m - i , arr2 , n , k - i ) ; } int main ( ) { int arr1 [ 5 ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ 4 ] = { 1 , 4 , 8 , 10 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int k = 5 ; int ans = kth ( arr1 , m , arr2 , n , k ) ; if ( ans == -1 ) cout << " Invalid β query " ; else cout << ans ; return 0 ; } |
K | C ++ Program to find kth element from two sorted arrays ; Function to find K - th min ; Declaring a min heap ; Pushing elements for array a to min - heap ; Pushing elements for array b to min - heap ; Poping - out K - 1 elements ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int kth ( int * a , int * b , int n , int m , int k ) { priority_queue < int , vector < int > , greater < int > > pq ; for ( int i = 0 ; i < n ; i ++ ) { pq . push ( a [ i ] ) ; } for ( int i = 0 ; i < m ; i ++ ) { pq . push ( b [ i ] ) ; } while ( k -- > 1 ) { pq . pop ( ) ; } return pq . top ( ) ; } int main ( ) { int arr1 [ 5 ] = { 2 , 3 , 6 , 7 , 9 } ; int arr2 [ 4 ] = { 1 , 4 , 8 , 10 } ; int k = 5 ; cout << kth ( arr1 , arr2 , 5 , 4 , k ) ; return 0 ; } |
Search element in a sorted matrix | C ++ implementation to search an element in a sorted matrix ; This function does Binary search for x in i - th row . It does the search from mat [ i ] [ j_low ] to mat [ i ] [ j_high ] ; Element found ; element not found ; Function to perform binary search on the mid values of row to get the desired pair of rows where the element can be found ; Single row matrix ; Do binary search in middle column . Condition to terminate the loop when the 2 desired rows are found ; element found ; If element is present on the mid of the two rows ; search element on 1 st half of 1 st row ; Search element on 2 nd half of 1 st row ; Search element on 1 st half of 2 nd row ; search element on 2 nd half of 2 nd row ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100 ; void binarySearch ( int mat [ ] [ MAX ] , int i , int j_low , int j_high , int x ) { while ( j_low <= j_high ) { int j_mid = ( j_low + j_high ) / 2 ; if ( mat [ i ] [ j_mid ] == x ) { cout << " Found β at β ( " << i << " , β " << j_mid << " ) " ; return ; } else if ( mat [ i ] [ j_mid ] > x ) j_high = j_mid - 1 ; else j_low = j_mid + 1 ; } cout << " Element β no β found " ; } void sortedMatrixSearch ( int mat [ ] [ MAX ] , int n , int m , int x ) { if ( n == 1 ) { binarySearch ( mat , 0 , 0 , m - 1 , x ) ; return ; } int i_low = 0 ; int i_high = n - 1 ; int j_mid = m / 2 ; while ( ( i_low + 1 ) < i_high ) { int i_mid = ( i_low + i_high ) / 2 ; if ( mat [ i_mid ] [ j_mid ] == x ) { cout << " Found β at β ( " << i_mid << " , β " << j_mid << " ) " ; return ; } else if ( mat [ i_mid ] [ j_mid ] > x ) i_high = i_mid ; else i_low = i_mid ; } if ( mat [ i_low ] [ j_mid ] == x ) cout << " Found β at β ( " << i_low << " , " << j_mid << " ) " ; else if ( mat [ i_low + 1 ] [ j_mid ] == x ) cout << " Found β at β ( " << ( i_low + 1 ) << " , β " << j_mid << " ) " ; else if ( x <= mat [ i_low ] [ j_mid - 1 ] ) binarySearch ( mat , i_low , 0 , j_mid - 1 , x ) ; else if ( x >= mat [ i_low ] [ j_mid + 1 ] && x <= mat [ i_low ] [ m - 1 ] ) binarySearch ( mat , i_low , j_mid + 1 , m - 1 , x ) ; else if ( x <= mat [ i_low + 1 ] [ j_mid - 1 ] ) binarySearch ( mat , i_low + 1 , 0 , j_mid - 1 , x ) ; else binarySearch ( mat , i_low + 1 , j_mid + 1 , m - 1 , x ) ; } int main ( ) { int n = 4 , m = 5 , x = 8 ; int mat [ ] [ MAX ] = { { 0 , 6 , 8 , 9 , 11 } , { 20 , 22 , 28 , 29 , 31 } , { 36 , 38 , 50 , 61 , 63 } , { 64 , 66 , 100 , 122 , 128 } } ; sortedMatrixSearch ( mat , n , m , x ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.