text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Generate all possible permutations of a Number divisible by N | Function to generate all permutations and print the ones that are divisible by the N ; Convert string to integer ; Check for divisibility and print it ; Print all the permutations ; Swap characters ; Permute remaining characters ; Revoke the swaps ; Driver Code | def permute ( st , l , r , n ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT p = ' ' . join ( st ) NEW_LINE j = int ( p ) NEW_LINE if ( j % n == 0 ) : NEW_LINE INDENT print ( p ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( l , r ) : NEW_LINE INDENT st [ l ] , st [ i ] = st [ i ] , st [ l ] NEW_LINE permute ( st , l + 1 , r , n ) NEW_LINE st [ l ] , st [ i ] = st [ i ] , st [ l ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "125" NEW_LINE n = 5 NEW_LINE length = len ( st ) NEW_LINE if ( length > 0 ) : NEW_LINE p = list ( st ) NEW_LINE permute ( p , 0 , length , n ) ; NEW_LINE DEDENT |
Check if binary representations of 0 to N are present as substrings in given binary string | Function to convert decimal to binary representation ; Iterate over all bits of N ; If bit is 1 ; Return binary representation ; Function to check if binary conversion of numbers from N to 1 exists in the string as a substring or not ; To store the count of number exists as a substring ; Traverse from N to 1 ; If current number is not present in map ; Store current number ; Find binary of t ; If the string s is a substring of str ; Mark t as true ; Increment the count ; Update for t / 2 ; Special judgment '0 ; If the count is N + 1 , return " yes " ; Driver Code ; Given String ; Given Number ; Function Call | def decimalToBinary ( N ) : NEW_LINE INDENT ans = " " NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT ans = '1' + ans NEW_LINE DEDENT else : NEW_LINE INDENT ans = '0' + ans NEW_LINE DEDENT N //= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT def checkBinaryString ( str , N ) : NEW_LINE INDENT map = [ 0 ] * ( N + 10 ) NEW_LINE cnt = 0 NEW_LINE for i in range ( N , - 1 , - 1 ) : NEW_LINE INDENT if ( not map [ i ] ) : NEW_LINE INDENT t = i NEW_LINE s = decimalToBinary ( t ) NEW_LINE if ( s in str ) : NEW_LINE INDENT while ( t and not map [ t ] ) : NEW_LINE INDENT map [ t ] = 1 NEW_LINE cnt += 1 NEW_LINE t >>= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT cnt += 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( cnt == N + 1 ) : NEW_LINE INDENT return " True " NEW_LINE DEDENT else : NEW_LINE INDENT return " False " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "0110" NEW_LINE N = 3 NEW_LINE print ( checkBinaryString ( str , N ) ) NEW_LINE DEDENT |
Find the word with most anagrams in a given sentence | Function to find the word with maximum number of anagrams ; Primes assigned to 26 alphabets ; Stores the product and word mappings ; Stores the frequencies of products ; Calculate the product of primes assigned ; If product already exists ; Otherwise ; Fetch the most frequent product ; Return a string with that product ; Driver Code | def largestAnagramGrp ( arr ) : NEW_LINE INDENT prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 , 101 ] NEW_LINE max = - 1 NEW_LINE maxpdt = - 1 NEW_LINE W = { } NEW_LINE P = { } NEW_LINE for temp in arr : NEW_LINE INDENT c = [ i for i in temp ] NEW_LINE pdt = 1 NEW_LINE for t in c : NEW_LINE INDENT pdt *= prime [ ord ( t ) - ord ( ' a ' ) ] NEW_LINE DEDENT if ( pdt in P ) : NEW_LINE INDENT P [ pdt ] = P . get ( pdt , 0 ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT W [ pdt ] = temp NEW_LINE P [ pdt ] = 1 NEW_LINE DEDENT DEDENT for e in P : NEW_LINE INDENT if ( max < P [ e ] ) : NEW_LINE INDENT max = P [ e ] NEW_LINE maxpdt = e NEW_LINE DEDENT DEDENT return W [ maxpdt ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " please β be β silent β and β listen β to β what β the β professor β says " NEW_LINE arr = S . split ( " β " ) NEW_LINE print ( largestAnagramGrp ( arr ) ) NEW_LINE DEDENT |
Replace every vowels with lexicographically next vowel in a String | Function to replace every vowel with next vowel lexicographically ; Storing the vowels in the map with custom numbers showing their index ; Iterate over the string ; If the current character is a vowel Find the index in Hash and Replace it with next vowel from Hash ; Driver function | def print_next_vovel_string ( st ) : NEW_LINE INDENT m = { } NEW_LINE m [ ' a ' ] = 0 NEW_LINE m [ ' e ' ] = 1 NEW_LINE m [ ' i ' ] = 2 NEW_LINE m [ ' o ' ] = 3 NEW_LINE m [ ' u ' ] = 4 NEW_LINE arr = [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] NEW_LINE N = len ( st ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT c = st [ i ] NEW_LINE if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT index = m [ st [ i ] ] + 1 NEW_LINE newindex = index % 5 NEW_LINE st = st . replace ( st [ i ] , arr [ newindex ] , 1 ) NEW_LINE DEDENT DEDENT return st NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " geeksforgeeks " NEW_LINE print ( print_next_vovel_string ( st ) ) NEW_LINE DEDENT |
Check if string is palindrome after removing all consecutive duplicates | Function to check if a string is palindrome or not ; Length of the string ; Check if its a palindrome ; If the palindromic condition is not met ; Return true as Str is palindromic ; Function to check if string str is palindromic after removing every consecutive characters from the str ; Length of the string str ; Create an empty compressed string ; The first character will always be included in final string ; Check all the characters of the string ; If the current character is not same as its previous one , then insert it in the final string ; Check if the compressed string is a palindrome ; Driver Code ; Given string ; Function call | def isPalindrome ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( Str [ i ] != Str [ Len - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isCompressablePalindrome ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE compressed = " " NEW_LINE compressed += Str [ 0 ] NEW_LINE for i in range ( 1 , Len ) : NEW_LINE INDENT if ( Str [ i ] != Str [ i - 1 ] ) : NEW_LINE INDENT compressed += Str [ i ] NEW_LINE DEDENT DEDENT return isPalindrome ( compressed ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = " abbcbbbaaa " NEW_LINE if ( isCompressablePalindrome ( Str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count of substrings consisting only of vowels | function to check vowel or not ; Function to Count all substrings in a string which contains only vowels ; if current character is vowel ; increment ; Count all possible substring of calculated length ; Reset the length ; Add remaining possible substrings consisting of vowels occupying last indices of the string ; Driver Program | def isvowel ( ch ) : NEW_LINE INDENT return ( ch in " aeiou " ) NEW_LINE DEDENT def CountTotal ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE n = len ( s ) NEW_LINE cnt = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( isvowel ( s [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( cnt * ( cnt + 1 ) // 2 ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT if ( cnt != 0 ) : NEW_LINE INDENT ans += ( cnt * ( cnt + 1 ) // 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE print ( CountTotal ( s ) ) NEW_LINE |
Number formed by flipping all bits to the left of rightmost set bit | Function to get the total count ; Moving until we get the rightmost set bit ; To get total number of bits in a number ; Function to find the integer formed after flipping all bits to the left of the rightmost set bit ; Find the total count of bits and the rightmost set bit ; XOR given number with the number which has is made up of only totbits set ; To avoid flipping the bits to the right of the set bit , take XOR with the number made up of only set firstbits ; Driver Code | def getTotCount ( num ) : NEW_LINE INDENT totCount = 1 NEW_LINE firstCount = 1 NEW_LINE temp = 1 NEW_LINE while ( not ( num & temp ) ) : NEW_LINE INDENT temp = temp << 1 NEW_LINE totCount += 1 NEW_LINE DEDENT firstCount = totCount NEW_LINE temp = num >> totCount NEW_LINE while ( temp ) : NEW_LINE INDENT totCount += 1 NEW_LINE temp = temp >> 1 NEW_LINE DEDENT return totCount , firstCount NEW_LINE DEDENT def flipBitsFromRightMostSetBit ( num ) : NEW_LINE INDENT totbit , firstbit = getTotCount ( num ) NEW_LINE num1 = num ^ ( ( 1 << totbit ) - 1 ) NEW_LINE num1 = num1 ^ ( ( 1 << firstbit ) - 1 ) NEW_LINE return num1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 120 NEW_LINE print ( flipBitsFromRightMostSetBit ( n ) ) NEW_LINE DEDENT |
Longest substring of vowels with no two adjacent alphabets same | Function to check a character is vowel or not ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid subString ; Stores length of current valid subString ; If curr and prev character are not same , include it ; If same as prev one , start new subString from here ; Store max in maxLen ; Driver code | def isVowel ( x ) : NEW_LINE INDENT return ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' ) ; NEW_LINE DEDENT def findMaxLen ( s ) : NEW_LINE INDENT maxLen = 0 NEW_LINE cur = 0 NEW_LINE if ( isVowel ( s [ 0 ] ) ) : NEW_LINE INDENT maxLen = 1 ; NEW_LINE DEDENT cur = maxLen NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) ) : NEW_LINE INDENT if ( s [ i ] != s [ i - 1 ] ) : NEW_LINE INDENT cur += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cur = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT cur = 0 ; NEW_LINE DEDENT maxLen = max ( cur , maxLen ) ; NEW_LINE DEDENT return maxLen NEW_LINE DEDENT Str = " aeoibsddaeiouudb " NEW_LINE print ( findMaxLen ( Str ) ) NEW_LINE |
Count of non | Iterative Function to calculate base ^ pow in O ( log y ) ; Function to return the count of non palindromic strings ; Count of strings using n characters with repetitions allowed ; Count of palindromic strings ; Count of non - palindromic strings ; Driver code | def power ( base , pwr ) : NEW_LINE INDENT res = 1 NEW_LINE while ( pwr > 0 ) : NEW_LINE INDENT if ( pwr & 1 ) : NEW_LINE INDENT res = res * base NEW_LINE DEDENT base = base * base NEW_LINE pwr >>= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def countNonPalindromicString ( n , m ) : NEW_LINE INDENT total = power ( n , m ) NEW_LINE palindrome = power ( n , m // 2 + m % 2 ) NEW_LINE count = total - palindrome NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE m = 5 NEW_LINE print ( countNonPalindromicString ( n , m ) ) NEW_LINE DEDENT |
Count of K | To store the frequency array ; Function to check palindromic of of any substring using frequency array ; Initialise the odd count ; Traversing frequency array to compute the count of characters having odd frequency ; Returns true if odd count is atmost 1 ; Function to count the total number substring whose any permutations are palindromic ; Computing the frequency of first K character of the string ; To store the count of palindromic permutations ; Checking for the current window if it has any palindromic permutation ; Start and end poof window ; Decrementing count of first element of the window ; Incrementing count of next element of the window ; Checking current window character frequency count ; Return the final count ; Given string str ; Window of size K ; Function call | freq = [ 0 ] * 26 NEW_LINE def checkPalindrome ( ) : NEW_LINE INDENT oddCnt = 0 NEW_LINE for x in freq : NEW_LINE INDENT if ( x % 2 == 1 ) : NEW_LINE INDENT oddCnt += 1 NEW_LINE DEDENT DEDENT return oddCnt <= 1 NEW_LINE DEDENT def countPalindromePermutation ( s , k ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - 97 ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE if ( checkPalindrome ( ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT i = 0 NEW_LINE j = k NEW_LINE while ( j < len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - 97 ] -= 1 NEW_LINE i += 1 NEW_LINE freq [ ord ( s [ j ] ) - 97 ] += 1 NEW_LINE j += 1 NEW_LINE if ( checkPalindrome ( ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT str = " abbaca " NEW_LINE K = 3 NEW_LINE print ( countPalindromePermutation ( str , K ) ) NEW_LINE |
Minimum flips required to form given binary string where every flip changes all bits to its right as well | Function to return the count of minimum flips required ; If curr occurs in the final string ; Switch curr to '0' if '1' or vice - versa ; Driver Code | def minFlips ( target ) : NEW_LINE INDENT curr = '1' NEW_LINE count = 0 NEW_LINE for i in range ( len ( target ) ) : NEW_LINE INDENT if ( target [ i ] == curr ) : NEW_LINE INDENT count += 1 NEW_LINE curr = chr ( 48 + ( ord ( curr ) + 1 ) % 2 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "011000" NEW_LINE print ( minFlips ( S ) ) NEW_LINE DEDENT |
Check if a number ends with another number or not | Python3 program for the above approach ; Function to check if B is a suffix of A or not ; Find the number of digit in B ; Subtract B from A ; Returns true , if B is a suffix of A ; Given numbers ; Function Call ; If B is a suffix of A , then print " Yes " | import math NEW_LINE def checkSuffix ( A , B ) : NEW_LINE INDENT digit_B = int ( math . log10 ( B ) ) + 1 ; NEW_LINE A -= B ; NEW_LINE return ( A % int ( math . pow ( 10 , digit_B ) ) ) ; NEW_LINE DEDENT A = 12345 ; B = 45 ; NEW_LINE result = checkSuffix ( A , B ) ; NEW_LINE if ( result == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Minimum length of substring whose rotation generates a palindromic substring | Python3 program to find the minimum length of substring whose rotation generates a palindromic substring ; Function to return the minimum length of substring ; Store the index of previous occurrence of the character ; Variable to store the maximum length of substring ; If the current character hasn 't appeared yet ; If the character has occured within one or two previous index , a palindromic substring already exists ; Update the maximum ; Replace the previous index of the character by the current index ; If character appeared at least twice ; Driver Code | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def count_min_length ( s ) : NEW_LINE INDENT hash = [ 0 ] * 26 ; NEW_LINE ans = sys . maxsize ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT hash [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_LINE INDENT hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] == i - 1 or hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] == i - 2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT ans = min ( ans , i - hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] - 1 ) ; NEW_LINE hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i ; NEW_LINE DEDENT DEDENT if ( ans == INT_MAX ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcdeba " ; NEW_LINE print ( count_min_length ( string ) ) ; NEW_LINE DEDENT |
Program to remove HTML tags from a given String | Python3 program for the above approach ; Function to remove the HTML tags from the given tags ; Print string after removing tags ; Driver code ; Given String ; Function call to print the HTML string after removing tags | import re NEW_LINE def RemoveHTMLTags ( strr ) : NEW_LINE INDENT print ( re . compile ( r ' < [ ^ > ] + > ' ) . sub ( ' ' , strr ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " < div > < b > Geeks β for β Geeks < / b > < / div > " NEW_LINE RemoveHTMLTags ( strr ) ; NEW_LINE DEDENT |
Score of Parentheses using Tree | Customized tree class or struct , contains all required methods . ; Function to add a child into the list of children ; Function to change the parent pointer to the node passed ; Function to return the parent of the current node ; Function to compute the score recursively . ; Base case ; Adds scores of all children ; Function to create the tree structure ; Creating a node for every " ( ) " ; If we find " ( " we add a node as a child ; On finding " ) " which confirms that a pair is closed , we go back to the parent ; Driver code ; Generating the tree ; Computing the score | class TreeNode : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . parent = None NEW_LINE self . children = [ ] NEW_LINE DEDENT def addChild ( self , node ) : NEW_LINE INDENT self . children . append ( node ) ; NEW_LINE DEDENT def setParent ( self , node ) : NEW_LINE INDENT self . parent = node ; NEW_LINE DEDENT def getParent ( self ) : NEW_LINE INDENT return self . parent ; NEW_LINE DEDENT def computeScore ( self ) : NEW_LINE INDENT if ( len ( self . children ) == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT res = 0 ; NEW_LINE for curr in self . children : NEW_LINE INDENT res += curr . computeScore ( ) ; NEW_LINE DEDENT if ( self . parent == None ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT else : NEW_LINE INDENT return 2 * res ; NEW_LINE DEDENT DEDENT DEDENT def computeTree ( s ) : NEW_LINE INDENT current = TreeNode ( ) ; NEW_LINE root = current ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT child = TreeNode ( ) ; NEW_LINE child . setParent ( current ) ; NEW_LINE current . addChild ( child ) ; NEW_LINE current = child ; NEW_LINE DEDENT else : NEW_LINE INDENT current = current . getParent ( ) ; NEW_LINE DEDENT DEDENT return root ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " ( ( ) ( ( ) ) ) " ; NEW_LINE root = computeTree ( s ) ; NEW_LINE print ( root . computeScore ( ) ) NEW_LINE DEDENT |
Move all occurrence of letter ' x ' from the string s to the end using Recursion | Recursive program to bring ' x ' to the end ; When the string is completed from reverse direction end of recursion ; If the character x is found ; Transverse the whole string ; Swap the x so that it moves to the last ; Call to the smaller problem now ; Driver code ; Size of a ; Call to rec | def rec ( a , i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT a . pop ( ) NEW_LINE print ( " " . join ( a ) ) NEW_LINE return NEW_LINE DEDENT if ( a [ i ] == ' x ' ) : NEW_LINE j = i NEW_LINE while ( a [ j ] != ' \0' and a [ j + 1 ] != ' \0' ) : NEW_LINE INDENT ( a [ j ] , a [ j + 1 ] ) = ( a [ j + 1 ] , a [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT rec ( a , i - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ ' g ' , ' e ' , ' e ' , ' k ' , ' x ' , ' s ' , ' x ' , ' x ' , ' k ' , ' s ' , ' \0' ] NEW_LINE n = 10 NEW_LINE rec ( a , n - 1 ) NEW_LINE DEDENT |
Find the largest Alphabetic character present in the string | Function to find the Largest Alphabetic Character ; Array for keeping track of both uppercase and lowercase english alphabets ; Iterate from right side of array to get the largest index character ; Check for the character if both its uppercase and lowercase exist or not ; Return - 1 if no such character whose uppercase and lowercase present in string str ; Driver code | def largestCharacter ( str ) : NEW_LINE INDENT uppercase = [ False ] * 26 NEW_LINE lowercase = [ False ] * 26 NEW_LINE arr = list ( str ) NEW_LINE for c in arr : NEW_LINE INDENT if ( c . islower ( ) ) : NEW_LINE INDENT lowercase [ ord ( c ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT if ( c . isupper ( ) ) : NEW_LINE INDENT uppercase [ ord ( c ) - ord ( ' A ' ) ] = True NEW_LINE DEDENT DEDENT for i in range ( 25 , - 1 , - 1 ) : NEW_LINE INDENT if ( uppercase [ i ] and lowercase [ i ] ) : NEW_LINE INDENT return chr ( i + ord ( ' A ' ) ) + " " NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT str = " admeDCAB " NEW_LINE print ( largestCharacter ( str ) ) NEW_LINE |
Print string after removing all ( β 10 β or β 01 β ) from the binary string | Function to print the final string after removing all the occurrences of "10" and "01" from the given binary string ; Variables to store the count of 1 ' s β and β 0' s ; Length of the string ; For loop to count the occurrences of 1 ' s β and β 0' s in the string ; To check if the count of 1 ' s β is β β greater β than β the β count β of β 0' s or not . If x is greater , then those many 1 's are printed. ; Length of the final remaining string after removing all the occurrences ; Printing the final string ; Driver Code | def finalString ( st ) : NEW_LINE INDENT x , y = 0 , 0 NEW_LINE n = len ( st ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == '1' ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT if ( x > y ) : NEW_LINE INDENT left = 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = 0 NEW_LINE DEDENT length = n - 2 * min ( x , y ) ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT print ( left , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "010110100100000" NEW_LINE finalString ( st ) NEW_LINE DEDENT |
Longest palindrome formed by concatenating and reordering strings of equal length | Function to print the longest palindrome ; Printing every string in left vector ; Printing the palindromic string in the middle ; Printing the reverse of the right vector to make the final output palindromic ; Function to find and print the longest palindrome that can be formed ; Inserting each string in the set ; Vectors to add the strings in the left and right side ; To add the already present palindrome string in the middle of the solution ; Iterating through all the given strings ; If the string is a palindrome it is added in the middle ; Checking if the reverse of the string is already present in the set ; Driver code | def printPalindrome ( left , mid , right ) : NEW_LINE INDENT for x in left : NEW_LINE INDENT print ( x , end = " " ) NEW_LINE DEDENT print ( mid , end = " " ) NEW_LINE right = right [ : : - 1 ] NEW_LINE for x in right : NEW_LINE INDENT print ( x , end = " " ) NEW_LINE DEDENT print ( ' ' , end = " " ) NEW_LINE DEDENT def findPalindrome ( S , N , M ) : NEW_LINE INDENT d = set ( ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT d . add ( S [ i ] ) NEW_LINE DEDENT left = [ ] NEW_LINE right = [ ] NEW_LINE mid = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT t = S [ i ] NEW_LINE t = t [ : : - 1 ] NEW_LINE if ( t == S [ i ] ) : NEW_LINE INDENT mid = t NEW_LINE DEDENT elif ( t in d ) : NEW_LINE INDENT left . append ( S [ i ] ) NEW_LINE right . append ( t ) NEW_LINE d . remove ( S [ i ] ) NEW_LINE d . remove ( t ) NEW_LINE DEDENT DEDENT printPalindrome ( left , mid , right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = [ " tab " , " one " , " bat " ] NEW_LINE M = 3 NEW_LINE N = len ( S ) NEW_LINE findPalindrome ( S , N , M ) NEW_LINE DEDENT |
Lexicographically smaller string by swapping at most one character pair | Function that finds whether is it possible to make string A lexicographically smaller than string B ; Condition if string A is already smaller than B ; Sorting temp string ; Condition for first changed character of string A and temp ; Condition if string A is already sorted ; Finding first changed character from last of string A ; Swap the two characters ; Condition if string A is smaller than B ; Driver Code | def IsLexicographicallySmaller ( A , B ) : NEW_LINE INDENT if ( A < B ) : NEW_LINE INDENT return True NEW_LINE DEDENT temp = A NEW_LINE temp = ' ' . join ( sorted ( temp ) ) NEW_LINE index = - 1 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] != temp [ i ] ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] == temp [ index ] ) : NEW_LINE INDENT j = i NEW_LINE DEDENT DEDENT A = list ( A ) NEW_LINE A [ index ] , A [ j ] = A [ j ] , A [ index ] NEW_LINE A = ' ' . join ( A ) NEW_LINE if ( A < B ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT A = " AGAIN " NEW_LINE B = " ACTION " NEW_LINE if ( IsLexicographicallySmaller ( A , B ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Length of longest palindromic sub | Function to find maximum of the two variables ; Function to find the longest palindromic substring : Recursion ; Base condition when the start index is greater than end index ; Base condition when both the start and end index are equal ; Condition when corner characters are equal in the string ; Recursive call to find the longest Palindromic string by excluding the corner characters ; Recursive call to find the longest Palindromic string by including one corner character at a time ; Function to find the longest palindromic sub - string ; Utility function call ; Driver Code ; Function Call | def maxi ( x , y ) : NEW_LINE INDENT if x > y : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return y NEW_LINE DEDENT DEDENT def longestPalindromic ( strn , i , j , count ) : NEW_LINE INDENT if i > j : NEW_LINE INDENT return count NEW_LINE DEDENT if i == j : NEW_LINE INDENT return ( count + 1 ) NEW_LINE DEDENT if strn [ i ] == strn [ j ] : NEW_LINE INDENT count = longestPalindromic ( strn , i + 1 , j - 1 , count + 2 ) NEW_LINE return maxi ( count , maxi ( longestPalindromic ( strn , i + 1 , j , 0 ) , longestPalindromic ( strn , i , j - 1 , 0 ) ) ) NEW_LINE DEDENT return maxi ( longestPalindromic ( strn , i + 1 , j , 0 ) , longestPalindromic ( strn , i , j - 1 , 0 ) ) NEW_LINE DEDENT def longest_palindromic_substr ( strn ) : NEW_LINE INDENT k = len ( strn ) - 1 NEW_LINE return longestPalindromic ( strn , 0 , k , 0 ) NEW_LINE DEDENT strn = " aaaabbaa " NEW_LINE print ( longest_palindromic_substr ( strn ) ) NEW_LINE |
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency | Function to find the maximum possible prefix of the string ; Hash map to store the frequency of the characters in the string ; Iterate over the string to find the occurence of each Character ; Minimum frequency of the Characters ; Loop to find the count of minimum frequency in the hash - map ; Loop to find the maximum possible length of the prefix in the string ; Condition to check if the frequency is greater than minimum possible freq ; maxprefix string and its length . ; Driver code ; String is initialize . ; str is passed in MaxPrefix function . | def MaxPrefix ( string ) : NEW_LINE INDENT Dict = { } NEW_LINE maxprefix = 0 NEW_LINE for i in string : NEW_LINE INDENT Dict [ i ] = Dict . get ( i , 0 ) + 1 NEW_LINE DEDENT minfrequency = min ( Dict . values ( ) ) NEW_LINE countminFrequency = 0 NEW_LINE for x in Dict : NEW_LINE INDENT if ( Dict [ x ] == minfrequency ) : NEW_LINE INDENT countminFrequency += 1 NEW_LINE DEDENT DEDENT mapper = { } NEW_LINE indi = 0 NEW_LINE for i in string : NEW_LINE INDENT mapper [ i ] = mapper . get ( i , 0 ) + 1 NEW_LINE if ( mapper [ i ] > countminFrequency ) : NEW_LINE INDENT break NEW_LINE DEDENT indi += 1 NEW_LINE DEDENT print ( string [ : indi ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = ' aabcdaab ' NEW_LINE MaxPrefix ( str ) NEW_LINE DEDENT |
Count of Substrings that can be formed without using the given list of Characters | Function to find the Number of sub - strings without using given character ; the freq array ; Count variable to store the count of the characters until a character from given L is encountered ; If a character from L is encountered , then the answer variable is incremented by the value obtained by using the mentioned formula and count is set to 0 ; For last remaining characters ; Driver code | def countSubstring ( S , L , n ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ( ord ( L [ i ] ) - ord ( ' a ' ) ) ] = 1 NEW_LINE DEDENT count , ans = 0 , 0 NEW_LINE for x in S : NEW_LINE INDENT if ( freq [ ord ( x ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT ans += ( count * count + count ) // 2 NEW_LINE count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT ans += ( count * count + count ) // 2 NEW_LINE return ans NEW_LINE DEDENT S = " abcpxyz " NEW_LINE L = [ ' a ' , ' p ' , ' q ' ] NEW_LINE n = len ( L ) NEW_LINE print ( countSubstring ( S , L , n ) ) NEW_LINE |
Program to accept Strings starting with a Vowel | Function to check if first character is vowel ; Function to check ; Driver function | def checkIfStartsWithVowels ( string ) : NEW_LINE INDENT if ( not ( string [ 0 ] == ' A ' or string [ 0 ] == ' a ' or string [ 0 ] == ' E ' or string [ 0 ] == ' e ' or string [ 0 ] == ' I ' or string [ 0 ] == ' i ' or string [ 0 ] == ' O ' or string [ 0 ] == ' o ' or string [ 0 ] == ' U ' or string [ 0 ] == ' u ' ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT def check ( string ) : NEW_LINE INDENT if ( checkIfStartsWithVowels ( string ) ) : NEW_LINE INDENT print ( " Not β Accepted " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Accepted " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " animal " ; NEW_LINE check ( string ) ; NEW_LINE string = " zebra " ; NEW_LINE check ( string ) ; NEW_LINE DEDENT |
Find the Nth occurrence of a character in the given String | Function to find the Nth occurrence of a character ; Loop to find the Nth occurrence of the character ; Driver Code | def findNthOccur ( string , ch , N ) : NEW_LINE INDENT occur = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ch ) : NEW_LINE INDENT occur += 1 ; NEW_LINE DEDENT if ( occur == N ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeks " ; NEW_LINE ch = ' e ' ; NEW_LINE N = 2 ; NEW_LINE print ( findNthOccur ( string , ch , N ) ) ; NEW_LINE DEDENT |
Longest equal substring with cost less than K | Function to find the maximum length ; Fill the prefix array with the difference of letters ; Update the maximum length ; Driver code | def solve ( X , Y , N , K ) : NEW_LINE INDENT count = [ 0 ] * ( N + 1 ) ; NEW_LINE sol = 0 ; NEW_LINE count [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT count [ i ] = ( count [ i - 1 ] + abs ( ord ( X [ i - 1 ] ) - ord ( Y [ i - 1 ] ) ) ) ; NEW_LINE DEDENT j = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT while ( ( count [ i ] - count [ j ] ) > K ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT sol = max ( sol , i - j ) ; NEW_LINE DEDENT return sol ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE X = " abcd " ; NEW_LINE Y = " bcde " ; NEW_LINE K = 3 ; NEW_LINE print ( solve ( X , Y , N , K ) ) ; NEW_LINE DEDENT |
Jaro and Jaro | Python3 implementation of above approach ; Function to calculate the Jaro Similarity of two strings ; If the strings are equal ; Length of two strings ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first string ; Check if there is any matches ; If there is a match ; If there is no match ; Number of transpositions ; Count number of occurrences where two characters match but there is a third matched character in between the indices ; Find the next matched character in second string ; Return the Jaro Similarity ; Jaro Winkler Similarity ; If the jaro Similarity is above a threshold ; Find the length of common prefix ; If the characters match ; Else break ; Maximum of 4 characters are allowed in prefix ; Calculate jaro winkler Similarity ; Driver code ; Print Jaro - Winkler Similarity of two strings | from math import floor NEW_LINE def jaro_distance ( s1 , s2 ) : NEW_LINE INDENT if ( s1 == s2 ) : NEW_LINE INDENT return 1.0 ; NEW_LINE DEDENT len1 = len ( s1 ) ; NEW_LINE len2 = len ( s2 ) ; NEW_LINE if ( len1 == 0 or len2 == 0 ) : NEW_LINE INDENT return 0.0 ; NEW_LINE DEDENT max_dist = ( max ( len ( s1 ) , len ( s2 ) ) // 2 ) - 1 ; NEW_LINE match = 0 ; NEW_LINE hash_s1 = [ 0 ] * len ( s1 ) ; NEW_LINE hash_s2 = [ 0 ] * len ( s2 ) ; NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT for j in range ( max ( 0 , i - max_dist ) , min ( len2 , i + max_dist + 1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ j ] and hash_s2 [ j ] == 0 ) : NEW_LINE INDENT hash_s1 [ i ] = 1 ; NEW_LINE hash_s2 [ j ] = 1 ; NEW_LINE match += 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT if ( match == 0 ) : NEW_LINE INDENT return 0.0 ; NEW_LINE DEDENT t = 0 ; NEW_LINE point = 0 ; NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT if ( hash_s1 [ i ] ) : NEW_LINE INDENT while ( hash_s2 [ point ] == 0 ) : NEW_LINE INDENT point += 1 ; NEW_LINE DEDENT if ( s1 [ i ] != s2 [ point ] ) : NEW_LINE INDENT point += 1 ; NEW_LINE t += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT point += 1 ; NEW_LINE DEDENT DEDENT t /= 2 ; NEW_LINE DEDENT return ( ( match / len1 + match / len2 + ( match - t ) / match ) / 3.0 ) ; NEW_LINE DEDENT def jaro_Winkler ( s1 , s2 ) : NEW_LINE INDENT jaro_dist = jaro_distance ( s1 , s2 ) ; NEW_LINE if ( jaro_dist > 0.7 ) : NEW_LINE INDENT prefix = 0 ; NEW_LINE for i in range ( min ( len ( s1 ) , len ( s2 ) ) ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ i ] ) : NEW_LINE INDENT prefix += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT prefix = min ( 4 , prefix ) ; NEW_LINE jaro_dist += 0.1 * prefix * ( 1 - jaro_dist ) ; NEW_LINE DEDENT return jaro_dist ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " TRATE " ; s2 = " TRACE " ; NEW_LINE print ( " Jaro - Winkler β Similarity β = " , jaro_Winkler ( s1 , s2 ) ) ; NEW_LINE DEDENT |
Check if a word is present in a sentence | Function that returns true if the word is found ; To break the sentence in words ; To temporarily store each individual word ; Comparing the current word with the word to be searched ; Driver code | def isWordPresent ( sentence , word ) : NEW_LINE INDENT s = sentence . split ( " β " ) NEW_LINE for i in s : NEW_LINE INDENT if ( i == word ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s = " Geeks β for β Geeks " NEW_LINE word = " Geeks " NEW_LINE if ( isWordPresent ( s , word ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Check if a word is present in a sentence | Function that returns true if the word is found ; To convert the word in uppercase ; To convert the complete sentence in uppercase ; To break the sentence in words ; To store the individual words of the sentence ; Compare the current word with the word to be searched ; Driver code | def isWordPresent ( sentence , word ) : NEW_LINE INDENT word = word . upper ( ) NEW_LINE sentence = sentence . upper ( ) NEW_LINE s = sentence . split ( ) ; NEW_LINE for temp in s : NEW_LINE INDENT if ( temp == word ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " Geeks β for β Geeks " ; NEW_LINE word = " geeks " ; NEW_LINE if ( isWordPresent ( s , word ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Count of 1 | Function to return the count of required characters ; While there are characters left ; Single bit character ; Two - bit character ; Update the count ; Driver code | def countChars ( string , n ) : NEW_LINE INDENT i = 0 ; cnt = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT i += 2 ; NEW_LINE DEDENT cnt += 1 ; NEW_LINE DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "11010" ; NEW_LINE n = len ( string ) ; NEW_LINE print ( countChars ( string , n ) ) ; NEW_LINE DEDENT |
Print the frequency of each character in Alphabetical order | Python3 implementation of the approach ; Function to print the frequency of each of the characters of s in alphabetical order ; To store the frequency of the characters ; Update the frequency array ; Print the frequency in alphatecial order ; If the current alphabet doesn 't appear in the string ; Driver code | MAX = 26 ; NEW_LINE def compressString ( s , n ) : NEW_LINE INDENT freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT print ( ( chr ) ( i + ord ( ' a ' ) ) , freq [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " ; NEW_LINE n = len ( s ) ; NEW_LINE compressString ( s , n ) ; NEW_LINE DEDENT |
Find the number obtained after concatenation of binary representation of M and N | Python3 implementation of the approach ; Function to convert decimal number n to its binary representation stored as an array arr [ ] ; Funtion to convert the number represented as a binary array arr [ ] its decimal equivalent ; Function to concatenate the binary numbers and return the decimal result ; Number of bits in both the numbers ; Convert the bits in both the gers to the arrays a [ ] and b [ ] ; c [ ] will be the binary array for the result ; Update the c [ ] array ; Return the decimal equivalent of the result ; Driver code | import math NEW_LINE def decBinary ( arr , n ) : NEW_LINE INDENT k = int ( math . log2 ( n ) ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT arr [ k ] = n % 2 NEW_LINE k = k - 1 NEW_LINE n = n // 2 NEW_LINE DEDENT DEDENT def binaryDec ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ans = ans + ( arr [ i ] << ( n - i - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def concat ( m , n ) : NEW_LINE INDENT k = int ( math . log2 ( m ) ) + 1 NEW_LINE l = int ( math . log2 ( n ) ) + 1 NEW_LINE a = [ 0 for i in range ( 0 , k ) ] NEW_LINE b = [ 0 for i in range ( 0 , l ) ] NEW_LINE c = [ 0 for i in range ( 0 , k + l ) ] NEW_LINE decBinary ( a , m ) ; NEW_LINE decBinary ( b , n ) ; NEW_LINE iin = 0 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT c [ iin ] = a [ i ] NEW_LINE iin = iin + 1 NEW_LINE DEDENT for i in range ( 0 , l ) : NEW_LINE INDENT c [ iin ] = b [ i ] NEW_LINE iin = iin + 1 NEW_LINE DEDENT return ( binaryDec ( c , k + l ) ) NEW_LINE DEDENT m = 4 NEW_LINE n = 5 NEW_LINE print ( concat ( m , n ) ) NEW_LINE |
Find the number obtained after concatenation of binary representation of M and N | Utility function to calculate binary length of a number . ; Function to concatenate the binary numbers and return the decimal result ; find binary length of n ; left binary shift m and then add n ; Driver code | def getBinaryLength ( n ) : NEW_LINE INDENT length = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT length += 1 NEW_LINE n //= 2 NEW_LINE DEDENT return length NEW_LINE DEDENT def concat ( m , n ) : NEW_LINE INDENT length = getBinaryLength ( n ) NEW_LINE return ( m << length ) + n NEW_LINE DEDENT m , n = 4 , 5 NEW_LINE print ( concat ( m , n ) ) NEW_LINE |
XOR two binary strings of unequal lengths | Function to insert n 0 s in the beginning of the given string ; Function to return the XOR of the given strings ; Lengths of the given strings ; Make both the strings of equal lengths by inserting 0 s in the beginning ; Updated length ; To store the resultant XOR ; Driver code | def addZeros ( strr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT strr = "0" + strr NEW_LINE DEDENT return strr NEW_LINE DEDENT def getXOR ( a , b ) : NEW_LINE INDENT aLen = len ( a ) NEW_LINE bLen = len ( b ) NEW_LINE if ( aLen > bLen ) : NEW_LINE INDENT b = addZeros ( b , aLen - bLen ) NEW_LINE DEDENT elif ( bLen > aLen ) : NEW_LINE INDENT a = addZeros ( a , bLen - aLen ) NEW_LINE DEDENT lenn = max ( aLen , bLen ) ; NEW_LINE res = " " NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( a [ i ] == b [ i ] ) : NEW_LINE INDENT res += "0" NEW_LINE DEDENT else : NEW_LINE INDENT res += "1" NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT a = "11001" NEW_LINE b = "111111" NEW_LINE print ( getXOR ( a , b ) ) NEW_LINE |
Minimum operations required to make the string satisfy the given condition | Python implementation of the approach ; Function to return the minimum operations required ; To store the first and the last occurrence of all the characters ; Set the first and the last occurrence of all the characters to - 1 ; Update the occurrences of the characters ; Only set the first occurrence if it hasn 't already been set ; To store the minimum operations ; If the frequency of the current character in the string is less than 2 ; Count of characters to be removed so that the string starts and ends at the current character ; Driver code | MAX = 26 ; NEW_LINE def minOperation ( str , len ) : NEW_LINE INDENT first , last = [ 0 ] * MAX , [ 0 ] * MAX ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT first [ i ] = - 1 ; NEW_LINE last [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ) : NEW_LINE INDENT index = ( ord ( str [ i ] ) - ord ( ' a ' ) ) ; NEW_LINE if ( first [ index ] == - 1 ) : NEW_LINE INDENT first [ index ] = i ; NEW_LINE DEDENT last [ index ] = i ; NEW_LINE DEDENT minOp = - 1 ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( first [ i ] == - 1 or first [ i ] == last [ i ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT cnt = len - ( last [ i ] - first [ i ] + 1 ) ; NEW_LINE if ( minOp == - 1 or cnt < minOp ) : NEW_LINE INDENT minOp = cnt ; NEW_LINE DEDENT DEDENT return minOp ; NEW_LINE DEDENT str = " abcda " ; NEW_LINE len = len ( str ) ; NEW_LINE print ( minOperation ( str , len ) ) ; NEW_LINE |
Queries to find the count of vowels in the substrings of the given string | Python3 implementation of the approach ; Function that returns true if ch is a vowel ; Function to return the count of vowels in the substring str [ l ... r ] ; To store the count of vowels ; For every character in the index range [ l , r ] ; If the current character is a vowel ; For every query ; Find the count of vowels for the current query ; Driver code | N = 2 ; NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) ; NEW_LINE DEDENT def countVowels ( string , l , r ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( isVowel ( string [ i ] ) ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT def performQueries ( string , queries , q ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT print ( countVowels ( string , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE queries = [ [ 1 , 3 ] , [ 2 , 4 ] , [ 1 , 9 ] ] ; NEW_LINE q = len ( queries ) NEW_LINE performQueries ( string , queries , q ) ; NEW_LINE DEDENT |
Convert a String to a Singly Linked List | Structure for a Singly Linked List ; Function to add a node to the Linked List ; Function to convert the string to Linked List . ; curr pointer points to the current node where the insertion should take place ; Function to print the data present in all the nodes ; Driver code | class node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT data = None NEW_LINE next = None NEW_LINE DEDENT DEDENT def add ( data ) : NEW_LINE INDENT newnode = node ( ) NEW_LINE newnode . data = data NEW_LINE newnode . next = None NEW_LINE return newnode NEW_LINE DEDENT def string_to_SLL ( text , head ) : NEW_LINE INDENT head = add ( text [ 0 ] ) NEW_LINE curr = head NEW_LINE for i in range ( len ( text ) - 1 ) : NEW_LINE INDENT curr . next = add ( text [ i + 1 ] ) NEW_LINE curr = curr . next NEW_LINE DEDENT return head NEW_LINE DEDENT def print_ ( head ) : NEW_LINE INDENT curr = head NEW_LINE while ( curr != None ) : NEW_LINE INDENT print ( ( curr . data ) , end = " β - β > β " ) NEW_LINE curr = curr . next NEW_LINE DEDENT DEDENT text = " GEEKS " NEW_LINE head = None NEW_LINE head = string_to_SLL ( text , head ) NEW_LINE print_ ( head ) NEW_LINE |
Reduce the string to minimum length with the given operation | Function to return the minimum possible length str can be reduced to with the given operation ; Stack to store the characters of the given string ; For every character of the string ; If the stack is empty then push the current character in the stack ; Get the top character ; If the top element is not equal to the current element and it only differs in the case ; Pop the top element from stack ; Else push the current element ; Driver code | def minLength ( string , l ) : NEW_LINE INDENT s = [ ] ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( string [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT c = s [ - 1 ] ; NEW_LINE if ( c != string [ i ] and c . upper ( ) == string [ i ] . upper ( ) ) : NEW_LINE INDENT s . pop ( ) ; NEW_LINE DEDENT else : NEW_LINE INDENT s . append ( string [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT return len ( s ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ASbBsd " ; NEW_LINE l = len ( string ) ; NEW_LINE print ( minLength ( string , l ) ) ; NEW_LINE DEDENT |
Check whether two strings can be made equal by copying their characters with the adjacent ones | Python3 implementation of the approach ; Function that returns true if both the strings can be made equal with the given operation ; Lengths of both the strings have to be equal ; To store the frequency of the characters of str1 ; For every character of str2 ; If current character of str2 also appears in str1 ; Driver code | MAX = 26 NEW_LINE def canBeMadeEqual ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE if ( len1 == len2 ) : NEW_LINE INDENT freq = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len2 ) : NEW_LINE INDENT if ( freq [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] > 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT str1 = " abc " NEW_LINE str2 = " defa " NEW_LINE if ( canBeMadeEqual ( str1 , str2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Minimum characters that are to be inserted such that no three consecutive characters are same | Function to return the count of characters that are to be inserted in str1 such that no three consecutive characters are same ; To store the count of operations required ; A character needs to be inserted after str1 [ i + 1 ] ; Current three consecutive characters are not same ; Driver code | def getCount ( str1 , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n - 2 ) : NEW_LINE INDENT if ( str1 [ i ] == str1 [ i + 1 ] and str1 [ i ] == str1 [ i + 2 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE i = i + 2 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT str1 = " aabbbcc " NEW_LINE n = len ( str1 ) NEW_LINE print ( getCount ( str1 , n ) ) NEW_LINE |
Find the number of strings formed using distinct characters of a given string | Function to return the factorial of n ; Function to return the count of all possible strings that can be formed with the characters of the given string without repeating characters ; To store the distinct characters of the string str ; Driver code | def fact ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact *= i ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def countStrings ( string , n ) : NEW_LINE INDENT distinct_char = set ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT distinct_char . add ( string [ i ] ) ; NEW_LINE DEDENT return fact ( len ( distinct_char ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE n = len ( string ) ; NEW_LINE print ( countStrings ( string , n ) ) ; NEW_LINE DEDENT |
Find the character made by adding all the characters of the given string | Function to return the required character ; To store the summ of the characters of the given string ; Add the current character to the summ ; Return the required character ; Driver code | def getChar ( strr ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( len ( strr ) ) : NEW_LINE INDENT summ += ( ord ( strr [ i ] ) - ord ( ' a ' ) + 1 ) NEW_LINE DEDENT if ( summ % 26 == 0 ) : NEW_LINE INDENT return ord ( ' z ' ) NEW_LINE DEDENT else : NEW_LINE INDENT summ = summ % 26 NEW_LINE return chr ( ord ( ' a ' ) + summ - 1 ) NEW_LINE DEDENT DEDENT strr = " gfg " NEW_LINE print ( getChar ( strr ) ) NEW_LINE |
Reverse the given string in the range [ L , R ] | Function to return the string after reversing characters in the range [ L , R ] ; Invalid range ; While there are characters to swap ; Swap ( str [ l ] , str [ r ] ) ; Driver code | def reverse ( string , length , l , r ) : NEW_LINE INDENT if ( l < 0 or r >= length or l > r ) : NEW_LINE INDENT return string ; NEW_LINE DEDENT string = list ( string ) NEW_LINE while ( l < r ) : NEW_LINE INDENT c = string [ l ] ; NEW_LINE string [ l ] = string [ r ] ; NEW_LINE string [ r ] = c ; NEW_LINE l += 1 ; NEW_LINE r -= 1 ; NEW_LINE DEDENT return " " . join ( string ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE length = len ( string ) ; NEW_LINE l = 5 ; r = 7 ; NEW_LINE print ( reverse ( string , length , l , r ) ) ; NEW_LINE DEDENT |
Program to Encrypt a String using ! and @ | Function to encrypt the string ; evenPos is for storing encrypting char at evenPosition oddPos is for storing encrypting char at oddPosition ; Get the number of times the character is to be repeated ; if i is odd , print ' ! ' else print '@ ; Driver code ; Encrypt the String | def encrypt ( input_arr ) : NEW_LINE INDENT evenPos = ' @ ' ; oddPos = ' ! ' ; NEW_LINE for i in range ( len ( input_arr ) ) : NEW_LINE INDENT ascii = ord ( input_arr [ i ] ) ; NEW_LINE repeat = ( ascii - 96 ) if ascii >= 97 else ( ascii - 64 ) ; NEW_LINE for j in range ( repeat ) : NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT print ( oddPos , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( evenPos , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input_arr = [ ' A ' , ' b ' , ' C ' , ' d ' ] ; NEW_LINE encrypt ( input_arr ) ; NEW_LINE DEDENT |
Check if expression contains redundant bracket or not | Set 2 | Function to check for redundant braces ; count of no of signs ; Driver Code | def IsRedundantBraces ( A ) : NEW_LINE INDENT a , b = 0 , 0 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] == ' ( ' and A [ i + 2 ] == ' ) ' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( A [ i ] == ' * ' or A [ i ] == ' + ' or A [ i ] == ' - ' or A [ i ] == ' / ' ) : NEW_LINE INDENT a += 1 ; NEW_LINE DEDENT if ( A [ i ] == ' ( ' ) : NEW_LINE INDENT b += 1 ; NEW_LINE DEDENT DEDENT if ( b > a ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " ( ( ( a + b ) β + β c ) β + β d ) " ; NEW_LINE if ( IsRedundantBraces ( A ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT DEDENT |
Convert an unbalanced bracket sequence to a balanced sequence | Function to return balancedBrackets String ; Initializing dep to 0 ; Stores maximum negative depth ; if dep is less than minDep ; if minDep is less than 0 then there is need to add ' ( ' at the front ; Reinitializing to check the updated String ; if dep is not 0 then there is need to add ' ) ' at the back ; Driver code | def balancedBrackets ( Str ) : NEW_LINE INDENT dep = 0 NEW_LINE minDep = 0 NEW_LINE for i in Str : NEW_LINE INDENT if ( i == ' ( ' ) : NEW_LINE INDENT dep += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dep -= 1 NEW_LINE DEDENT if ( minDep > dep ) : NEW_LINE INDENT minDep = dep NEW_LINE DEDENT DEDENT if ( minDep < 0 ) : NEW_LINE INDENT for i in range ( abs ( minDep ) ) : NEW_LINE INDENT Str = ' ( ' + Str NEW_LINE DEDENT DEDENT dep = 0 NEW_LINE for i in Str : NEW_LINE INDENT if ( i == ' ( ' ) : NEW_LINE INDENT dep += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dep -= 1 NEW_LINE DEDENT DEDENT if ( dep != 0 ) : NEW_LINE INDENT for i in range ( dep ) : Str = Str + ' ) ' NEW_LINE DEDENT return Str NEW_LINE DEDENT Str = " ) ) ) ( ) " NEW_LINE print ( balancedBrackets ( Str ) ) NEW_LINE |
Minimum operations required to convert a binary string to all 0 s or all 1 s | Function to return the count of minimum operations required ; Increment count when consecutive characters are different ; Answer is rounding off the ( count / 2 ) to lower ; Driver code | def minOperations ( str , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( str [ i ] != str [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return ( count + 1 ) // 2 NEW_LINE DEDENT str = "000111" NEW_LINE n = len ( str ) NEW_LINE print ( minOperations ( str , n ) ) NEW_LINE |
Append a digit in the end to make the number equal to the length of the remaining string | Function to return the required digit ; To store the position of the first numeric digit in the string ; To store the length of the string without the numeric digits in the end ; pw stores the current power of 10 and num is to store the number which is appended in the end ; If current character is a numeric digit ; Get the current digit ; Build the number ; If number exceeds the length ; Next power of 10 ; Append 0 in the end ; Required number that must be added ; If number is not a single digit ; Driver code | def find_digit ( s , n ) : NEW_LINE INDENT first_digit = - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if s [ i ] < '0' or s [ i ] > '9' : NEW_LINE INDENT first_digit = i NEW_LINE break NEW_LINE DEDENT DEDENT first_digit += 1 NEW_LINE s_len = first_digit NEW_LINE num = 0 NEW_LINE pw = 1 NEW_LINE i = n - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT if s [ i ] >= '0' and s [ i ] <= '9' : NEW_LINE INDENT digit = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE num = num + ( pw * digit ) NEW_LINE if num >= s_len : NEW_LINE INDENT return - 1 NEW_LINE DEDENT pw = pw * 10 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT num = num * 10 NEW_LINE req = s_len - num NEW_LINE if req > 9 or req < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return req NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcd0" NEW_LINE n = len ( s ) NEW_LINE print ( find_digit ( s , n ) ) NEW_LINE DEDENT |
Check whether str1 can be converted to str2 with the given operations | Function that returns true if str1 can be converted to str2 with the given operations ; Traverse from left to right ; If the two characters do not match ; If possible to combine ; If not possible to combine ; If the two characters match ; If possible to convert one string to another ; Driver code | def canConvert ( str1 , str2 ) : NEW_LINE INDENT i , j = 0 , 0 ; NEW_LINE while ( i < len ( str1 ) and j < len ( str2 ) ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT if ( str1 [ i ] == '0' and str2 [ j ] == '1' and i + 1 < len ( str1 ) and str1 [ i + 1 ] == '0' ) : NEW_LINE INDENT i += 2 ; NEW_LINE j += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT i += 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT DEDENT if ( i == len ( str1 ) and j == len ( str2 ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT str1 = "00100" ; NEW_LINE str2 = "111" ; NEW_LINE if ( canConvert ( str1 , str2 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Reverse the Words of a String using Stack | function to reverse the words of the given string without using strtok ( ) . ; create an empty string stack ; create an empty temporary string ; traversing the entire string ; push the temporary variable into the stack ; assigning temporary variable as empty ; for the last word of the string ; Get the words in reverse order ; Driver code | def reverse ( s ) : NEW_LINE INDENT stc = [ ] NEW_LINE temp = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] == ' β ' : NEW_LINE stc . append ( temp ) NEW_LINE temp = " " NEW_LINE else : NEW_LINE temp = temp + s [ i ] NEW_LINE DEDENT stc . append ( temp ) NEW_LINE while len ( stc ) != 0 : NEW_LINE INDENT temp = stc [ len ( stc ) - 1 ] NEW_LINE print ( temp , end = " β " ) NEW_LINE stc . pop ( ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT s = " I β Love β To β Code " NEW_LINE reverse ( s ) NEW_LINE |
Print an N x M matrix such that each row and column has all the vowels in it | Function to print the required matrix ; Impossible to generate the required matrix ; Store all the vowels ; Print the matrix ; Print vowels for every index ; Shift the vowels by one ; Driver code | def printMatrix ( n , m ) : NEW_LINE INDENT if ( n < 5 or m < 5 ) : NEW_LINE INDENT print ( - 1 , end = " β " ) ; NEW_LINE return ; NEW_LINE DEDENT s = " aeiou " ; NEW_LINE s = list ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT print ( s [ j % 5 ] , end = " β " ) ; NEW_LINE DEDENT print ( ) NEW_LINE c = s [ 0 ] ; NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT s [ i ] = s [ i + 1 ] ; NEW_LINE DEDENT s [ 4 ] = c ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; m = 5 ; NEW_LINE printMatrix ( n , m ) ; NEW_LINE DEDENT |
Check if a given string is made up of two alternating characters | Function that returns true if the string is made up of two alternating characters ; Check if ith character matches with the character at index ( i + 2 ) ; If string consists of a single character repeating itself ; Driver code | def isTwoAlter ( s ) : NEW_LINE INDENT for i in range ( len ( s ) - 2 ) : NEW_LINE INDENT if ( s [ i ] != s [ i + 2 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( s [ 0 ] == s [ 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " ABAB " NEW_LINE if ( isTwoAlter ( str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Number of character corrections in the given strings to make them equal | Function to return the count of operations required ; To store the count of operations ; No operation required ; One operation is required when any two characters are equal ; Two operations are required when none of the characters are equal ; Return the minimum count of operations required ; Driver code | def minOperations ( n , a , b , c ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE y = b [ i ] NEW_LINE z = c [ i ] NEW_LINE if ( x == y and y == z ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( x == y or y == z or x == z ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += 2 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = " place " NEW_LINE b = " abcde " NEW_LINE c = " plybe " NEW_LINE n = len ( a ) NEW_LINE print ( minOperations ( n , a , b , c ) ) NEW_LINE DEDENT |
Check if string can be made lexicographically smaller by reversing any substring | Function that returns true if s can be made lexicographically smaller by reversing a sub - string in s ; Traverse in the string ; Check if s [ i + 1 ] < s [ i ] ; Not possible ; Driver code | def check ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s [ i ] > s [ i + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE if ( check ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count of sub | Function to return the count of required sub - strings ; Number of sub - strings from position of current x to the end of str ; To store the number of characters before x ; Driver code | def countSubStr ( str , n , x ) : NEW_LINE INDENT res = 0 ; count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == x ) : NEW_LINE INDENT res += ( ( count + 1 ) * ( n - i ) ) ; NEW_LINE count = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT str = " abcabc " ; NEW_LINE n = len ( str ) ; NEW_LINE x = ' c ' ; NEW_LINE print ( countSubStr ( str , n , x ) ) ; NEW_LINE |
Count of sub | Function to return the count of possible sub - strings of length n ; Driver code | def countSubStr ( string , n ) : NEW_LINE INDENT length = len ( string ) ; NEW_LINE return ( length - n + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE n = 5 ; NEW_LINE print ( countSubStr ( string , n ) ) ; NEW_LINE DEDENT |
Count of sub | Function to return the number of sub - strings that do not contain the given character c ; Length of the string ; Traverse in the string ; If current character is different from the given character ; Update the number of sub - strings ; Reset count to 0 ; For the characters appearing after the last occurrence of c ; Driver code | def countSubstrings ( s , c ) : NEW_LINE INDENT n = len ( s ) NEW_LINE cnt = 0 NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] != c ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Sum += ( cnt * ( cnt + 1 ) ) // 2 NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT Sum += ( cnt * ( cnt + 1 ) ) // 2 NEW_LINE return Sum NEW_LINE DEDENT s = " baa " NEW_LINE c = ' b ' NEW_LINE print ( countSubstrings ( s , c ) ) NEW_LINE |
Minimize ASCII values sum after removing all occurrences of one character | Python3 implementation of the approach ; Function to return the minimized sum ; To store the occurrences of each character of the string ; Update the occurrence ; Calculate the sum ; Get the character which is contributing the maximum value to the sum ; Count of occurrence of the character multiplied by its ASCII value ; Return the minimized sum ; Driver code | import sys NEW_LINE def getMinimizedSum ( string , length ) : NEW_LINE INDENT maxVal = - ( sys . maxsize - 1 ) NEW_LINE sum = 0 ; NEW_LINE occurrences = [ 0 ] * 26 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT occurrences [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE sum += ord ( string [ i ] ) ; NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT count = occurrences [ i ] * ( i + ord ( ' a ' ) ) NEW_LINE maxVal = max ( maxVal , count ) ; NEW_LINE DEDENT return ( sum - maxVal ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE length = len ( string ) ; NEW_LINE print ( getMinimizedSum ( string , length ) ) ; NEW_LINE DEDENT |
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Function that returns true if s is palindrome ; Function to return the required index ; Copy the ith character in S ; Copy all the character of string s2 in Temp ; Check whether the string is palindrome ; Driver code | def isPalindrome ( s ) : NEW_LINE INDENT i = 0 ; NEW_LINE j = len ( s ) - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( s [ i ] is not s [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def getIndex ( S1 , S2 , n ) : NEW_LINE INDENT S = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT S = S + S1 [ i ] ; NEW_LINE Temp = " " ; NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT Temp += S2 [ j ] ; NEW_LINE DEDENT if ( isPalindrome ( S + Temp ) ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT S1 = " abcdf " ; S2 = " sfgba " ; NEW_LINE n = len ( S1 ) ; NEW_LINE print ( getIndex ( S1 , S2 , n ) ) ; NEW_LINE |
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Function that returns true if the sub - string starting from index i and ending at index j is a palindrome ; Function to get the required index ; Start comparing the two strings from both ends . ; Break from the loop at first mismatch ; If it is possible to concatenate the strings to form palindrome , return index ; If remaining part for s2 is palindrome ; If remaining part for s1 is palindrome ; If not possible , return - 1 ; Driver Code | def isPalindrome ( s , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def getIndex ( s1 , s2 , length ) : NEW_LINE INDENT i = 0 ; j = length - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ j ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT return i - 1 ; NEW_LINE DEDENT elif ( isPalindrome ( s2 , i , j ) ) : NEW_LINE INDENT return i - 1 ; NEW_LINE DEDENT elif ( isPalindrome ( s1 , i , j ) ) : NEW_LINE INDENT return j ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " abcdf " ; NEW_LINE s2 = " sfgba " ; NEW_LINE length = len ( s1 ) ; NEW_LINE print ( getIndex ( s1 , s2 , length ) ) ; NEW_LINE DEDENT |
Acronym words | Function to return the number of strings that can be an acronym for other strings ; Frequency array to store the frequency of the first character of every string in the array ; To store the count of required strings ; Current word ; Frequency array to store the frequency of each of the character of the current string ; Check if the frequency of every character in the current string is <= its value in freq [ ] ; First character of the current string ; Driver Code | def count_acronym ( n , arr ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( arr [ i ] [ 0 ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT st = arr [ i ] NEW_LINE num = [ 0 ] * 26 NEW_LINE for j in range ( len ( st ) ) : NEW_LINE INDENT num [ ord ( st [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT flag = True NEW_LINE for j in range ( 1 , 26 ) : NEW_LINE INDENT if num [ j ] > freq [ j ] : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT x = ord ( st [ 0 ] ) - ord ( ' a ' ) NEW_LINE if freq [ x ] - 1 < num [ x ] : NEW_LINE INDENT flag = False NEW_LINE DEDENT if flag : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " abc " , " bcad " , " cabd " , " cba " , " dzzz " ] NEW_LINE n = 5 NEW_LINE print ( count_acronym ( n , arr ) ) NEW_LINE DEDENT |
Sub | Function that returns true if every lowercase character appears atmost once ; Every character frequency must be not greater than one ; Function that returns the modified good string if possible ; If the length of the string is less than n ; Sub - strings of length 26 ; To store frequency of each character ; Get the frequency of each character in the current sub - string ; Check if we can get sub - string containing the 26 characters all ; Find which character is missing ; Fill with missing characters ; Find the next missing character ; Return the modified good string ; Driver code | def valid ( cnt ) : NEW_LINE INDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT if cnt [ i ] >= 2 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def getGoodString ( s , n ) : NEW_LINE INDENT if n < 26 : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT for i in range ( 25 , n ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE for j in range ( i , i - 26 , - 1 ) : NEW_LINE INDENT if s [ j ] != ' ? ' : NEW_LINE INDENT cnt [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT if valid ( cnt ) : NEW_LINE INDENT cur = 0 NEW_LINE while cur < 26 and cnt [ cur ] > 0 : NEW_LINE INDENT cur += 1 NEW_LINE DEDENT for j in range ( i - 25 , i + 1 ) : NEW_LINE INDENT if s [ j ] == ' ? ' : NEW_LINE INDENT s [ j ] = chr ( cur + ord ( ' a ' ) ) NEW_LINE cur += 1 NEW_LINE while cur < 26 and cnt [ cur ] > 0 : NEW_LINE INDENT cur += 1 NEW_LINE DEDENT DEDENT DEDENT return ' ' . join ( s ) NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcdefghijkl ? nopqrstuvwxy ? " NEW_LINE n = len ( s ) NEW_LINE print ( getGoodString ( list ( s ) , n ) ) NEW_LINE DEDENT |
Modify the string by swapping continuous vowels or consonants | Function to check if a character is a vowel ; Function to swap two consecutively repeated vowels or consonants ; Traverse through the length of the string ; Check if the two consecutive characters are vowels or consonants ; swap the two characters ; Driver code | def isVowel ( c ) : NEW_LINE INDENT c = c . lower ( ) ; NEW_LINE if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def swapRepeated ( string ) : NEW_LINE INDENT for i in range ( len ( string ) - 1 ) : NEW_LINE INDENT if ( ( isVowel ( string [ i ] ) and isVowel ( string [ i + 1 ] ) ) or ( not ( isVowel ( string [ i ] ) ) and not ( isVowel ( string [ i + 1 ] ) ) ) ) : NEW_LINE INDENT ( string [ i ] , string [ i + 1 ] ) = ( string [ i + 1 ] , string [ i ] ) ; NEW_LINE DEDENT DEDENT string = " " . join ( string ) NEW_LINE return string ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE print ( swapRepeated ( list ( string ) ) ) ; NEW_LINE DEDENT |
Find the lexicographically largest palindromic Subsequence of a String | Function to find the largest palindromic subsequence ; Find the largest character ; Append all occurrences of largest character to the resultant string ; Driver Code | def largestPalinSub ( s ) : NEW_LINE INDENT res = " " NEW_LINE mx = s [ 0 ] NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT mx = max ( mx , s [ i ] ) NEW_LINE DEDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] == mx : NEW_LINE INDENT res += s [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE print ( largestPalinSub ( s ) ) NEW_LINE DEDENT |
Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | Function to print the required string ; count number of 1 s ; To check if the all the 1 s have been used or not ; Print all the 1 s if any 2 is encountered ; If Str1 [ i ] = 0 or Str1 [ i ] = 2 ; If 1 s are not printed yet ; Driver code | def printString ( Str1 , n ) : NEW_LINE INDENT ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str1 [ i ] == '1' ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT DEDENT used = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str1 [ i ] == '2' and used == False ) : NEW_LINE INDENT used = 1 NEW_LINE for j in range ( ones ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT DEDENT if ( Str1 [ i ] != '1' ) : NEW_LINE INDENT print ( Str1 [ i ] , end = " " ) NEW_LINE DEDENT DEDENT if ( used == False ) : NEW_LINE INDENT for j in range ( ones ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT DEDENT DEDENT Str1 = "100210" NEW_LINE n = len ( Str1 ) NEW_LINE printString ( Str1 , n ) NEW_LINE |
K length words that can be formed from given characters without repetition | Python3 implementation of the approach ; Function to return the required count ; To store the count of distinct characters in str ; Traverse str character by character ; If current character is appearing for the first time in str ; Increment the distinct character count ; Update the appearance of the current character ; Since P ( n , r ) = n ! / ( n - r ) ! ; Return the answer ; Driver code | import math as mt NEW_LINE def findPermutation ( string , k ) : NEW_LINE INDENT has = [ False for i in range ( 26 ) ] NEW_LINE cnt = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( has [ ord ( string [ i ] ) - ord ( ' a ' ) ] == False ) : NEW_LINE INDENT cnt += 1 NEW_LINE has [ ord ( string [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE for i in range ( 2 , cnt + 1 ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT for i in range ( cnt - k , 1 , - 1 ) : NEW_LINE INDENT ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT string = " geeksforgeeks " NEW_LINE k = 4 NEW_LINE print ( findPermutation ( string , k ) ) NEW_LINE |
Find the number in a range having maximum product of the digits | Returns the product of digits of number x ; This function returns the number having maximum product of the digits ; Converting both integers to strings ; Let the current answer be r ; Stores the current number having current digit one less than current digit in b ; Replace all following digits with 9 to maximise the product ; Convert string to number ; Check if it lies in range and its product is greater than max product ; Driver Code | def product ( x ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( x ) : NEW_LINE INDENT prod *= ( x % 10 ) NEW_LINE x //= 10 ; NEW_LINE DEDENT return prod NEW_LINE DEDENT def findNumber ( l , r ) : NEW_LINE INDENT a = str ( l ) ; NEW_LINE b = str ( r ) ; NEW_LINE ans = r NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT if ( b [ i ] == '0' ) : NEW_LINE INDENT continue NEW_LINE DEDENT curr = list ( b ) NEW_LINE curr [ i ] = str ( ( ( ord ( curr [ i ] ) - ord ( '0' ) ) - 1 ) + ord ( '0' ) ) NEW_LINE for j in range ( i + 1 , len ( curr ) ) : NEW_LINE INDENT curr [ j ] = str ( ord ( '9' ) ) NEW_LINE DEDENT num = 0 NEW_LINE for c in curr : NEW_LINE INDENT num = num * 10 + ( int ( c ) - ord ( '0' ) ) NEW_LINE DEDENT if ( num >= l and product ( ans ) < product ( num ) ) : NEW_LINE INDENT ans = num NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l , r = 1 , 10 NEW_LINE print ( findNumber ( l , r ) ) NEW_LINE l , r = 51 , 62 NEW_LINE print ( findNumber ( l , r ) ) NEW_LINE DEDENT |
Longest Ordered Subsequence of Vowels | Python3 program to find the longest subsequence of vowels in the specified order ; Mapping values for vowels ; Function to check if given subsequence contains all the vowels or not ; not contain vowel ; Function to find the longest subsequence of vowels in the given string in specified order ; If we have reached the end of the string , return the subsequence if it is valid , else return an empty list ; If there is no vowel in the subsequence yet , add vowel at current index if it is ' a ' , else move on to the next character in the string ; If the last vowel in the subsequence until now is same as the vowel at current index , add it to the subsequence ; If the vowel at the current index comes right after the last vowel in the subsequence , we have two options : either to add the vowel in the subsequence , or move on to next character . We choose the one which gives the longest subsequence . ; Driver Code | vowels = [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] NEW_LINE mapping = { ' a ' : 0 , ' e ' : 1 , ' i ' : 2 , ' o ' : 3 , ' u ' : 4 } NEW_LINE def isValidSequence ( subList ) : NEW_LINE INDENT for vowel in vowels : NEW_LINE INDENT if vowel not in subList : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def longestSubsequence ( string , subList , index ) : NEW_LINE INDENT if index == len ( string ) : NEW_LINE INDENT if isValidSequence ( subList ) == True : NEW_LINE INDENT return subList NEW_LINE DEDENT else : NEW_LINE INDENT return [ ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if len ( subList ) == 0 : NEW_LINE INDENT if string [ index ] != ' a ' : NEW_LINE INDENT return longestSubsequence ( string , subList , index + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return longestSubsequence ( string , subList + \ [ string [ index ] ] , index + 1 ) NEW_LINE DEDENT DEDENT elif mapping [ subList [ - 1 ] ] == mapping [ string [ index ] ] : NEW_LINE INDENT return longestSubsequence ( string , subList + \ [ string [ index ] ] , index + 1 ) NEW_LINE DEDENT elif ( mapping [ subList [ - 1 ] ] + 1 ) == mapping [ string [ index ] ] : NEW_LINE INDENT sub1 = longestSubsequence ( string , subList + \ [ string [ index ] ] , index + 1 ) NEW_LINE sub2 = longestSubsequence ( string , subList , index + 1 ) NEW_LINE if len ( sub1 ) > len ( sub2 ) : NEW_LINE INDENT return sub1 NEW_LINE DEDENT else : NEW_LINE INDENT return sub2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return longestSubsequence ( string , subList , index + 1 ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " aeiaaioooauuaeiou " NEW_LINE subsequence = longestSubsequence ( string , [ ] , 0 ) NEW_LINE if len ( subsequence ) == 0 : NEW_LINE INDENT print ( " No β subsequence β possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( subsequence ) NEW_LINE DEDENT DEDENT |
Concatenate suffixes of a String | Function to print the expansion of the string ; Take sub - string from i to n - 1 ; Print the sub - string ; Driver code | def printExpansion ( str ) : NEW_LINE INDENT for i in range ( len ( str ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( i , len ( str ) ) : NEW_LINE INDENT print ( str [ j ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT str = " geeks " NEW_LINE printExpansion ( str ) NEW_LINE |
Construct a binary string following the given constraints | Function to print a binary string which has ' a ' number of 0 ' s , β ' b ' β number β of β 1' s and there are at least ' x ' indices such that s [ i ] != s [ i + 1 ] ; Divide index value by 2 and store it into d ; If index value x is even and x / 2 is not equal to a ; Loop for d for each d print 10 ; subtract d from a and b ; Loop for b to print remaining 1 's ; Loop for a to print remaining 0 's ; Driver Code | def constructBinString ( a , b , x ) : NEW_LINE INDENT d = x // 2 NEW_LINE if x % 2 == 0 and x // 2 != a : NEW_LINE INDENT d -= 1 NEW_LINE print ( "0" , end = " " ) NEW_LINE a -= 1 NEW_LINE DEDENT for i in range ( d ) : NEW_LINE INDENT print ( "10" , end = " " ) NEW_LINE DEDENT a = a - d NEW_LINE b = b - d NEW_LINE for i in range ( b ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT for i in range ( a ) : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , x = 4 , 3 , 2 NEW_LINE constructBinString ( a , b , x ) NEW_LINE DEDENT |
Check If every group of a ' s β is β followed β by β a β group β of β b ' s of same length | Function to match whether there are always n consecutive b ' s β followed β by β n β consecutive β a ' s throughout the string ; Traverse through the string ; Count a 's in current segment ; Count b 's in current segment ; If both counts are not same . ; Driver code | def matchPattern ( s ) : NEW_LINE INDENT count = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT while ( i < n and s [ i ] == ' a ' ) : NEW_LINE INDENT count += 1 ; NEW_LINE i = + 1 ; NEW_LINE DEDENT while ( i < n and s [ i ] == ' b ' ) : NEW_LINE INDENT count -= 1 ; NEW_LINE i += 1 ; NEW_LINE DEDENT if ( count != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT s = " bb " ; NEW_LINE if ( matchPattern ( s ) == True ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Length of longest consecutive ones by at most one swap in a Binary String | Function to calculate the length of the longest consecutive 1 's ; To count all 1 's in the string ; To store cumulative 1 's ; Counting cumulative 1 's from left ; If 0 then start new cumulative one from that i ; perform step 3 of the approach ; step 3 ; Driver Code ; string | def maximum_one ( s , n ) : NEW_LINE INDENT cnt_one = 0 NEW_LINE cnt , max_cnt = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT cnt_one += 1 NEW_LINE cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT max_cnt = max ( max_cnt , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT max_cnt = max ( max_cnt , cnt ) NEW_LINE left = [ 0 ] * n NEW_LINE right = [ 0 ] * n NEW_LINE if ( s [ 0 ] == '1' ) : NEW_LINE INDENT left [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT left [ 0 ] = 0 NEW_LINE DEDENT if ( s [ n - 1 ] == '1' ) : NEW_LINE INDENT right [ n - 1 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT right [ n - 1 ] = 0 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT left [ i ] = left [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT left [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT right [ i ] = right [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT sum = left [ i - 1 ] + right [ i + 1 ] NEW_LINE if ( sum < cnt_one ) : NEW_LINE INDENT max_cnt = max ( max_cnt , sum + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT max_cnt = max ( max_cnt , sum ) NEW_LINE DEDENT DEDENT DEDENT return max_cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "111011101" NEW_LINE print ( maximum_one ( s , len ( s ) ) ) NEW_LINE DEDENT |
Maximum length substring with highest frequency in a string | function to return maximum occurred substring of a string ; size of string ; to store maximum frequency ; To store string which has maximum frequency ; return substring which has maximum freq ; Driver code ; Function call | def MaxFreq ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT string = ' ' NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT string += s [ j ] NEW_LINE if string in m . keys ( ) : NEW_LINE INDENT m [ string ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ string ] = 1 NEW_LINE DEDENT DEDENT DEDENT maxi = 0 NEW_LINE maxi_str = ' ' NEW_LINE for i in m : NEW_LINE INDENT if m [ i ] > maxi : NEW_LINE INDENT maxi = m [ i ] NEW_LINE maxi_str = i NEW_LINE DEDENT elif m [ i ] == maxi : NEW_LINE INDENT ss = i NEW_LINE if len ( ss ) > len ( maxi_str ) : NEW_LINE INDENT maxi_str = ss NEW_LINE DEDENT DEDENT DEDENT return maxi_str NEW_LINE DEDENT string = " ababecdecd " NEW_LINE INDENT print ( MaxFreq ( string ) ) NEW_LINE DEDENT |
Lexicographically smallest substring with maximum occurrences containing a ' s β and β b ' s only | Function to Find the lexicographically smallest substring in a given string with maximum frequency and contains a ' s β and β b ' s only . ; To store frequency of digits ; size of string ; Take lexicographically larger digit in b ; get frequency of each character ; If no such string exits ; Maximum frequency ; Driver program | def maxFreq ( s , a , b ) : NEW_LINE INDENT fre = [ 0 for i in range ( 10 ) ] NEW_LINE n = len ( s ) NEW_LINE if ( a > b ) : NEW_LINE INDENT swap ( a , b ) NEW_LINE DEDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT a = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE fre [ a ] += 1 NEW_LINE DEDENT if ( fre [ a ] == 0 and fre [ b ] == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT elif ( fre [ a ] >= fre [ b ] ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 4 NEW_LINE b = 7 NEW_LINE s = "47744" NEW_LINE print ( maxFreq ( s , a , b ) ) NEW_LINE DEDENT |
Minimum steps to convert one binary string to other only using negation | Function to find the minimum steps to convert string a to string b ; List to mark the positions needed to be negated ; If two character are not same then they need to be negated ; To count the blocks of 1 ; To count the number of 1 ' s β in β each β β block β of β 1' s ; For the last block of 1 's ; Driver code | def convert ( n , a , b ) : NEW_LINE INDENT l = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT l [ i ] = 1 NEW_LINE DEDENT DEDENT cc = 0 NEW_LINE vl = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( l [ i ] == 0 ) : NEW_LINE INDENT if ( vl != 0 ) : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT vl = 0 NEW_LINE DEDENT else : NEW_LINE INDENT vl += 1 NEW_LINE DEDENT DEDENT if ( vl != 0 ) : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT print ( cc ) NEW_LINE DEDENT a = "101010" NEW_LINE b = "110011" NEW_LINE n = len ( a ) NEW_LINE convert ( n , a , b ) NEW_LINE |
Generate a sequence with the given operations | function to find minimum required permutation ; Driver code | def StringMatch ( S ) : NEW_LINE INDENT lo , hi = 0 , len ( S ) NEW_LINE ans = [ ] NEW_LINE for x in S : NEW_LINE INDENT if x == ' I ' : NEW_LINE INDENT ans . append ( lo ) NEW_LINE lo += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( hi ) NEW_LINE hi -= 1 NEW_LINE DEDENT DEDENT return ans + [ lo ] NEW_LINE DEDENT S = " IDID " NEW_LINE print ( StringMatch ( S ) ) NEW_LINE |
Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes | Function to find number of ways ; initialise result that store No . of swaps required ; Traverse both strings and check the bits as explained ; calculate result ; Driver code | def countWays ( s1 , s2 , n ) : NEW_LINE INDENT a = b = c = d = 0 NEW_LINE result = 0 ; NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( s2 [ i ] == '0' ) : NEW_LINE INDENT if ( s1 [ i ] == '0' ) : NEW_LINE INDENT c += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT d += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s1 [ i ] == '0' ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT else : NEW_LINE INDENT b += 1 NEW_LINE DEDENT DEDENT DEDENT result = a * d + b * c + c * d NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE s1 = "01011" NEW_LINE s2 = "11001" NEW_LINE print ( countWays ( s1 , s2 , n ) ) NEW_LINE DEDENT |
Find the player who rearranges the characters to get a palindrome string first | Function that returns the winner of the game ; Initialize the freq array to 0 ; Iterate and count the frequencies of each character in the string ; Count the odd occurring character ; If odd occurrence ; Check condition for Player - 1 winning the game ; Driver code ; Function call that returns the winner | def returnWinner ( s , l ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( 0 , l , 1 ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] % 2 != 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt == 0 or cnt & 1 == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " abaaab " NEW_LINE l = len ( s ) NEW_LINE winner = returnWinner ( s , l ) NEW_LINE print ( " Player - " , winner ) NEW_LINE DEDENT |
Maximum sum and product of the M consecutive digits in a number | Python implementation of above approach ; Function to find the maximum product ; Driver code | import sys NEW_LINE def maxProductSum ( string , m ) : NEW_LINE INDENT n = len ( string ) NEW_LINE maxProd , maxSum = ( - ( sys . maxsize ) - 1 , - ( sys . maxsize ) - 1 ) NEW_LINE for i in range ( n - m + 1 ) : NEW_LINE INDENT product , sum = 1 , 0 NEW_LINE for j in range ( i , m + i ) : NEW_LINE INDENT product = product * ( ord ( string [ j ] ) - ord ( '0' ) ) NEW_LINE sum = sum + ( ord ( string [ j ] ) - ord ( '0' ) ) NEW_LINE DEDENT maxProd = max ( maxProd , product ) NEW_LINE maxSum = max ( maxSum , sum ) NEW_LINE DEDENT print ( " Maximum β Product β = " , maxProd ) NEW_LINE print ( " Maximum β sum β = " , maxSum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "3605356297" NEW_LINE m = 3 NEW_LINE maxProductSum ( string , m ) NEW_LINE DEDENT |
Find time taken for signal to reach all positions in a string | Python3 program to Find time taken for signal to reach all positions in a string ; Returns time needed for signal to traverse through complete string . ; for the calculation of last index ; for strings like oxoooo , xoxxoooo ; if coun is greater than max_length ; if ' x ' is present at the right side of max_length ; if ' x ' is present at left side of max_length ; We use ceiling function to handle odd number ' o ' s ; Driver code | import sys NEW_LINE import math NEW_LINE def maxLength ( s , n ) : NEW_LINE INDENT right = 0 NEW_LINE left = 0 NEW_LINE coun = 0 NEW_LINE max_length = - ( sys . maxsize - 1 ) NEW_LINE s = s + '1' NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT if s [ i ] == ' o ' : NEW_LINE INDENT coun += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if coun > max_length : NEW_LINE INDENT right = 0 NEW_LINE left = 0 NEW_LINE if s [ i ] == ' x ' : NEW_LINE INDENT right = 1 NEW_LINE DEDENT if i - coun > 0 and s [ i - coun - 1 ] == ' x ' : NEW_LINE INDENT left = 1 NEW_LINE DEDENT coun = math . ceil ( float ( coun / ( right + left ) ) ) NEW_LINE max_length = max ( max_length , coun ) NEW_LINE DEDENT coun = 0 NEW_LINE DEDENT DEDENT return max_length NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " oooxoooooooooxooo " NEW_LINE n = len ( s ) NEW_LINE print ( maxLength ( s , n ) ) NEW_LINE DEDENT |
Lexicographically largest string formed from the characters in range L and R | Function to return the lexicographically largest string ; hash array ; make 0 - based indexing ; iterate and count frequencies of character ; ans string ; iterate in frequency array ; add til all characters are added ; Driver Code | def printLargestString ( s , l , r ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE for i in range ( min ( l , r ) , max ( l , r ) + 1 ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = " " NEW_LINE for i in range ( 25 , - 1 , - 1 ) : NEW_LINE INDENT while ( freq [ i ] ) : NEW_LINE INDENT ans += chr ( ord ( ' a ' ) + i ) NEW_LINE freq [ i ] -= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " striver " NEW_LINE l = 3 NEW_LINE r = 5 NEW_LINE print ( printLargestString ( s , l , r ) ) NEW_LINE DEDENT |
Arrange a binary string to get maximum value within a range of indices | Python implementation of the approach ; Storing the count of 1 's in the string ; Query of l and r ; Applying range update technique . ; Taking prefix sum to get the range update values ; Final array which will store the arranged string ; if after maximizing the ranges any 1 is left then we maximize the string lexicographically . ; Driver Code | def arrange ( s ) : NEW_LINE INDENT cc = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == "1" ) : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT DEDENT a = [ 0 ] * ( len ( s ) + 1 ) NEW_LINE qq = [ ( 2 , 3 ) , ( 5 , 5 ) ] NEW_LINE n = len ( qq ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT l , r = qq [ i ] [ 0 ] , qq [ i ] [ 1 ] NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE a [ l ] += 1 NEW_LINE a [ r + 1 ] -= 1 NEW_LINE DEDENT for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT a [ i ] = a [ i ] + a [ i - 1 ] NEW_LINE DEDENT zz = [ 0 ] * len ( s ) NEW_LINE for i in range ( len ( a ) - 1 ) : NEW_LINE INDENT if ( a [ i ] > 0 ) : NEW_LINE INDENT if ( cc > 0 ) : NEW_LINE INDENT zz [ i ] = 1 NEW_LINE cc -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( cc == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( cc > 0 ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( zz [ i ] == 0 ) : NEW_LINE INDENT zz [ i ] = 1 NEW_LINE cc -= 1 NEW_LINE DEDENT if ( cc == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT print ( * zz , sep = " " ) NEW_LINE DEDENT str = "11100" NEW_LINE arrange ( str ) NEW_LINE |
Check whether the vowels in a string are in alphabetical order or not | Function that checks whether the vowel characters in a string are in alphabetical order or not ; ASCII Value 64 is less than all the alphabets so using it as a default value ; check if the vowels in the string are sorted or not ; if the vowel is smaller than the previous vowel ; store the vowel ; Driver code ; check whether the vowel characters in a string are in alphabetical order or not | def areVowelsInOrder ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE c = chr ( 64 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) : NEW_LINE INDENT if s [ i ] < c : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT c = s [ i ] NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabbbddeecc " NEW_LINE if areVowelsInOrder ( s ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Program to replace every space in a string with hyphen | Python program for the above approach ; Split by space and converting String to list and ; joining the list and storing in string ; returning thee string ; Driver code | def printHyphen ( string ) : NEW_LINE INDENT lis = list ( string . split ( " β " ) ) NEW_LINE string = ' - ' . join ( lis ) NEW_LINE return string NEW_LINE DEDENT string = " Text β contains β malayalam β and β level β words " NEW_LINE print ( printHyphen ( string ) ) NEW_LINE |
Rearrange the string to maximize the number of palindromic substrings | Function to return the newString ; length of string ; hashing array ; iterate and count ; resulting string ; form the resulting string ; number of times character appears ; append to resulting string ; Driver Code | def newString ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE freq = [ 0 ] * ( 26 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = " " NEW_LINE for i in range ( 0 , 26 ) : NEW_LINE INDENT for j in range ( 0 , freq [ i ] ) : NEW_LINE INDENT ans += chr ( 97 + i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabab " NEW_LINE print ( newString ( s ) ) NEW_LINE DEDENT |
Program to find remainder when large number is divided by r | Function to Return Remainder ; len is variable to store the length of Number string . ; loop that find Remainder ; Return the remainder ; Driver code ; Get the large number as string ; Get the divisor R ; Find and print the remainder | def Remainder ( str , R ) : NEW_LINE INDENT l = len ( str ) NEW_LINE Rem = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT Num = Rem * 10 + ( ord ( str [ i ] ) - ord ( '0' ) ) NEW_LINE Rem = Num % R NEW_LINE DEDENT return Rem NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "13589234356546756" NEW_LINE R = 13 NEW_LINE print ( Remainder ( str , R ) ) NEW_LINE DEDENT |
Number of balanced bracket subsequence of length 2 and 4 | Python 3 implementation of above approach ; Taking the frequency suffix sum of the number of 2 's present after every index ; Storing the count of subsequence ; Subsequence of length 2 ; Subsequence of length 4 of type 1 1 2 2 ; Subsequence of length 4 of type 1 2 1 2 ; Driver Code | def countWays ( a , n ) : NEW_LINE INDENT suff = [ 0 ] * n NEW_LINE if ( a [ n - 1 ] == 2 ) : NEW_LINE INDENT suff [ n - 1 ] = 1 NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] == 2 ) : NEW_LINE INDENT suff [ i ] = suff [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT suff [ i ] = suff [ i + 1 ] NEW_LINE DEDENT DEDENT ss = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT ss += suff [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( a [ i ] == 1 and a [ j ] == 1 and suff [ j ] >= 2 ) : NEW_LINE INDENT ss += ( suff [ j ] ) * ( suff [ j ] - 1 ) // 2 NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( a [ i ] == 1 and a [ j ] == 1 and ( suff [ i ] - suff [ j ] ) >= 1 and suff [ j ] >= 1 ) : NEW_LINE INDENT ss += ( suff [ i ] - suff [ j ] ) * suff [ j ] NEW_LINE DEDENT DEDENT DEDENT print ( ss ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 1 , 1 , 2 , 2 ] NEW_LINE n = 6 NEW_LINE countWays ( a , n ) NEW_LINE DEDENT |
Count the number of carry operations required to add two numbers | Function to count the number of carry operations ; Initialize the value of carry to 0 ; Counts the number of carry operations ; Initialize len_a and len_b with the sizes of strings ; Assigning the ascii value of the character ; Add both numbers / digits ; If sum > 0 , increment count and set carry to 1 ; Else , set carry to 0 ; Driver code | def count_carry ( a , b ) : NEW_LINE INDENT carry = 0 ; NEW_LINE count = 0 ; NEW_LINE len_a = len ( a ) ; NEW_LINE len_b = len ( b ) ; NEW_LINE while ( len_a != 0 or len_b != 0 ) : NEW_LINE INDENT x = 0 ; NEW_LINE y = 0 ; NEW_LINE if ( len_a > 0 ) : NEW_LINE INDENT x = int ( a [ len_a - 1 ] ) + int ( '0' ) ; NEW_LINE len_a -= 1 ; NEW_LINE DEDENT if ( len_b > 0 ) : NEW_LINE INDENT y = int ( b [ len_b - 1 ] ) + int ( '0' ) ; NEW_LINE len_b -= 1 ; NEW_LINE DEDENT sum = x + y + carry ; NEW_LINE if ( sum >= 10 ) : NEW_LINE INDENT carry = 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT a = "9555" ; NEW_LINE b = "555" ; NEW_LINE count = count_carry ( a , b ) ; NEW_LINE if ( count == 0 ) : NEW_LINE INDENT print ( "0" ) ; NEW_LINE DEDENT elif ( count == 1 ) : NEW_LINE INDENT print ( "1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( count ) ; NEW_LINE DEDENT |
Check if a number is in given base or not | Python3 program to check if given number is in given base or not . ; Allowed bases are till 16 ( Hexadecimal ) ; If base is below or equal to 10 , then all digits should be from 0 to 9. ; If base is below or equal to 16 , then all digits should be from 0 to 9 or from 'A ; Driver code | def isInGivenBase ( Str , base ) : NEW_LINE INDENT if ( base > 16 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( base <= 10 ) : NEW_LINE INDENT for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( Str [ i ] . isnumeric ( ) and ( ord ( Str [ i ] ) >= ord ( '0' ) and ord ( Str [ i ] ) < ( ord ( '0' ) + base ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( Str [ i ] . isnumeric ( ) and ( ( ord ( Str [ i ] ) >= ord ( '0' ) and ord ( Str [ i ] ) < ( ord ( '0' ) + base ) ) or ( ord ( Str [ i ] ) >= ord ( ' A ' ) and ord ( Str [ i ] ) < ( ord ( ' A ' ) + base - 10 ) ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT Str = " AF87" NEW_LINE if ( isInGivenBase ( Str , 16 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find indices of all occurrence of one string in other | Python program to find indices of all occurrences of one String in other . ; Driver code | def printIndex ( str , s ) : NEW_LINE INDENT flag = False ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i : i + len ( s ) ] == s ) : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE flag = True ; NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " NONE " ) ; NEW_LINE DEDENT DEDENT str1 = " GeeksforGeeks " ; NEW_LINE str2 = " Geeks " ; NEW_LINE printIndex ( str1 , str2 ) ; NEW_LINE |
Alternatively Merge two Strings in Java | Function for alternatively merging two strings ; To store the final string ; For every index in the strings ; First choose the ith character of the first string if it exists ; Then choose the ith character of the second string if it exists ; Driver Code | def merge ( s1 , s2 ) : NEW_LINE INDENT result = " " NEW_LINE i = 0 NEW_LINE while ( i < len ( s1 ) ) or ( i < len ( s2 ) ) : NEW_LINE INDENT if ( i < len ( s1 ) ) : NEW_LINE INDENT result += s1 [ i ] NEW_LINE DEDENT if ( i < len ( s2 ) ) : NEW_LINE INDENT result += s2 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return result NEW_LINE DEDENT s1 = " geeks " NEW_LINE s2 = " forgeeks " NEW_LINE print ( merge ( s1 , s2 ) ) NEW_LINE |
Maximum occurring character in an input string | Set | function to find the maximum occurring character in an input string which is lexicographically first ; freq [ ] used as hash table ; to store maximum frequency ; length of str ; get frequency of each character of 'str ; for each character , where character is obtained by ( i + ' a ' ) check whether it is the maximum character so far and accodingly update 'result ; maximum occurring character ; Driver Code | def getMaxOccurringChar ( str ) : NEW_LINE INDENT freq = [ 0 for i in range ( 100 ) ] NEW_LINE max = - 1 NEW_LINE len__ = len ( str ) NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , len__ , 1 ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT if ( max < freq [ i ] ) : NEW_LINE INDENT max = freq [ i ] NEW_LINE result = chr ( ord ( ' a ' ) + i ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " sample β program " NEW_LINE print ( " Maximum β occurring β character β = " , getMaxOccurringChar ( str ) ) NEW_LINE DEDENT |
Check if the given string of words can be formed from words present in the dictionary | Python3 program to check if a sentence can be formed from a given set of words . include < bits / stdc ++ . h > ; here isEnd is an integer that will store count of words ending at that node ; utility function to create a new node ; Initialize new node with null ; Function to insert new words in trie ; Iterate for the length of a word ; If the next key does not contains the character ; isEnd is increment so not only the word but its count is also stored ; Search function to find a word of a sentence ; Iterate for the complete length of the word ; If the character is not present then word is also not present ; If present move to next character in Trie ; If word found then decrement count of the word ; if the word is found decrement isEnd showing one occurrence of this word is already taken so ; Function to check if string can be formed from the sentence ; Iterate for all words in the string ; if a word is not found in a string then the sentence cannot be made from this dictionary of words ; If possible ; Function to insert all the words of dict in the Trie ; Driver Code ; Dictionary of words ; Calling Function to insert words of dictionary to tree ; String to be checked ; Function call to check possibility | ALPHABET_SIZE = 26 ; NEW_LINE class trieNode : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . t = [ None for i in range ( ALPHABET_SIZE ) ] NEW_LINE self . isEnd = 0 NEW_LINE DEDENT DEDENT def getNode ( ) : NEW_LINE INDENT temp = trieNode ( ) NEW_LINE return temp ; NEW_LINE DEDENT def insert ( root , key ) : NEW_LINE INDENT trail = None NEW_LINE trail = root ; NEW_LINE for i in range ( len ( key ) ) : NEW_LINE INDENT if ( trail . t [ ord ( key [ i ] ) - ord ( ' a ' ) ] == None ) : NEW_LINE INDENT temp = None NEW_LINE temp = getNode ( ) ; NEW_LINE trail . t [ ord ( key [ i ] ) - ord ( ' a ' ) ] = temp ; NEW_LINE DEDENT trail = trail . t [ ord ( key [ i ] ) - ord ( ' a ' ) ] ; NEW_LINE DEDENT ( trail . isEnd ) += 1 NEW_LINE DEDENT def search_mod ( root , word ) : NEW_LINE INDENT trail = root ; NEW_LINE for i in range ( len ( word ) ) : NEW_LINE INDENT if ( trail . t [ ord ( word [ i ] ) - ord ( ' a ' ) ] == None ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT trail = trail . t [ ord ( word [ i ] ) - ord ( ' a ' ) ] ; NEW_LINE DEDENT if ( ( trail . isEnd ) > 0 and trail != None ) : NEW_LINE INDENT ( trail . isEnd ) -= 1 NEW_LINE return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def checkPossibility ( sentence , m , root ) : NEW_LINE INDENT flag = 1 ; NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( search_mod ( root , sentence [ i ] ) == False ) : NEW_LINE INDENT print ( ' NO ' , end = ' ' ) NEW_LINE return ; NEW_LINE DEDENT DEDENT print ( ' YES ' ) NEW_LINE DEDENT def insertToTrie ( dictionary , n , root ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT insert ( root , dictionary [ i ] ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( ) ; NEW_LINE dictionary = [ " find " , " a " , " geeks " , " all " , " for " , " on " , " geeks " , " answers " , " inter " ] NEW_LINE N = len ( dictionary ) NEW_LINE insertToTrie ( dictionary , N , root ) ; NEW_LINE sentence = [ " find " , " all " , " answers " , " on " , " geeks " , " for " , " geeks " ] NEW_LINE M = len ( sentence ) NEW_LINE checkPossibility ( sentence , M , root ) ; NEW_LINE DEDENT |
Given two numbers as strings , find if one is a power of other | Python3 program to check if one number is a power of other ; Multiply the numbers . It multiplies each digit of second string to each digit of first and stores the result . ; If the digit exceeds 9 , add the cumulative carry to previous digit . ; If all zeroes , return "0" . ; Remove starting zeroes . ; Removes Extra zeroes from front of a string . ; Make sure there are no leading zeroes in the string . ; Making sure that s1 is smaller . If it is greater , we recur we reversed parameters . ; Driver Code | def isGreaterThanEqualTo ( s1 , s2 ) : NEW_LINE INDENT if len ( s1 ) > len ( s2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return s1 == s2 NEW_LINE DEDENT def multiply ( s1 , s2 ) : NEW_LINE INDENT n , m = len ( s1 ) , len ( s2 ) NEW_LINE result = [ 0 ] * ( n + m ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( m - 1 , - 1 , - 1 ) : NEW_LINE INDENT result [ i + j + 1 ] += ( int ( s1 [ i ] ) * int ( s2 [ j ] ) ) NEW_LINE DEDENT DEDENT size = len ( result ) NEW_LINE for i in range ( size - 1 , 0 , - 1 ) : NEW_LINE INDENT if result [ i ] >= 10 : NEW_LINE INDENT result [ i - 1 ] += result [ i ] // 10 NEW_LINE result [ i ] = result [ i ] % 10 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while i < size and result [ i ] == 0 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if i == size : NEW_LINE INDENT return "0" NEW_LINE DEDENT temp = " " NEW_LINE while i < size : NEW_LINE INDENT temp += str ( result [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT return temp NEW_LINE DEDENT def removeLeadingZeores ( s ) : NEW_LINE INDENT n , i = len ( s ) , 0 NEW_LINE while i < n and s [ i ] == '0' : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if i == n : NEW_LINE INDENT return "0" NEW_LINE DEDENT temp = " " NEW_LINE while i < n : NEW_LINE INDENT temp += s [ i ] NEW_LINE i += 1 NEW_LINE DEDENT return temp NEW_LINE DEDENT def isPower ( s1 , s2 ) : NEW_LINE INDENT s1 = removeLeadingZeores ( s1 ) NEW_LINE s2 = removeLeadingZeores ( s2 ) NEW_LINE if s1 == "0" or s2 == "0" : NEW_LINE INDENT return False NEW_LINE DEDENT if s1 == "1" and s2 == "1" : NEW_LINE INDENT return True NEW_LINE DEDENT if s1 == "1" and s2 == "1" : NEW_LINE INDENT return True NEW_LINE DEDENT if len ( s1 ) > len ( s2 ) : NEW_LINE INDENT return isPower ( s2 , s1 ) NEW_LINE DEDENT temp = s1 NEW_LINE while not isGreaterThanEqualTo ( s1 , s2 ) : NEW_LINE INDENT s1 = multiply ( s1 , temp ) NEW_LINE DEDENT return s1 == s2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 , s2 = "374747" , "52627712618930723" NEW_LINE if isPower ( s1 , s2 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT s1 , s2 = "4099" , "2" NEW_LINE if isPower ( s1 , s2 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Check for balanced parentheses in an expression | O ( 1 ) space | Function1 to match closing bracket ; Function1 to match opening bracket ; Function to check balanced parentheses ; helper variables ; Handling case of opening parentheses ; Handling case of closing parentheses ; If corresponding matching opening parentheses doesn 't lie in given interval return 0 ; else continue ; If corresponding closing parentheses doesn 't lie in given interval, return 0 ; if found , now check for each opening and closing parentheses in this interval ; Driver Code | def matchClosing ( X , start , end , open , close ) : NEW_LINE INDENT c = 1 NEW_LINE i = start + 1 NEW_LINE while ( i <= end ) : NEW_LINE INDENT if ( X [ i ] == open ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT elif ( X [ i ] == close ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return i NEW_LINE DEDENT def matchingOpening ( X , start , end , open , close ) : NEW_LINE INDENT c = - 1 NEW_LINE i = end - 1 NEW_LINE while ( i >= start ) : NEW_LINE INDENT if ( X [ i ] == open ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT elif ( X [ i ] == close ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def isBalanced ( X , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( X [ i ] == ' ( ' ) : NEW_LINE INDENT j = matchClosing ( X , i , n - 1 , ' ( ' , ' ) ' ) NEW_LINE DEDENT elif ( X [ i ] == ' { ' ) : NEW_LINE INDENT j = matchClosing ( X , i , n - 1 , ' { ' , ' } ' ) NEW_LINE DEDENT elif ( X [ i ] == ' [ ' ) : NEW_LINE INDENT j = matchClosing ( X , i , n - 1 , ' [ ' , ' ] ' ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( X [ i ] == ' ) ' ) : NEW_LINE INDENT j = matchingOpening ( X , 0 , i , ' ( ' , ' ) ' ) NEW_LINE DEDENT elif ( X [ i ] == ' } ' ) : NEW_LINE INDENT j = matchingOpening ( X , 0 , i , ' { ' , ' } ' ) NEW_LINE DEDENT elif ( X [ i ] == ' ] ' ) : NEW_LINE INDENT j = matchingOpening ( X , 0 , i , ' [ ' , ' ] ' ) NEW_LINE DEDENT if ( j < 0 or j >= i ) : NEW_LINE INDENT return False NEW_LINE DEDENT continue NEW_LINE DEDENT if ( j >= n or j < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT start = i NEW_LINE end = j NEW_LINE for k in range ( start + 1 , end ) : NEW_LINE INDENT if ( X [ k ] == ' ( ' ) : NEW_LINE INDENT x = matchClosing ( X , k , end , ' ( ' , ' ) ' ) NEW_LINE if ( not ( k < x and x < end ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT elif ( X [ k ] == ' ) ' ) : NEW_LINE INDENT x = matchingOpening ( X , start , k , ' ( ' , ' ) ' ) NEW_LINE if ( not ( start < x and x < k ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( X [ k ] == ' { ' ) : NEW_LINE INDENT x = matchClosing ( X , k , end , ' { ' , ' } ' ) NEW_LINE if ( not ( k < x and x < end ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT elif ( X [ k ] == ' } ' ) : NEW_LINE INDENT x = matchingOpening ( X , start , k , ' { ' , ' } ' ) NEW_LINE if ( not ( start < x and x < k ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( X [ k ] == ' [ ' ) : NEW_LINE INDENT x = matchClosing ( X , k , end , ' [ ' , ' ] ' ) NEW_LINE if ( not ( k < x and x < end ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT elif ( X [ k ] == ' ] ' ) : NEW_LINE INDENT x = matchingOpening ( X , start , k , ' [ ' , ' ] ' ) NEW_LINE if ( not ( start < x and x < k ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " [ ( ) ] ( ) " NEW_LINE n = 6 NEW_LINE if ( isBalanced ( X , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT Y = " [ [ ( ) ] ] ) " NEW_LINE n = 7 NEW_LINE if ( isBalanced ( Y , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Sorting array with conditional swapping | Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driver Code | def possibleToSort ( arr , n , str ) : NEW_LINE INDENT max_element = - 1 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT max_element = max ( max_element , arr [ i ] ) NEW_LINE if ( str [ i ] == '0' ) : NEW_LINE INDENT if ( max_element > i + 1 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE str = "01110" NEW_LINE print ( possibleToSort ( arr , n , str ) ) NEW_LINE DEDENT |
Prime String | Function that checks if sum is prime or not ; corner cases ; This is checked so that we can skip middle five numbers in below loop ; Driver code | def isPrimeString ( str1 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE n = 0 NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT n += ord ( str1 [ i ] ) NEW_LINE DEDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT while ( i * i <= n ) : NEW_LINE INDENT if n % i == 0 or n % ( i + 2 ) == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT str1 = " geekRam " NEW_LINE if ( isPrimeString ( str1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Ways to split string such that each partition starts with distinct character | Returns the number of we can split the string ; Finding the frequency of each character . ; making frequency of first character of string equal to 1. ; Finding the product of frequency of occurrence of each character . ; Driver Code | def countWays ( s ) : NEW_LINE INDENT count = [ 0 ] * 26 ; NEW_LINE for x in s : NEW_LINE INDENT count [ ord ( x ) - ord ( ' a ' ) ] = ( count [ ord ( x ) - ord ( ' a ' ) ] ) + 1 ; NEW_LINE DEDENT count [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] = 1 ; NEW_LINE ans = 1 ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( count [ i ] != 0 ) : NEW_LINE INDENT ans *= count [ i ] ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " acbbcc " ; NEW_LINE print ( countWays ( s ) ) ; NEW_LINE DEDENT |
Lexicographically next greater string using same character set | function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; searching the first character left of index k and not equal to greatest character of the string ; finding the just next greater character than s [ i ] ; suffix with smallest character ; if we reach here then all indices to the left of k had the greatest character ; Driver code ; Function call | def lexoString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE v = [ ] NEW_LINE mp = { s [ i ] : 0 for i in range ( len ( s ) ) } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( mp [ s [ i ] ] == 0 ) : NEW_LINE INDENT mp [ s [ i ] ] = 1 NEW_LINE v . append ( s [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( reverse = False ) NEW_LINE if ( k > n ) : NEW_LINE INDENT print ( s , end = " " ) NEW_LINE for i in range ( n , k , 1 ) : NEW_LINE INDENT print ( v [ 0 ] , end = " " ) NEW_LINE DEDENT return ; NEW_LINE DEDENT i = k - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( s [ i ] != v [ len ( v ) - 1 ] ) : NEW_LINE INDENT for j in range ( 0 , i , 1 ) : NEW_LINE INDENT print ( s [ j ] , end = " β " ) NEW_LINE DEDENT for j in range ( 0 , len ( v ) , 1 ) : NEW_LINE INDENT if ( v [ j ] > s [ i ] ) : NEW_LINE INDENT print ( v [ j ] , end = " β " ) NEW_LINE break NEW_LINE DEDENT DEDENT for j in range ( i + 1 , k , 1 ) : NEW_LINE INDENT print ( v [ 0 ] , end = " β " ) NEW_LINE DEDENT re1turn NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( " No β lexicographically β greater " , " string β of β length " , k , " possible β here . " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " gi " NEW_LINE k = 3 NEW_LINE lexoString ( s , k ) NEW_LINE DEDENT |
Number of palindromic permutations | Set 1 | Python3 program to find number of palindromic permutations of a given string ; Returns factorial of n ; Returns count of palindromic permutations of str . ; Count frequencies of all characters ; Since half of the characters decide count of palindromic permutations , we take ( n / 2 ) ! ; To make sure that there is at most one odd occurring char ; Traverse through all counts ; To make sure that the string can permute to form a palindrome ; If there are more than one odd occurring chars ; Divide all permutations with repeated characters ; Driver code | MAX = 256 NEW_LINE def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def countPalinPermutations ( str ) : NEW_LINE INDENT global MAX NEW_LINE n = len ( str ) NEW_LINE freq = [ 0 ] * MAX ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) ] = freq [ ord ( str [ i ] ) ] + 1 ; NEW_LINE DEDENT res = fact ( int ( n / 2 ) ) NEW_LINE oddFreq = False NEW_LINE for i in range ( 0 , MAX ) : NEW_LINE INDENT half = int ( freq [ i ] / 2 ) NEW_LINE if ( freq [ i ] % 2 != 0 ) : NEW_LINE INDENT if ( oddFreq == True ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT oddFreq = True NEW_LINE DEDENT res = int ( res / fact ( half ) ) NEW_LINE DEDENT return res NEW_LINE DEDENT str = " gffg " NEW_LINE print ( countPalinPermutations ( str ) ) NEW_LINE |