text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Count distinct strings possible by replacing each character by its Morse code | Function to count unique array elements by replacing each character by its Morse code ; Stores Morse code of all lowercase characters ; Stores distinct elements of String by replacing each character by Morse code ; Stores length of arr array ; Traverse the array ; Stores the Morse code of arr [ i ] ; Stores length of current String ; Update temp ; Insert temp into st ; Return count of elements in the set ; Driver code | def uniqueMorseRep ( arr ) : NEW_LINE INDENT morseCode = [ " . - " , " - . . . " , " - . - . " , " - . . " , " . " , " . . - . " , " - - . " , " . . . . " , " . . " , " . - - - " , " - . - " , " . - . . " , " - - " , " - . " , " - - - " , " . - - . " , " - - . - " , " . - . " , " . . . " , " - " , " . . - " , " . . . - " , " . - - " , " - . . - " , " - . - - " , " - - . . " ] ; NEW_LINE st = set ( ) ; NEW_LINE N = len ( arr ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp = " " ; NEW_LINE M = len ( arr [ i ] ) ; NEW_LINE for j in range ( M ) : NEW_LINE INDENT temp += morseCode [ ord ( arr [ i ] [ j ] ) - ord ( ' a ' ) ] ; NEW_LINE DEDENT st . add ( temp ) ; NEW_LINE DEDENT return len ( st ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " gig " , " zeg " , " gin " , " msn " ] ; NEW_LINE print ( uniqueMorseRep ( arr ) , " " ) ; NEW_LINE DEDENT |
Maximum repeating character for every index in given String | Function to print the maximum repeating character at each index of the string ; Stores frequency of each distinct character ; Stores frequency of maximum repeating character ; Stores the character having maximum frequency ; Traverse the string ; Stores current character ; Update the frequency of strr [ i ] ; If frequency of current character exceeds max ; Update max ; Update charMax ; Print the required output ; Driver Code ; Stores length of strr | def findFreq ( strr , N ) : NEW_LINE INDENT freq = [ 0 ] * 256 NEW_LINE max = 0 NEW_LINE charMax = '0' NEW_LINE for i in range ( N ) : NEW_LINE INDENT ch = ord ( strr [ i ] ) NEW_LINE freq [ ch ] += 1 NEW_LINE if ( freq [ ch ] >= max ) : NEW_LINE INDENT max = freq [ ch ] NEW_LINE charMax = ch NEW_LINE DEDENT print ( chr ( charMax ) , " - > " , max ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " abbc " NEW_LINE N = len ( strr ) NEW_LINE findFreq ( strr , N ) NEW_LINE DEDENT |
Minimize cost to convert given string to a palindrome | Function to find the minimum cost to convert the into a palindrome ; Length of the string ; If iointer is in the second half ; Reverse the string ; Find the farthest index needed to change on left side ; Find the farthest index needed to change on right side ; Changing the variable to make palindrome ; min distance to travel to make palindrome ; Total cost ; Return the minimum cost ; Driver Code ; Given S ; Given pointer P ; Function Call | def findMinCost ( strr , pos ) : NEW_LINE INDENT n = len ( strr ) NEW_LINE if ( pos >= n / 2 ) : NEW_LINE INDENT strr = strr [ : : - 1 ] NEW_LINE pos = n - pos - 1 NEW_LINE DEDENT left , right = pos , pos NEW_LINE for i in range ( pos , - 1 , - 1 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE INDENT left = i NEW_LINE DEDENT DEDENT for i in range ( pos , n // 2 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE INDENT right = i NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT dis = ( min ( ( 2 * ( pos - left ) + ( right - pos ) ) , ( 2 * ( right - pos ) + ( pos - left ) ) ) ) NEW_LINE ans = ans + dis NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " bass " NEW_LINE P = 3 NEW_LINE print ( findMinCost ( S , P ) ) NEW_LINE DEDENT |
Minimize replacements by previous or next alphabet required to make all characters of a string the same | Function to find the minimum count of operations to make all characters of the string same ; Set min to some large value ; Find minimum operations for each character ; Initialize cnt ; Add the value to cnt ; Update minValue ; Return minValue ; Driver Code ; Given string str ; Function Call | def minCost ( s , n ) : NEW_LINE INDENT minValue = 100000000 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT cnt += min ( abs ( i - ( ord ( s [ j ] ) - ord ( ' a ' ) ) ) , 26 - abs ( i - ( ord ( s [ j ] ) - ord ( ' a ' ) ) ) ) NEW_LINE DEDENT minValue = min ( minValue , cnt ) NEW_LINE DEDENT return minValue NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " geeksforgeeks " NEW_LINE N = len ( st ) NEW_LINE print ( minCost ( st , N ) ) NEW_LINE DEDENT |
Longest palindromic string possible by concatenating strings from a given array | Python3 program for the above approach ; Stores the distinct strings from the given array ; Insert the strings into set ; Stores the left and right substrings of the given string ; Stores the middle substring ; Traverse the array of strings ; Reverse the current string ; Checking if the is itself a palindrome or not ; Check if the reverse of the is present or not ; Append to the left substring ; Append to the right substring ; Erase both the strings from the set ; Print the left substring ; Print the middle substring ; Print the right substring ; Driver Code ; Function call | def max_len ( s , N , M ) : NEW_LINE INDENT set_str = { } NEW_LINE for i in s : NEW_LINE INDENT set_str [ i ] = 1 NEW_LINE DEDENT left_ans , right_ans = [ ] , [ ] 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 set_str ) : NEW_LINE INDENT left_ans . append ( s [ i ] ) NEW_LINE right_ans . append ( t ) NEW_LINE del set_str [ s [ i ] ] NEW_LINE del set_str [ t ] NEW_LINE DEDENT DEDENT for x in left_ans : NEW_LINE INDENT print ( x , end = " " ) NEW_LINE DEDENT print ( mid , end = " " ) NEW_LINE right_ans = right_ans [ : : - 1 ] NEW_LINE for x in right_ans : NEW_LINE INDENT print ( x , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE M = 3 NEW_LINE s = [ " omg " , " bbb " , " ffd " , " gmo " ] NEW_LINE max_len ( s , N , M ) NEW_LINE DEDENT |
Minimize steps defined by a string required to reach the destination from a given source | Function to find the minimum length of string required to reach from source to destination ; Size of the string ; Stores the index of the four directions E , W , N , S ; If destination reached ; Iterate over the string ; Move east ; Change x1 according to direction E ; Move west ; Change x1 according to direction W ; Move north ; Change y1 according to direction N ; Move south ; Change y1 according to direction S ; Store the max of all positions ; Print the minimum length of string required ; Otherwise , it is impossible ; Given string ; Given source and destination ; Function call | def minimum_length ( x1 , y1 , x2 , y2 , str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE pos1 = - 1 NEW_LINE pos2 = - 1 NEW_LINE pos3 = - 1 NEW_LINE pos4 = - 1 NEW_LINE if ( x1 == x2 and y1 == y2 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( x2 > x1 ) : NEW_LINE INDENT if ( str [ i ] == ' E ' ) : NEW_LINE INDENT x1 = x1 + 1 NEW_LINE if ( x1 == x2 ) : NEW_LINE INDENT pos1 = i NEW_LINE DEDENT DEDENT DEDENT if ( x2 < x1 ) : NEW_LINE INDENT if ( str [ i ] == ' W ' ) : NEW_LINE INDENT x1 = x1 - 1 NEW_LINE if ( x1 == x2 ) : NEW_LINE INDENT pos2 = i NEW_LINE DEDENT DEDENT DEDENT if ( y2 > y1 ) : NEW_LINE INDENT if ( str [ i ] == ' N ' ) : NEW_LINE INDENT y1 = y1 + 1 NEW_LINE if ( y1 == y2 ) : NEW_LINE INDENT pos3 = i NEW_LINE DEDENT DEDENT DEDENT if ( y2 < y1 ) : NEW_LINE INDENT if ( str [ i ] == ' S ' ) : NEW_LINE INDENT y1 = y1 - 1 NEW_LINE if ( y1 == y2 ) : NEW_LINE INDENT pos4 = i NEW_LINE DEDENT DEDENT DEDENT DEDENT z = 0 NEW_LINE z = max ( pos1 , max ( max ( pos2 , pos3 ) , pos4 ) ) NEW_LINE if ( x1 == x2 and y1 == y2 ) : NEW_LINE INDENT print ( z + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT DEDENT str = " SESNW " NEW_LINE x1 = 0 NEW_LINE x2 = 1 NEW_LINE y1 = 0 NEW_LINE y2 = 1 NEW_LINE minimum_length ( x1 , y1 , x2 , y2 , str ) NEW_LINE |
Remove all duplicate adjacent characters from a string using Stack | Function to remove adjacent duplicate elements ; Store the string without duplicate elements ; Store the index of str ; Traverse the string str ; Checks if stack is empty or top of the stack is not equal to current character ; If top element of the stack is equal to the current character ; If stack is empty ; If stack is not Empty ; Driver Code | def ShortenString ( str1 ) : NEW_LINE INDENT st = [ ] NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) : NEW_LINE INDENT if len ( st ) == 0 or str1 [ i ] != st [ - 1 ] : NEW_LINE INDENT st . append ( str1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if len ( st ) == 0 : NEW_LINE INDENT return ( " Empty β String " ) NEW_LINE DEDENT else : NEW_LINE INDENT short_string = " " NEW_LINE for i in st : NEW_LINE INDENT short_string += str ( i ) NEW_LINE DEDENT return ( short_string ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " azzxzy " NEW_LINE print ( ShortenString ( str1 ) ) NEW_LINE DEDENT |
Count ways to place all the characters of two given strings alternately | Function to get the factorial of N ; Function to get the total number of distinct ways ; Length of str1 ; Length of str2 ; If both strings have equal length ; If both strings do not have equal length ; Driver code | def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def distinctWays ( str1 , str2 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE if ( n == m ) : NEW_LINE INDENT return 2 * fact ( n ) * fact ( m ) NEW_LINE DEDENT return fact ( n ) * fact ( m ) NEW_LINE DEDENT str1 = " aegh " NEW_LINE str2 = " rsw " NEW_LINE print ( distinctWays ( str1 , str2 ) ) NEW_LINE |
Smallest string without any multiplication sign that represents the product of two given numbers | Python3 program for the above approach ; Function to find the string which evaluates to the product of A and B ; Stores the result ; 2 ^ logg <= B && 2 ^ ( logg + 1 ) > B ; Update res to res += A X 2 ^ logg ; Update res to res += A X 2 ^ 0 ; Find the remainder ; If remainder is not equal to 0 ; Return the resultant string ; Function to find the minimum length representation of A * B ; Find representation of form A << k1 + A << k2 + ... + A << kn ; Find representation of form B << k1 + B << k2 + ... + B << kn ; Compare the length of the representations ; Driver Code ; Product A X B ; Function call | from math import log NEW_LINE def lenn ( A , B ) : NEW_LINE INDENT res = " " NEW_LINE logg = 0 NEW_LINE while True : NEW_LINE INDENT logg = log ( B ) // log ( 2 ) NEW_LINE if ( logg != 0 ) : NEW_LINE INDENT res += ( str ( A ) + " < < " + str ( int ( logg ) ) ) NEW_LINE DEDENT else : NEW_LINE INDENT res += A NEW_LINE break NEW_LINE DEDENT B = B - pow ( 2 , logg ) NEW_LINE if ( B != 0 ) : NEW_LINE INDENT res += " + " NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT if logg == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def minimumString ( A , B ) : NEW_LINE INDENT res1 = lenn ( A , B ) NEW_LINE res2 = lenn ( B , A ) NEW_LINE if ( len ( res1 ) > len ( res2 ) ) : NEW_LINE INDENT print ( res2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 6 NEW_LINE B = 10 NEW_LINE minimumString ( A , B ) NEW_LINE DEDENT |
Count substrings of a given string whose anagram is a palindrome | Function to prcount of subStrings whose anagrams are palindromic ; Stores the answer ; Iterate over the String ; Set the current character ; Parity update ; Print final count ; Driver Code ; Function Call | def countSubString ( s ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT x = 0 ; NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT temp = 1 << ord ( s [ j ] ) - ord ( ' a ' ) ; NEW_LINE x ^= temp ; NEW_LINE if ( ( x & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT res += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( res ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aaa " ; NEW_LINE countSubString ( str ) ; NEW_LINE DEDENT |
Count substrings of a given string whose anagram is a palindrome | Python3 program for the above approach ; Function to get the count of substrings whose anagrams are palindromic ; Store the answer ; Map to store the freq of masks ; Set frequency for mask 00. . .00 to 1 ; Store mask in x from 0 to i ; Update answer ; Update frequency ; Print the answer ; Driver Code ; Function call | from collections import defaultdict NEW_LINE def countSubstring ( s ) : NEW_LINE INDENT answer = 0 NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE m [ 0 ] = 1 NEW_LINE x = 0 NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT x ^= 1 << ( ord ( s [ j ] ) - ord ( ' a ' ) ) NEW_LINE answer += m [ x ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT answer += m [ x ^ ( 1 << i ) ] NEW_LINE DEDENT m [ x ] += 1 NEW_LINE DEDENT print ( answer ) NEW_LINE DEDENT str = " abab " NEW_LINE countSubstring ( str ) NEW_LINE |
Sum of an array of large numbers | Function to prthe result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer ; Stores the carry ; Stores the result of summation ; Initialize the sum ; Calculate sum ; Update the sum by adding existing carry ; Store the number of digits ; Increase count of digits ; If the number exceeds 9 , Store the unit digit in carry ; Store the rest of the sum ; Append digit by digit into result array ; Append result until carry is 0 ; Print the result ; Driver Code ; Given N array of large numbers | def printResult ( result ) : NEW_LINE INDENT result = result [ : : - 1 ] NEW_LINE i = 0 NEW_LINE while ( i < len ( result ) ) : NEW_LINE INDENT print ( result [ i ] , end = " " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def sumOfLargeNumbers ( v , k , N ) : NEW_LINE INDENT x = [ [ ] for i in range ( 1000 ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT x [ i ] . append ( ord ( v [ i ] [ j ] ) - ord ( '0' ) ) NEW_LINE DEDENT DEDENT carry = 0 NEW_LINE result = [ ] NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( k ) : NEW_LINE INDENT sum += x [ j ] [ i ] NEW_LINE DEDENT sum += carry NEW_LINE temp = sum NEW_LINE count = 0 NEW_LINE while ( temp > 9 ) : NEW_LINE INDENT temp = temp % 10 NEW_LINE count += 1 NEW_LINE DEDENT l = pow ( 10 , count ) NEW_LINE if ( l != 1 ) : NEW_LINE INDENT carry = sum / l NEW_LINE DEDENT sum = sum % 10 NEW_LINE result . append ( sum ) NEW_LINE DEDENT while ( carry != 0 ) : NEW_LINE INDENT a = carry % 10 NEW_LINE result . append ( a ) NEW_LINE carry = carry // 10 NEW_LINE DEDENT printResult ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 10 NEW_LINE N = 5 NEW_LINE arr = [ "1111111111" , "1111111111" , "1111111111" , "1111111111" , "1111111111" ] NEW_LINE sumOfLargeNumbers ( arr , N , K ) NEW_LINE DEDENT |
Reverse words in a given string | Set 2 | Function to reverse the words of a given string ; Stack to store each word of the string ; Store the whole string in stream ; Push each word of the into the stack ; Print the in reverse order of the words ; Driver Code | def printRev ( strr ) : NEW_LINE INDENT strr = strr . split ( " β " ) NEW_LINE st = [ ] NEW_LINE for i in strr : NEW_LINE INDENT st . append ( i ) NEW_LINE DEDENT while len ( st ) > 0 : NEW_LINE INDENT print ( st [ - 1 ] , end = " β " ) NEW_LINE del st [ - 1 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " geeks β quiz β practice β code " NEW_LINE printRev ( strr ) NEW_LINE DEDENT |
Count of substrings of a Binary string containing only 1 s | Function to find the total number of substring having only ones ; Driver Code | def countOfSubstringWithOnlyOnes ( s ) : NEW_LINE INDENT count = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] == '1' : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 ; NEW_LINE DEDENT res = res + count NEW_LINE DEDENT return res NEW_LINE DEDENT s = "0110111" NEW_LINE print ( countOfSubstringWithOnlyOnes ( s ) ) NEW_LINE |
Count of Distinct strings possible by inserting K characters in the original string | Python3 program for the above approach ; Function to calculate and return x ^ n in log ( n ) time using Binary Exponentiation ; Function to calculate the factorial of a number ; Function to calculate combination ; nCi = ( n ! ) / ( ( n - i ) ! * i ! ) ; Using Euler 's theorem of Modular multiplicative inverse to find the inverse of a number. (1/a)%mod=a^(m?2)%mod ; Function to find the count of possible strings ; Number of ways to form all possible strings ; Number of ways to form strings that don 't contain the input string as a subsequence ; Checking for all prefix length from 0 to | S | - 1. ; To calculate nCi ; Select the remaining characters 25 ^ ( N - i ) ; Add the answer for this prefix length to the final answer ; Answer is the difference of allWays and noWays ; Print the answer ; Driver Code | mod = 1000000007 NEW_LINE def binExp ( base , power ) : NEW_LINE INDENT x = 1 NEW_LINE while ( power ) : NEW_LINE INDENT if ( power % 2 == 1 ) : NEW_LINE INDENT x = ( ( ( x % mod ) * ( base % mod ) ) % mod ) NEW_LINE DEDENT base = ( ( ( base % mod ) * ( base % mod ) ) % mod ) NEW_LINE power = power // 2 NEW_LINE DEDENT return x NEW_LINE DEDENT def fact ( num ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT result = ( ( ( result % mod ) * ( i % mod ) ) % mod ) NEW_LINE DEDENT return result NEW_LINE DEDENT def calculate_nCi ( N , i ) : NEW_LINE INDENT nfact = fact ( N ) NEW_LINE ifact = fact ( i ) NEW_LINE dfact = fact ( N - i ) NEW_LINE inv_ifact = binExp ( ifact , mod - 2 ) NEW_LINE inv_dfact = binExp ( dfact , mod - 2 ) NEW_LINE denm = ( ( ( inv_ifact % mod ) * ( inv_dfact % mod ) ) % mod ) NEW_LINE answer = ( ( ( nfact % mod ) * ( denm % mod ) ) % mod ) NEW_LINE return answer NEW_LINE DEDENT def countSubstring ( N , s , k ) : NEW_LINE INDENT allWays = binExp ( 26 , N ) NEW_LINE noWays = 0 NEW_LINE for i in range ( s ) : NEW_LINE INDENT nCi = calculate_nCi ( N , i ) NEW_LINE remaining = binExp ( 25 , N - i ) NEW_LINE multiply = ( ( ( nCi % mod ) * ( remaining % mod ) ) % mod ) NEW_LINE noWays = ( ( ( noWays % mod ) + ( multiply % mod ) ) % mod ) NEW_LINE DEDENT answer = ( ( ( allWays % mod ) - ( noWays % mod ) ) % mod ) NEW_LINE if ( answer < 0 ) : NEW_LINE INDENT answer += mod NEW_LINE DEDENT print ( answer ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " abc " NEW_LINE k = 2 NEW_LINE s = len ( st ) NEW_LINE N = s + k NEW_LINE countSubstring ( N , s , k ) NEW_LINE DEDENT |
Calculate Sum of ratio of special characters to length of substrings of the given string | Python3 program to implement the above approach ; Stores frequency of special characters in the array ; Stores prefix sum ; Function to check whether a character is special or not ; If current character is special ; Otherwise ; Function to find sum of ratio of count of special characters and length of substrings ; Calculate the prefix sum of special nodes ; Generate prefix sum array ; Calculate ratio for substring ; Driver Code | N = 100005 NEW_LINE prefix = [ 0 ] * N NEW_LINE sum = [ 0 ] * N NEW_LINE def isSpecial ( c , special ) : NEW_LINE INDENT for i in special : NEW_LINE INDENT if ( i == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def countRatio ( s , special ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix [ i ] = int ( isSpecial ( s [ i ] , special ) ) NEW_LINE if ( i > 0 ) : NEW_LINE INDENT prefix [ i ] += prefix [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT sum [ i ] = prefix [ i ] NEW_LINE if ( i > 0 ) : NEW_LINE INDENT sum [ i ] += sum [ i - 1 ] NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if i > 1 : NEW_LINE INDENT count = sum [ n - 1 ] - sum [ i - 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT count = sum [ n - 1 ] NEW_LINE DEDENT if i < n : NEW_LINE INDENT count -= sum [ n - i - 1 ] NEW_LINE DEDENT ans += count / i NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcd " NEW_LINE special = [ ' b ' , ' c ' ] NEW_LINE ans = countRatio ( s , special ) NEW_LINE print ( ' % .6f ' % ans ) NEW_LINE DEDENT |
Minimum replacements in a string to make adjacent characters unequal | Function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; Move j until characters s [ i ] & s [ j ] are equal or the end of the string is reached ; diff stores the length of the substring such that all the characters are equal in it ; We need atleast diff / 2 operations for this substring ; Driver code | def count_minimum ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT j = i NEW_LINE while j < n and ( s [ j ] == s [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT diff = j - i NEW_LINE ans += diff // 2 NEW_LINE i = j NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " caaab " NEW_LINE count_minimum ( str ) NEW_LINE DEDENT |
Minimum cost to convert given string to consist of only vowels | Function to find the minimum cost ; Store vowels ; Loop for iteration of string ; Loop to calculate the cost ; Add minimum cost ; Given String ; Function Call | def min_cost ( st ) : NEW_LINE INDENT vow = " aeiou " NEW_LINE cost = 0 NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT costs = [ ] NEW_LINE for j in range ( 5 ) : NEW_LINE INDENT costs . append ( abs ( ord ( st [ i ] ) - ord ( vow [ j ] ) ) ) NEW_LINE DEDENT cost += min ( costs ) NEW_LINE DEDENT return cost NEW_LINE DEDENT str = " abcde " NEW_LINE print ( min_cost ( str ) ) NEW_LINE |
Check if a given string is Even | Function to check if the string str is palindromic or not ; Pointers to iterate the string from both ends ; If characters are found to be distinct ; Return true if the string is palindromic ; Function to generate string from characters at odd indices ; Function to generate string from characters at even indices ; Functions to checks if string is Even - Odd Palindrome or not ; Generate odd indexed string ; Generate even indexed string ; Check for Palindrome ; Driver code | def isPalindrome ( Str ) : NEW_LINE INDENT l = 0 NEW_LINE h = len ( Str ) - 1 NEW_LINE while ( h > l ) : NEW_LINE INDENT if ( Str [ l ] != Str [ h ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def makeOddString ( Str ) : NEW_LINE INDENT odd = " " NEW_LINE for i in range ( 1 , len ( Str ) , 2 ) : NEW_LINE INDENT odd += Str [ i ] NEW_LINE DEDENT return odd NEW_LINE DEDENT def makeevenString ( Str ) : NEW_LINE INDENT even = " " NEW_LINE for i in range ( 0 , len ( Str ) , 2 ) : NEW_LINE INDENT even += Str [ i ] NEW_LINE DEDENT return even NEW_LINE DEDENT def checkevenOddPalindrome ( Str ) : NEW_LINE INDENT odd = makeOddString ( Str ) NEW_LINE even = makeevenString ( Str ) NEW_LINE if ( isPalindrome ( odd ) and isPalindrome ( even ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT Str = " abzzab " NEW_LINE checkevenOddPalindrome ( Str ) NEW_LINE |
Check given string is oddly palindrome or not | Function to check if the string str is palindromic or not ; Iterate the string str from left and right pointers ; Keep comparing characters while they are same ; If they are not same then return false ; Return true if the string is palindromic ; Function to make string using odd indices of string str ; Functions checks if characters at odd index of the string forms palindrome or not ; Make odd indexed string ; Check for Palindrome ; Given string ; Function call | def isPalindrome ( str ) : NEW_LINE INDENT l = 0 ; NEW_LINE h = len ( str ) - 1 ; NEW_LINE while ( h > l ) : NEW_LINE INDENT if ( str [ l ] != str [ h ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT return True ; NEW_LINE DEDENT def makeOddString ( str ) : NEW_LINE INDENT odd = " " ; NEW_LINE for i in range ( 1 , len ( str ) , 2 ) : NEW_LINE INDENT odd += str [ i ] ; NEW_LINE DEDENT return odd ; NEW_LINE DEDENT def checkOddlyPalindrome ( str ) : NEW_LINE INDENT odd = makeOddString ( str ) ; NEW_LINE if ( isPalindrome ( odd ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT str = " ddwfefwde " ; NEW_LINE checkOddlyPalindrome ( str ) ; NEW_LINE |
Count of binary strings of given length consisting of at least one 1 | Function to return the count of Strings ; Calculate pow ( 2 , n ) ; Return pow ( 2 , n ) - 1 ; Driver Code | def count_Strings ( n ) : NEW_LINE INDENT x = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT x = ( 1 << x ) ; NEW_LINE DEDENT return x - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE print ( count_Strings ( n ) ) ; NEW_LINE DEDENT |
String formed with middle character of every right substring followed by left sequentially | Function to decrypt and print the new string ; If the whole string has been traversed ; To calculate middle index of the string ; Print the character at middle index ; Recursively call for right - substring ; Recursive call for left - substring ; Driver Code | def decrypt ( Str , Start , End ) : NEW_LINE INDENT if ( Start > End ) : NEW_LINE INDENT return ; NEW_LINE DEDENT mid = ( Start + End ) >> 1 ; NEW_LINE print ( Str [ mid ] , end = " " ) ; NEW_LINE decrypt ( Str , mid + 1 , End ) ; NEW_LINE decrypt ( Str , Start , mid - 1 ) ; NEW_LINE DEDENT N = 4 ; NEW_LINE Str = " abcd " ; NEW_LINE decrypt ( Str , 0 , N - 1 ) ; NEW_LINE print ( ) ; NEW_LINE N = 6 ; NEW_LINE Str = " gyuitp " ; NEW_LINE decrypt ( Str , 0 , N - 1 ) ; NEW_LINE |
Check whether the binary equivalent of a number ends with given string or not | Function returns true if s1 is suffix of s2 ; Function to check if binary equivalent of a number ends in "111" or not ; To store the binary number ; Count used to store exponent value ; Driver code | def isSuffix ( s1 , s2 ) : NEW_LINE INDENT n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE if ( n1 > n2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( n1 ) : NEW_LINE INDENT if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def CheckBinaryEquivalent ( N , s ) : NEW_LINE INDENT B_Number = 0 ; NEW_LINE cnt = 0 ; NEW_LINE while ( N != 0 ) : NEW_LINE INDENT rem = N % 2 ; NEW_LINE c = pow ( 10 , cnt ) ; NEW_LINE B_Number += rem * c ; NEW_LINE N //= 2 ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT bin = str ( B_Number ) ; NEW_LINE return isSuffix ( s , bin ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 23 ; NEW_LINE s = "111" ; NEW_LINE if ( CheckBinaryEquivalent ( N , s ) ) : 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 if a character is vowel or not ; Function to check whether string contains only vowel ; Check if the character is not vowel then invalid ; Function to Count all substrings in a string which contains only vowels ; Generate all substring of s ; If temp contains only vowels ; Increment the count ; Driver code | 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 isvalid ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( not isvowel ( s [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def CountTotal ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = " " NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT temp += s [ j ] NEW_LINE if ( isvalid ( temp ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " aeoibsddaaeiouudb " NEW_LINE print ( CountTotal ( s ) ) NEW_LINE DEDENT |
Longest substring of vowels with no two adjacent alphabets same | Function to check a character is vowel or not ; Function to check a substring is valid or not ; If size is 1 then check only first character ; If 0 'th character is not vowel then invalid ; If two adjacent characters are same or i 'th char is not vowel then invalid ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid substring ; For current substring ; Check if substring is valid ; Size of substring is ( j - i + 1 ) ; Driver code | def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def isValid ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return ( isVowel ( s [ 0 ] ) ) NEW_LINE DEDENT if ( isVowel ( s [ 0 ] ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] or not isVowel ( s [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findMaxLen ( s ) : NEW_LINE INDENT maxLen = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = " " NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT temp = temp + s [ j ] NEW_LINE if ( isValid ( temp ) ) : NEW_LINE INDENT maxLen = ( max ( maxLen , ( j - i + 1 ) ) ) NEW_LINE DEDENT DEDENT DEDENT return maxLen NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Str = " aeoibsddaeiouudb " NEW_LINE print ( findMaxLen ( Str ) ) NEW_LINE DEDENT |
Check if the number is balanced | Function to check whether N is Balanced Number or not ; Calculating the Leftsum and rightSum simultaneously ; Typecasting each character to integer and adding the digit to respective sums ; Driver Code ; Function call | def BalancedNumber ( s ) : NEW_LINE INDENT Leftsum = 0 NEW_LINE Rightsum = 0 NEW_LINE for i in range ( 0 , int ( len ( s ) / 2 ) ) : NEW_LINE INDENT Leftsum = Leftsum + int ( s [ i ] ) NEW_LINE Rightsum = ( Rightsum + int ( s [ len ( s ) - 1 - i ] ) ) NEW_LINE DEDENT if ( Leftsum == Rightsum ) : NEW_LINE INDENT print ( " Balanced " , end = ' ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Balanced " , end = ' ' ) NEW_LINE DEDENT DEDENT s = "12321" NEW_LINE BalancedNumber ( s ) NEW_LINE |
Count of N size strings consisting of at least one vowel and one consonant | Python3 program to count all possible strings of length N consisting of atleast one vowel and one consonant ; Function to return base ^ exponent ; Function to count all possible strings ; All possible strings of length N ; vowels only ; consonants only ; Return the final result ; Driver Program | mod = 1e9 + 7 NEW_LINE def expo ( base , exponent ) : NEW_LINE INDENT ans = 1 NEW_LINE while ( exponent != 0 ) : NEW_LINE INDENT if ( ( exponent & 1 ) == 1 ) : NEW_LINE INDENT ans = ans * base NEW_LINE ans = ans % mod NEW_LINE DEDENT base = base * base NEW_LINE base %= mod NEW_LINE exponent >>= 1 NEW_LINE DEDENT return ans % mod NEW_LINE DEDENT def findCount ( N ) : NEW_LINE INDENT ans = ( ( expo ( 26 , N ) - expo ( 5 , N ) - expo ( 21 , N ) ) % mod ) NEW_LINE ans += mod NEW_LINE ans %= mod NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( int ( findCount ( N ) ) ) NEW_LINE DEDENT |
Sum of decomposition values of all suffixes of an Array | Python3 implementation to find the sum of Decomposition values of all suffixes of an array ; Function to find the decomposition values of the array ; Stack ; Variable to maintain min value in stack ; Loop to iterate over the array ; Condition to check if the stack is empty ; Condition to check if the top of the stack is greater than the current element ; Loop to pop the element out ; The size of the stack is the max no of subarrays for suffix till index i from the right ; Driver Code | import sys NEW_LINE def decompose ( S ) : NEW_LINE INDENT s = [ ] NEW_LINE N = len ( S ) NEW_LINE ans = 0 NEW_LINE nix = sys . maxsize NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( S [ i ] ) NEW_LINE nix = S [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT if ( S [ i ] < s [ - 1 ] ) : NEW_LINE INDENT s . append ( S [ i ] ) NEW_LINE nix = min ( nix , S [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT val = S [ i ] NEW_LINE while ( len ( s ) != 0 and val >= s [ - 1 ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT nix = min ( nix , S [ i ] ) ; NEW_LINE s . append ( nix ) NEW_LINE DEDENT DEDENT ans += len ( s ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = [ 9 , 6 , 9 , 35 ] NEW_LINE print ( decompose ( S ) ) NEW_LINE DEDENT |
Maximum number of set bits count in a K | Function that find Maximum number of set bit appears in a substring of size K . ; Traverse string 1 to k ; Increment count if character is set bit ; Traverse string k + 1 to length of string ; Remove the contribution of the ( i - k ) th character which is no longer in the window ; Add the contribution of the current character ; Update maxCount at for each window of size k ; Return maxCount ; Driver code | def maxSetBitCount ( s , k ) : NEW_LINE INDENT maxCount = 0 NEW_LINE n = len ( s ) NEW_LINE count = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT maxCount = count NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT if ( s [ i - k ] == '1' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT maxCount = max ( maxCount , count ) NEW_LINE DEDENT return maxCount NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "100111010" NEW_LINE k = 3 NEW_LINE print ( maxSetBitCount ( s , k ) ) NEW_LINE DEDENT |
Minimum characters to be deleted from the beginning of two strings to make them equal | Function that finds minimum character required to be deleted ; Iterate in the strings ; Check if the characters are not equal ; Return the result ; Driver code | def minDel ( s1 , s2 ) : NEW_LINE INDENT i = len ( s1 ) NEW_LINE j = len ( s2 ) NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( s1 [ i - 1 ] != s2 [ j - 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT return i + j NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " geeksforgeeks " NEW_LINE s2 = " peeks " NEW_LINE print ( minDel ( s1 , s2 ) ) NEW_LINE DEDENT |
Minimum characters to be deleted from the end to make given two strings equal | Function that finds minimum character required to be deleted ; Iterate in the strings ; Check if the characters are not equal ; Return the result ; Driver code | def minDel ( s1 , s2 ) : NEW_LINE INDENT i = 0 ; NEW_LINE while ( i < min ( len ( s1 ) , len ( s2 ) ) ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT ans = ( ( len ( s1 ) - i ) + ( len ( s2 ) - i ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " geeks " ; NEW_LINE s2 = " geeksfor " ; NEW_LINE print ( minDel ( s1 , s2 ) ) ; NEW_LINE DEDENT |
Check if given Parentheses expression is balanced or not | Function to check if parenthesis are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more closing parenthesis than opening ; If count is not zero , it means there are more opening parenthesis ; Driver code | def isBalanced ( exp ) : NEW_LINE INDENT flag = True NEW_LINE count = 0 NEW_LINE for i in range ( len ( exp ) ) : NEW_LINE INDENT if ( exp [ i ] == ' ( ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < 0 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( count != 0 ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT return flag NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT exp1 = " ( ( ( ) ) ) ( ) ( ) " NEW_LINE if ( isBalanced ( exp1 ) ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Balanced " ) NEW_LINE DEDENT exp2 = " ( ) ) ( ( ( ) ) " NEW_LINE if ( isBalanced ( exp2 ) ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Balanced " ) NEW_LINE DEDENT DEDENT |
Check if a given string can be formed using characters of adjacent cells of a Matrix | Function to check if the word exists ; If index exceeds board range ; If the current cell does not contain the required character ; If the cell contains the required character and is the last character of the word required to be matched ; Return true as word is found ; Mark cell visited ; Check Adjacent cells for the next character ; Restore cell value ; Driver Code | def checkWord ( board , word , index , row , col ) : NEW_LINE INDENT if ( row < 0 or col < 0 or row >= len ( board ) or col >= len ( board [ 0 ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( board [ row ] [ col ] != word [ index ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( index == len ( word ) - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT temp = board [ row ] [ col ] NEW_LINE board [ row ] [ col ] = ' * ' NEW_LINE if ( checkWord ( board , word , index + 1 , row + 1 , col ) or checkWord ( board , word , index + 1 , row - 1 , col ) or checkWord ( board , word , index + 1 , row , col + 1 ) or checkWord ( board , word , index + 1 , row , col - 1 ) ) : NEW_LINE INDENT board [ row ] [ col ] = temp NEW_LINE return True NEW_LINE DEDENT board [ row ] [ col ] = temp NEW_LINE return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT board = [ [ ' A ' , ' B ' , ' C ' , ' E ' ] , [ ' S ' , ' F ' , ' C ' , ' S ' ] , [ ' A ' , ' D ' , ' E ' , ' E ' ] ] NEW_LINE word = " CFDASABCESEE " NEW_LINE f = 0 NEW_LINE for i in range ( len ( board ) ) : NEW_LINE INDENT for j in range ( len ( board [ 0 ] ) ) : NEW_LINE INDENT if ( board [ i ] [ j ] == word [ 0 ] and checkWord ( board , word , 0 , i , j ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if f == 1 : NEW_LINE break NEW_LINE DEDENT if f == 0 : NEW_LINE print ( " False " ) NEW_LINE DEDENT |
Split the number N by maximizing the count of subparts divisible by K | Function to count the subparts ; Total subStr till now ; If it can be divided , then this substring is one of the possible answer ; Convert string to long long and check if its divisible with X ; Consider there is no vertical cut between this index and the next one , hence take total carrying total substr a . ; If there is vertical cut between this index and next one , then we start again with subStr as " " and add b for the count of subStr upto now ; Return max of both the cases ; Driver code | def count ( N , X , subStr , index , n ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT a = subStr + N [ index ] NEW_LINE b = 0 NEW_LINE if ( int ( a ) % X == 0 ) : NEW_LINE INDENT b = 1 NEW_LINE DEDENT m1 = count ( N , X , a , index + 1 , n ) NEW_LINE m2 = b + count ( N , X , " " , index + 1 , n ) NEW_LINE return max ( m1 , m2 ) NEW_LINE DEDENT N = "00001242" NEW_LINE K = 3 NEW_LINE l = len ( N ) NEW_LINE print ( count ( N , K , " " , 0 , l ) ) NEW_LINE |
Check if a number ends with another number or not | Function to check if B is a suffix of A or not ; Convert numbers into strings ; Find the lengths of strings s1 and s2 ; Base Case ; Traverse the strings s1 & s2 ; If at any index characters are unequals then return false ; Return true ; Given numbers ; Function Call ; If B is a suffix of A , then print " Yes " | def checkSuffix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) ; NEW_LINE s2 = str ( B ) ; NEW_LINE n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE if ( n1 < n2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT A = 12345 NEW_LINE B = 45 ; NEW_LINE result = checkSuffix ( A , B ) ; NEW_LINE if ( result ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Check if a number ends with another number or not | Function to check if B is a suffix of A or not ; Convert numbers into strings ; Check if s2 is a suffix of s1 or not ; If result is true print " Yes " ; Driver code ; Given numbers ; Function call | def checkSuffix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) NEW_LINE s2 = str ( B ) NEW_LINE result = s1 . endswith ( s2 ) NEW_LINE if ( result ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 12345 NEW_LINE B = 45 NEW_LINE checkSuffix ( A , B ) NEW_LINE DEDENT |
Binary string with given frequencies of sums of consecutive pairs of characters | A Function that generates and returns the binary string ; P : Frequency of consecutive characters with sum 0 Q : Frequency of consecutive characters with sum 1 R : Frequency of consecutive characters with sum 2 ; If no consecutive character adds up to 1 ; Not possible if both P and Q are non - zero ; If P is not equal to 0 ; Append 0 P + 1 times ; Append 1 R + 1 times ; Append "01" to satisfy Q ; Append "0" P times ; Append "1" R times ; Driver Code | def build_binary_str ( p , q , r ) : NEW_LINE INDENT ans = " " NEW_LINE if ( q == 0 ) : NEW_LINE INDENT if ( p != 0 and r != 0 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT else : NEW_LINE INDENT if ( p ) : NEW_LINE INDENT temp = " " NEW_LINE for i in range ( p + 1 ) : NEW_LINE INDENT temp += '0' NEW_LINE DEDENT ans = temp NEW_LINE DEDENT else : NEW_LINE INDENT temp = " " NEW_LINE for i in range ( r + 1 ) : NEW_LINE INDENT temp += '1' NEW_LINE DEDENT ans = temp NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 1 , q + 2 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT ans += '0' NEW_LINE DEDENT else : NEW_LINE INDENT ans += '1' NEW_LINE DEDENT DEDENT temp = " " NEW_LINE for i in range ( p ) : NEW_LINE INDENT temp += '0' NEW_LINE DEDENT st = " " NEW_LINE st += ans [ 0 ] NEW_LINE st += temp NEW_LINE for i in range ( 1 , len ( ans ) ) : NEW_LINE INDENT st += ans [ i ] NEW_LINE DEDENT ans = st NEW_LINE temp = " " NEW_LINE for i in range ( r ) : NEW_LINE INDENT temp += '1' NEW_LINE DEDENT ans = temp + ans NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 1 NEW_LINE q = 2 NEW_LINE r = 2 NEW_LINE print ( build_binary_str ( p , q , r ) ) NEW_LINE DEDENT |
Check if there exists a permutation of given string which doesn 't contain any monotonous substring | Function to check a string doesn 't contains a monotonous substring ; Loop to iterate over the string and check that it doesn 't contains the monotonous substring ; Function to check that there exist a arrangement of string such that it doesn 't contains monotonous substring ; Loop to group the characters of the string into two buckets ; Sorting the two buckets ; Condition to check if the concatenation point doesn 't contains the monotonous string ; Driver Code | def check ( s ) : NEW_LINE INDENT ok = True NEW_LINE for i in range ( 0 , len ( s ) - 1 , 1 ) : NEW_LINE INDENT ok = ( ok & ( abs ( ord ( s [ i ] ) - ord ( s [ i + 1 ] ) ) != 1 ) ) NEW_LINE DEDENT return ok NEW_LINE DEDENT def monotonousString ( s ) : NEW_LINE INDENT odd = " " NEW_LINE even = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) % 2 == 0 ) : NEW_LINE INDENT odd += s [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT even += s [ i ] NEW_LINE DEDENT DEDENT odd = list ( odd ) NEW_LINE odd . sort ( reverse = False ) NEW_LINE odd = str ( odd ) NEW_LINE even = list ( even ) NEW_LINE even . sort ( reverse = False ) NEW_LINE even = str ( even ) NEW_LINE if ( check ( odd + even ) ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT elif ( check ( even + odd ) ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abcd " NEW_LINE ans = monotonousString ( str1 ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Length of the smallest substring which contains all vowels | Function to return the index for respective vowels to increase their count ; Returns - 1 for consonants ; Function to find the minimum length ; Store the starting index of the current substring ; Store the frequencies of vowels ; If the current character is a vowel ; Increase its count ; Move start as much right as possible ; Condition for valid substring ; Driver code | def get_index ( ch ) : NEW_LINE INDENT if ( ch == ' a ' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( ch == ' e ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( ch == ' i ' ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif ( ch == ' o ' ) : NEW_LINE INDENT return 3 NEW_LINE DEDENT elif ( ch == ' u ' ) : NEW_LINE INDENT return 4 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def findMinLength ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = n + 1 NEW_LINE start = 0 NEW_LINE count = [ 0 ] * 5 NEW_LINE for x in range ( n ) : NEW_LINE INDENT idx = get_index ( s [ x ] ) NEW_LINE if ( idx != - 1 ) : NEW_LINE INDENT count [ idx ] += 1 NEW_LINE DEDENT idx_start = get_index ( s [ start ] ) NEW_LINE while ( idx_start == - 1 or count [ idx_start ] > 1 ) : NEW_LINE INDENT if ( idx_start != - 1 ) : NEW_LINE INDENT count [ idx_start ] -= 1 NEW_LINE DEDENT start += 1 NEW_LINE if ( start < n ) : NEW_LINE INDENT idx_start = get_index ( s [ start ] ) NEW_LINE DEDENT DEDENT if ( count [ 0 ] > 0 and count [ 1 ] > 0 and count [ 2 ] > 0 and count [ 3 ] > 0 and count [ 4 ] > 0 ) : NEW_LINE INDENT ans = min ( ans , x - start + 1 ) NEW_LINE DEDENT DEDENT if ( ans == n + 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aaeebbeaccaaoiuooooooooiuu " NEW_LINE print ( findMinLength ( s ) ) NEW_LINE DEDENT |
Number of strings which starts and ends with same character after rotations | Function to find the count of string with equal end after rotations ; To store the final count ; Traverse the string ; If current character is same as the previous character then increment the count ; Return the final count ; Driver Code ; Given string ; Function call | def countStrings ( s ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( 1 , len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aacbb " ; NEW_LINE print ( countStrings ( str ) ) ; NEW_LINE DEDENT |
Check if frequency of each character is equal to its position in English Alphabet | Python3 program for the above approach ; Initialise frequency array ; Traverse the string ; Update the frequency ; Check for valid string ; If frequency is non - zero ; If freq is not equals to ( i + 1 ) , then return false ; Return true ; Given string str | def checkValidString ( str ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT if ( freq [ i ] != i + 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT str = " abbcccdddd " NEW_LINE if ( checkValidString ( str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Print all the non | Function to print all the non - repeating words from the two given sentences ; Concatenate the two strings into one ; Iterating over the whole concatenated string ; Searching for the word in A . If while searching , we reach the end of the string , then the word is not present in the string ; Initialise word for the next iteration ; Driver code | def removeRepeating ( s1 , s2 ) : NEW_LINE INDENT s3 = s1 + " β " + s2 + " β " NEW_LINE words = " " NEW_LINE i = 0 NEW_LINE for x in s3 : NEW_LINE INDENT if ( x == ' β ' ) : NEW_LINE INDENT if ( words not in s1 or words not in s2 ) : NEW_LINE INDENT print ( words , end = " " ) NEW_LINE DEDENT words = " β " NEW_LINE DEDENT else : NEW_LINE INDENT words = words + x NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " I β have β go β a β pen " NEW_LINE s2 = " I β want β to β go β park " NEW_LINE removeRepeating ( s1 , s2 ) NEW_LINE DEDENT |
Convert the number from International system to Indian system | Function to convert a number represented in International numeric system to Indian numeric system . ; Find the length of the input string ; Removing all the separators ( , ) from the input string ; Reverse the input string ; Declaring the output string ; Process the input string ; Add a separator ( , ) after the third number ; Then add a separator ( , ) after every second number ; Reverse the output string ; Return the output string back to the main function ; Driver code | def convert ( input ) : NEW_LINE INDENT Len = len ( input ) NEW_LINE i = 0 NEW_LINE while ( i < Len ) : NEW_LINE INDENT if ( input [ i ] == " , " ) : NEW_LINE INDENT input = input [ : i ] + input [ i + 1 : ] NEW_LINE Len -= 1 NEW_LINE i -= 1 NEW_LINE DEDENT elif ( input [ i ] == " β " ) : NEW_LINE INDENT input = input [ : i ] + input [ i + 1 : ] NEW_LINE Len -= 1 NEW_LINE i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT input = input [ : : - 1 ] NEW_LINE output = " " NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( i == 2 ) : NEW_LINE INDENT output += input [ i ] NEW_LINE output += " β , " NEW_LINE DEDENT elif ( i > 2 and i % 2 == 0 and i + 1 < Len ) : NEW_LINE INDENT output += input [ i ] NEW_LINE output += " β , " NEW_LINE DEDENT else : NEW_LINE INDENT output += input [ i ] NEW_LINE DEDENT DEDENT output = output [ : : - 1 ] NEW_LINE return output NEW_LINE DEDENT input1 = "123 , β 456 , β 789" NEW_LINE input2 = "90 , β 050 , β 000 , β 000" NEW_LINE print ( convert ( input1 ) ) NEW_LINE print ( convert ( input2 ) ) NEW_LINE |
Construct the Cypher string based on the given conditions | Python3 program for the above approach ; Function to check whether a number is prime or not ; Function to check if a prime number can be expressed as sum of two Prime Numbers ; If the N && ( N - 2 ) is Prime ; Function to check semiPrime ; Loop from 2 to sqrt ( num ) ; Increment the count of prime numbers ; If num is greater than 1 , then add 1 to it ; Return '1' if count is 2 else return '0 ; Function to make the Cypher string ; Resultant string ; Make string for the number N ; Check for semiPrime ; Traverse to make Cypher string ; If index is odd add the current character ; Else current character is changed ; Check for sum of two primes ; Traverse to make Cypher string ; If index is odd then current character is changed ; Else add the current character ; If the resultant string is " " then print - 1 ; Else print the resultant string ; Driver Code ; Given number ; Function call | import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT sqt = ( int ) ( math . sqrt ( n ) ) NEW_LINE for i in range ( 2 , sqt ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPossibleSum ( N ) : NEW_LINE INDENT if ( isPrime ( N ) and isPrime ( N - 2 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def checkSemiprime ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE i = 2 NEW_LINE while cnt < 2 and i * i <= num : NEW_LINE INDENT while ( num % i == 0 ) : NEW_LINE INDENT num //= i NEW_LINE cnt += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( num > 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT return cnt == 2 NEW_LINE DEDENT def makeCypherString ( N ) : NEW_LINE INDENT semiPrime = " " NEW_LINE sumOfPrime = " " NEW_LINE st = str ( N ) NEW_LINE if ( checkSemiprime ( N ) ) : NEW_LINE INDENT for i in range ( len ( st ) ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT semiPrime += st [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT semiPrime += chr ( ord ( st [ i ] ) - ord ( '0' ) + 65 ) NEW_LINE DEDENT DEDENT DEDENT if ( isPossibleSum ( N ) ) : NEW_LINE INDENT for i in range ( len ( st ) ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT sumOfPrime += chr ( ord ( st [ i ] ) - ord ( '0' ) + 65 ) NEW_LINE DEDENT else : NEW_LINE INDENT sumOfPrime += st [ i ] NEW_LINE DEDENT DEDENT DEDENT if ( semiPrime + sumOfPrime == " " ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( semiPrime + sumOfPrime ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 1011243 NEW_LINE makeCypherString ( N ) NEW_LINE DEDENT |
Maximum splits in binary string such that each substring is divisible by given odd number | Function to calculate maximum splits possible ; Driver code | def max_segments ( st , K ) : NEW_LINE INDENT n = len ( st ) NEW_LINE s , sum , count = 0 , 0 , 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT a = ord ( st [ i ] ) - 48 NEW_LINE sum += a * pow ( 2 , s ) NEW_LINE s += 1 NEW_LINE if ( sum != 0 and sum % K == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE sum = 0 NEW_LINE s = 0 NEW_LINE DEDENT DEDENT if ( sum != 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( count ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "10111001" NEW_LINE K = 5 NEW_LINE max_segments ( st , K ) NEW_LINE DEDENT |
Make the string lexicographically smallest and non palindromic by replacing exactly one character | Function to find the required string ; Length of the string ; Iterate till half of the string ; Replacing a non ' a ' char with 'a ; Check if there is no ' a ' in string we replace last char of string by 'b ; If the input is a single character ; Driver Code | def findStr ( S ) : NEW_LINE INDENT S = list ( S ) NEW_LINE n = len ( S ) NEW_LINE for i in range ( 0 , n // 2 ) : NEW_LINE DEDENT ' NEW_LINE INDENT if S [ i ] != ' a ' : NEW_LINE INDENT S [ i ] = ' a ' NEW_LINE return ( ' ' . join ( S ) ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT S [ n - 1 ] = ' b ' NEW_LINE if n < 2 : NEW_LINE INDENT return ' - 1' NEW_LINE DEDENT else : NEW_LINE INDENT return ( ' ' . join ( S ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = ' a ' NEW_LINE print ( findStr ( str1 ) ) NEW_LINE str2 = ' abccba ' NEW_LINE print ( findStr ( str2 ) ) NEW_LINE DEDENT |
Find the k | Function to find the Kth string in lexicographical order which consists of N - 2 xs and 2 ys ; Iterate for all possible positions of left most Y ; If i is the left most position of Y ; Put Y in their positions ; Driver code ; Function call | def kth_string ( n , k ) : NEW_LINE INDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if k <= ( n - i - 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( j == i or j == n - k ) : NEW_LINE INDENT print ( ' Y ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' X ' , end = " " ) NEW_LINE DEDENT DEDENT break NEW_LINE DEDENT k -= ( n - i - 1 ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE k = 7 NEW_LINE kth_string ( n , k ) NEW_LINE |
Transform string str1 into str2 by taking characters from string str3 | Function to check whether str1 can be transformed to str2 ; To store the frequency of characters of string str3 ; Declare two pointers & flag ; Traverse both the string and check whether it can be transformed ; If both pointers point to same characters increment them ; If the letters don 't match check if we can find it in string C ; If the letter is available in string str3 , decrement it 's frequency & increment the ptr2 ; If letter isn 't present in str3[] set the flag to false and break ; If the flag is true and both pointers points to their end of respective strings then it is possible to transformed str1 into str2 , otherwise not . ; Driver Code ; Function Call | def convertString ( str1 , str2 , str3 ) : NEW_LINE INDENT freq = { } NEW_LINE for i in range ( len ( str3 ) ) : NEW_LINE INDENT if ( freq . get ( str3 [ i ] ) == None ) : NEW_LINE INDENT freq [ str3 [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq . get ( str3 [ i ] , 1 ) NEW_LINE DEDENT DEDENT ptr1 = 0 NEW_LINE ptr2 = 0 ; NEW_LINE flag = True NEW_LINE while ( ptr1 < len ( str1 ) and ptr2 < len ( str2 ) ) : NEW_LINE INDENT if ( str1 [ ptr1 ] == str2 [ ptr2 ] ) : NEW_LINE INDENT ptr1 += 1 NEW_LINE ptr2 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( freq [ str3 [ ptr2 ] ] > 0 ) : NEW_LINE INDENT freq [ str3 [ ptr2 ] ] -= 1 NEW_LINE ptr2 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( flag and ptr1 == len ( str1 ) and ptr2 == len ( str2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abyzfe " NEW_LINE str2 = " abcdeyzf " NEW_LINE str3 = " popode " NEW_LINE convertString ( str1 , str2 , str3 ) NEW_LINE DEDENT |
Decrypt the String according to given algorithm | Python3 implementation of the approach ; Function that returns ( num % 26 ) ; Initialize result ; One by one process all digits of 'num ; Function to return the decrypted string ; To store the final decrypted answer ; One by one check for each character if it is a numeric character ; Modulo the number found in the string by 26 ; Driver code ; Print the decrypted string | MOD = 26 NEW_LINE def modulo_by_26 ( num ) : NEW_LINE INDENT res = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( num ) ) : NEW_LINE INDENT res = ( ( res * 10 + ord ( num [ i ] ) - ord ( '0' ) ) % MOD ) NEW_LINE DEDENT return res NEW_LINE DEDENT def decrypt_message ( s ) : NEW_LINE INDENT decrypted_str = " " NEW_LINE num_found_so_far = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] >= '0' and s [ i ] <= '9' ) : NEW_LINE INDENT num_found_so_far += s [ i ] NEW_LINE DEDENT elif ( len ( num_found_so_far ) > 0 ) : NEW_LINE INDENT decrypted_str += chr ( ord ( ' a ' ) + ( modulo_by_26 ( num_found_so_far ) ) ) NEW_LINE num_found_so_far = " " NEW_LINE DEDENT DEDENT if ( len ( num_found_so_far ) > 0 ) : NEW_LINE INDENT decrypted_str += chr ( ord ( ' a ' ) + ( modulo_by_26 ( num_found_so_far ) ) ) NEW_LINE DEDENT return decrypted_str NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "32ytAAcV4ui30hf10hj18" NEW_LINE print ( decrypt_message ( s ) ) NEW_LINE DEDENT |
Maximum number of overlapping string | Function to find the maximum overlapping strings ; Get the current character ; Condition to check if the current character is the first character of the string T then increment the overlapping count ; Condition to check previous character is also occurred ; Update count of previous and current character ; Condition to check the current character is the last character of the string T ; Condition to check the every subsequence is a valid string T ; Driver Code ; Function Call | def maxOverlap ( S , T ) : NEW_LINE INDENT str = T NEW_LINE count = [ 0 for i in range ( len ( T ) ) ] NEW_LINE overlap = 0 NEW_LINE max_overlap = 0 NEW_LINE for i in range ( 0 , len ( S ) ) : NEW_LINE INDENT index = str . find ( S [ i ] ) NEW_LINE if ( index == 0 ) : NEW_LINE INDENT overlap += 1 NEW_LINE if ( overlap >= 2 ) : NEW_LINE INDENT max_overlap = max ( overlap , max_overlap ) NEW_LINE DEDENT count [ index ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count [ index - 1 ] <= 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT count [ index ] += 1 NEW_LINE count [ index - 1 ] -= 1 NEW_LINE DEDENT if ( index == 4 ) : NEW_LINE INDENT overlap -= 1 NEW_LINE DEDENT DEDENT if ( overlap == 0 ) : NEW_LINE INDENT return max_overlap NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT S = " chcirphirp " NEW_LINE T = " chirp " NEW_LINE print ( maxOverlap ( S , T ) ) NEW_LINE |
Minimum number of operations required to make two strings equal | Python3 implementation to find the minimum number of operations to make two strings equal ; Function to find out parent of an alphabet ; Function to merge two different alphabets ; Merge a and b using rank compression ; Function to find the minimum number of operations required ; Initializing parent to i and rank ( size ) to 1 ; We will store our answerin this list ; Traversing strings ; If they have different parents ; Find their respective parents and merge them ; Store this in our Answer list ; Number of operations ; Driver code ; Two strings S1 and S2 ; Function Call | MAX = 500001 NEW_LINE parent = [ 0 ] * MAX NEW_LINE Rank = [ 0 ] * MAX NEW_LINE def find ( x ) : NEW_LINE INDENT if parent [ x ] == x : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return find ( parent [ x ] ) NEW_LINE DEDENT DEDENT def merge ( r1 , r2 ) : NEW_LINE INDENT if ( r1 != r2 ) : NEW_LINE INDENT if ( Rank [ r1 ] > Rank [ r2 ] ) : NEW_LINE INDENT parent [ r2 ] = r1 NEW_LINE Rank [ r1 ] += Rank [ r2 ] NEW_LINE DEDENT else : NEW_LINE INDENT parent [ r1 ] = r2 NEW_LINE Rank [ r2 ] += Rank [ r1 ] NEW_LINE DEDENT DEDENT DEDENT def minimumOperations ( s1 , s2 ) : NEW_LINE INDENT for i in range ( 1 , 26 + 1 ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE Rank [ i ] = 1 NEW_LINE DEDENT ans = [ ] NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT if ( find ( ord ( s1 [ i ] ) - 96 ) != find ( ord ( s2 [ i ] ) - 96 ) ) : NEW_LINE INDENT x = find ( ord ( s1 [ i ] ) - 96 ) NEW_LINE y = find ( ord ( s2 [ i ] ) - 96 ) NEW_LINE merge ( x , y ) NEW_LINE ans . append ( [ s1 [ i ] , s2 [ i ] ] ) NEW_LINE DEDENT DEDENT DEDENT print ( len ( ans ) ) NEW_LINE for i in ans : NEW_LINE INDENT print ( i [ 0 ] , " - > " , i [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " abb " NEW_LINE s2 = " dad " NEW_LINE minimumOperations ( s1 , s2 ) NEW_LINE DEDENT |
Find the N | Function to calculate nth permutation of string ; Creating an empty list ; Subtracting 1 from N because the permutations start from 0 in factroid method ; Loop to generate the factroid of the sequence ; Loop to generate nth permutation ; Remove 1 - element in each cycle ; Final answer ; Driver code | def string_permutation ( n , str ) : NEW_LINE INDENT s = [ ] NEW_LINE result = " " NEW_LINE str = list ( str ) NEW_LINE n = n - 1 NEW_LINE for i in range ( 1 , len ( str ) + 1 ) : NEW_LINE INDENT s . append ( n % i ) NEW_LINE n = int ( n / i ) NEW_LINE DEDENT for i in range ( len ( str ) ) : NEW_LINE INDENT a = s [ - 1 ] NEW_LINE result += str [ a ] NEW_LINE for j in range ( a , len ( str ) - 1 ) : NEW_LINE INDENT str [ j ] = str [ j + 1 ] NEW_LINE DEDENT str [ j + 1 ] = ' \0' NEW_LINE s . pop ( ) NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT str = " abcde " NEW_LINE n = 11 NEW_LINE string_permutation ( n , str ) NEW_LINE |
Defanged Version of Internet Protocol Address | Function to generate a defanged version of IP address . ; Loop to iterate over the characters of the string ; Driver Code | def GeberateDefangIP ( str ) : NEW_LINE INDENT defangIP = " " ; NEW_LINE for c in str : NEW_LINE INDENT if ( c == ' . ' ) : NEW_LINE INDENT defangIP += " [ . ] " NEW_LINE DEDENT else : NEW_LINE INDENT defangIP += c ; NEW_LINE DEDENT DEDENT return defangIP ; NEW_LINE DEDENT str = "255.100.50.0" ; NEW_LINE print ( GeberateDefangIP ( str ) ) ; NEW_LINE |
Longest palindromic string formed by concatenation of prefix and suffix of a string | Function used to calculate the longest prefix which is also a suffix ; Traverse the string ; Update the lps size ; Returns size of lps ; Function to calculate the length of longest palindromic substring which is either a suffix or prefix ; Append a character to separate the string and reverse of the string ; Reverse the string ; Append the reversed string ; Function to find the Longest palindromic string formed from concatenation of prefix and suffix of a given string ; Calculating the length for which prefix is reverse of suffix ; Append prefix to the answer ; Store the remaining string ; If the remaining string is not empty that means that there can be a palindrome substring which can be added between the suffix & prefix ; Calculate the length of longest prefix palindromic substring ; Reverse the given string to find the longest palindromic suffix ; Calculate the length of longest prefix palindromic substring ; If the prefix palindrome is greater than the suffix palindrome ; Append the prefix to the answer ; If the suffix palindrome is greater than the prefix palindrome ; Append the suffix to the answer ; Finally append the suffix to the answer ; Return the answer string ; Driver Code | def kmp ( s ) : NEW_LINE INDENT lps = [ 0 ] * ( len ( s ) ) NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT previous_index = lps [ i - 1 ] NEW_LINE while ( previous_index > 0 and s [ i ] != s [ previous_index ] ) : NEW_LINE INDENT previous_index = lps [ previous_index - 1 ] NEW_LINE DEDENT lps [ i ] = previous_index NEW_LINE if ( s [ i ] == s [ previous_index ] ) : NEW_LINE INDENT lps [ i ] += 1 NEW_LINE DEDENT DEDENT return lps [ - 1 ] NEW_LINE DEDENT def remainingStringLongestPallindrome ( s ) : NEW_LINE INDENT t = s + " ? " NEW_LINE s = s [ : : - 1 ] NEW_LINE t += s NEW_LINE return kmp ( t ) NEW_LINE DEDENT def longestPrefixSuffixPallindrome ( s ) : NEW_LINE INDENT length = 0 NEW_LINE n = len ( s ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while i < j : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE length += 1 NEW_LINE DEDENT ans = s [ 0 : length ] NEW_LINE remaining = s [ length : length + ( n - ( 2 * length ) ) ] NEW_LINE if ( len ( remaining ) ) : NEW_LINE INDENT longest_prefix = remainingStringLongestPallindrome ( remaining ) ; NEW_LINE remaining = remaining [ : : - 1 ] NEW_LINE longest_suffix = remainingStringLongestPallindrome ( remaining ) ; NEW_LINE if ( longest_prefix > longest_suffix ) : NEW_LINE INDENT remaining = remaining [ : : - 1 ] NEW_LINE ans += remaining [ 0 : longest_prefix ] NEW_LINE DEDENT else : NEW_LINE INDENT ans += remaining [ 0 : longest_suffix ] NEW_LINE DEDENT DEDENT ans += s [ n - length : n ] NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " rombobinnimor " NEW_LINE print ( longestPrefixSuffixPallindrome ( st ) ) NEW_LINE DEDENT |
Generate a string with maximum possible alphabets with odd frequencies | Function to generate a string of length n with maximum possible alphabets each occuring odd number of times . ; If n is odd ; Add all characters from b - y ; Append a to fill the remaining length ; If n is even ; Add all characters from b - z ; Append a to fill the remaining length ; Driver code | def generateTheString ( n ) : NEW_LINE INDENT ans = " " NEW_LINE if ( n % 2 ) : NEW_LINE INDENT for i in range ( min ( n , 24 ) ) : NEW_LINE INDENT ans += chr ( ord ( ' b ' ) + i ) NEW_LINE DEDENT if ( n > 24 ) : NEW_LINE INDENT for i in range ( ( n - 24 ) ) : NEW_LINE INDENT ans += ' a ' NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( min ( n , 25 ) ) : NEW_LINE INDENT ans += chr ( ord ( ' b ' ) + i ) NEW_LINE DEDENT if ( n > 25 ) : NEW_LINE INDENT for i in range ( ( n - 25 ) ) : NEW_LINE INDENT ans += ' a ' NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 34 NEW_LINE print ( generateTheString ( n ) ) NEW_LINE DEDENT |
Move all occurrence of letter ' x ' from the string s to the end using Recursion | Function to move all ' x ' in the end ; Store current character ; Check if current character is not 'x ; Recursive function call ; Check if current character is 'x ; Driver code | def moveAtEnd ( s , i , l ) : NEW_LINE INDENT if ( i >= l ) : NEW_LINE return NEW_LINE curr = s [ i ] NEW_LINE DEDENT ' NEW_LINE INDENT if ( curr != ' x ' ) : NEW_LINE INDENT print ( curr , end = " " ) NEW_LINE DEDENT moveAtEnd ( s , i + 1 , l ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( curr == ' x ' ) : NEW_LINE INDENT print ( curr , end = " " ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geekxsforgexxeksxx " NEW_LINE l = len ( s ) NEW_LINE moveAtEnd ( s , 0 , l ) NEW_LINE DEDENT |
Construct a string of length L such that each substring of length X has exactly Y distinct letters | Python implementation to construct a string of length L such that each substring of length X has exactly Y distinct letters . ; Initialize p equal to the ASCII value of a ; Iterate till the length of the string ; Driver code | def String ( l , x , y ) : NEW_LINE INDENT p = 97 NEW_LINE for j in range ( l ) : NEW_LINE INDENT ans = chr ( p + j % y ) NEW_LINE print ( ans , end = " " ) NEW_LINE DEDENT DEDENT l = 6 NEW_LINE x = 5 NEW_LINE y = 3 NEW_LINE String ( l , x , y ) NEW_LINE |
Find the final co | Function to print the final position of the point after traversing through the given directions ; Traversing through the given directions ; If its north or south the point will move left or right ; If its west or east the point will move upwards or downwards ; Returning the final position ; Driver Code | def finalCoordinates ( SX , SY , D ) : NEW_LINE INDENT for i in range ( len ( D ) ) : NEW_LINE INDENT if ( D [ i ] == ' N ' ) : NEW_LINE INDENT SY += 1 NEW_LINE DEDENT elif ( D [ i ] == ' S ' ) : NEW_LINE INDENT SY -= 1 NEW_LINE DEDENT elif ( D [ i ] == ' E ' ) : NEW_LINE INDENT SX += 1 NEW_LINE DEDENT else : NEW_LINE INDENT SX -= 1 NEW_LINE DEDENT DEDENT ans = ' ( ' + str ( SX ) + ' , ' + str ( SY ) + ' ) ' NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT SX , SY = 2 , 2 NEW_LINE D = " NSSE " NEW_LINE finalCoordinates ( SX , SY , D ) NEW_LINE DEDENT |
Frequency of smallest character in first sentence less than that of second sentence | Python3 program for the above approach ; Function to count the frequency of minimum character ; Sort the string s ; Return the count with smallest character ; Function to count number of frequency of smallest character of string arr1 [ ] is less than the string in arr2 [ ] ; To store the frequency of smallest character in each string of arr2 ; Traverse the arr2 [ ] ; Count the frequency of smallest character in string s ; Append the frequency to freq [ ] ; Sort the frequency array ; Traverse the array arr1 [ ] ; Count the frequency of smallest character in string s ; find the element greater than f ; Find the count such that arr1 [ i ] < arr2 [ j ] ; Print the count ; Driver Code ; Function Call | from bisect import bisect_right as upper_bound NEW_LINE def countMinFreq ( s ) : NEW_LINE INDENT s = sorted ( s ) NEW_LINE x = 0 NEW_LINE for i in s : NEW_LINE INDENT if i == s [ 0 ] : NEW_LINE INDENT x += 1 NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def countLessThan ( arr1 , arr2 ) : NEW_LINE INDENT freq = [ ] NEW_LINE for s in arr2 : NEW_LINE INDENT f = countMinFreq ( s ) NEW_LINE freq . append ( f ) NEW_LINE DEDENT feq = sorted ( freq ) NEW_LINE for s in arr1 : NEW_LINE INDENT f = countMinFreq ( s ) ; NEW_LINE it = upper_bound ( freq , f ) NEW_LINE cnt = len ( freq ) - it NEW_LINE print ( cnt , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ " yyy " , " zz " ] NEW_LINE arr2 = [ " x " , " xx " , " xxx " , " xxxx " ] NEW_LINE countLessThan ( arr1 , arr2 ) ; NEW_LINE DEDENT |
Lexicographically all Shortest Palindromic Substrings from a given string | Function to find all lexicographically shortest palindromic substring ; Array to keep track of alphabetic characters ; Iterate to print all lexicographically shortest substring ; Driver code | def shortestPalindrome ( s ) : NEW_LINE INDENT abcd = [ 0 ] * 26 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT abcd [ ord ( s [ i ] ) - 97 ] = 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if abcd [ i ] == 1 : NEW_LINE INDENT print ( chr ( i + 97 ) , end = ' β ' ) NEW_LINE DEDENT DEDENT DEDENT s = " geeksforgeeks " NEW_LINE shortestPalindrome ( s ) NEW_LINE |
Remove duplicates from string keeping the order according to last occurrences | Python3 program to remove duplicate character from character array and print sorted order ; Used as index in the modified string ; Traverse through all characters ; Check if str [ i ] is present before it ; If not present , then add it to result . ; Driver code | def removeDuplicates ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while j < n : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT res = res + str [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE print ( removeDuplicates ( str ) ) NEW_LINE DEDENT |
Remove duplicates from string keeping the order according to last occurrences | Python3 program to remove duplicate character from character array and prin sorted order ; Used as index in the modified string ; Create an empty hash table ; Traverse through all characters from right to left ; If current character is not in ; Reverse the result string ; Driver code | def removeDuplicates ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE s = set ( ) NEW_LINE res = " " NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] not in s ) : NEW_LINE INDENT res = res + str [ i ] NEW_LINE s . add ( str [ i ] ) NEW_LINE DEDENT DEDENT res = res [ : : - 1 ] NEW_LINE return res NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE print ( removeDuplicates ( str ) ) NEW_LINE |
Count of numbers in a range that does not contain the digit M and which is divisible by M . | Function to count all the numbers which does not contain the digit ' M ' and is divisible by M ; Storing all the distinct digits of a number ; Checking if the two conditions are satisfied or not ; Driver code ; Lower Range ; Upper Range ; The digit | def contain ( L , U , M ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( L , U + 1 ) : NEW_LINE INDENT num = set ( str ( j ) ) NEW_LINE if ( j % M == 0 and str ( M ) not in num ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE L = 106 NEW_LINE U = 200 NEW_LINE M = 7 NEW_LINE INDENT contain ( L , U , M ) NEW_LINE DEDENT |
Longest string which is prefix string of at least two strings | Python3 program to find longest string which is prefix string of at least two strings ; Function to find max length of the prefix ; Base case ; Iterating over all the alphabets ; Checking if char exists in current string or not ; If atleast 2 string have that character ; Recursive call to i + 1 ; Driver code ; Initialising strings ; Push strings into vectors . | max1 = 0 NEW_LINE def MaxLength ( v , i , m ) : NEW_LINE INDENT global max1 NEW_LINE if ( i >= m ) : NEW_LINE INDENT return m - 1 NEW_LINE DEDENT for k in range ( 26 ) : NEW_LINE INDENT c = chr ( ord ( ' a ' ) + k ) NEW_LINE v1 = [ ] NEW_LINE for j in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ j ] [ i ] == c ) : NEW_LINE INDENT v1 . append ( v [ j ] ) NEW_LINE DEDENT DEDENT if ( len ( v1 ) >= 2 ) : NEW_LINE INDENT max1 = max ( max1 , MaxLength ( v1 , i + 1 , m ) ) NEW_LINE DEDENT else : NEW_LINE INDENT max1 = max ( max1 , i - 1 ) NEW_LINE DEDENT DEDENT return max1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " abcde " NEW_LINE s2 = " abcsd " NEW_LINE s3 = " bcsdf " NEW_LINE s4 = " abcda " NEW_LINE s5 = " abced " NEW_LINE v = [ ] NEW_LINE v . append ( s1 ) NEW_LINE v . append ( s2 ) NEW_LINE v . append ( s3 ) NEW_LINE v . append ( s4 ) NEW_LINE v . append ( s5 ) NEW_LINE m = len ( v [ 0 ] ) NEW_LINE print ( MaxLength ( v , 0 , m ) + 1 ) NEW_LINE DEDENT |
Periodic Binary String With Minimum Period and a Given Binary String as Subsequence . | Function to find the periodic string with minimum period ; Print the S if it consists of similar elements ; Find the required periodic with period 2 ; Driver Code | def findPeriodicString ( S ) : NEW_LINE INDENT l = 2 * len ( S ) NEW_LINE count = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == len ( S ) or count == 0 ) : NEW_LINE INDENT print ( S ) NEW_LINE DEDENT else : NEW_LINE INDENT arr = [ '0' ] * l NEW_LINE for i in range ( 0 , l , 2 ) : NEW_LINE INDENT arr [ i ] = '1' NEW_LINE arr [ i + 1 ] = '0' NEW_LINE DEDENT for i in range ( l ) : NEW_LINE INDENT print ( arr [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1111001" NEW_LINE findPeriodicString ( S ) NEW_LINE DEDENT |
Print Strings In Reverse Dictionary Order Using Trie | Python3 program to print array of string in reverse dictionary order using trie ; Trie node ; endOfWord is true if the node represents end of a word ; Function will return the new node initialized NONE ; Initialize null to the all child ; Function will insert the string in a trie recursively ; Create a new node ; Recursive call for insertion of string ; Make the endOfWord true which represents the end of string ; Function call to insert a string ; Function call with necessary arguments ; Function to check whether the node is leaf or not ; Function to display the content of trie ; If node is leaf node , it indicates end of string , so a null character is added and string is displayed ; Assign a null character in temporary string ; check if NON NONE child is found add parent key to str and call the display function recursively for child node ; Function call for displaying content ; Driver code ; After inserting strings , trie will look like root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r | CHILDREN = 26 NEW_LINE MAX = 100 NEW_LINE class trie : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . child = [ 0 for i in range ( CHILDREN ) ] NEW_LINE self . endOfWord = False ; NEW_LINE DEDENT DEDENT def createNode ( ) : NEW_LINE INDENT temp = trie ( ) ; NEW_LINE temp . endOfWord = False ; NEW_LINE for i in range ( CHILDREN ) : NEW_LINE INDENT temp . child [ i ] = None ; NEW_LINE DEDENT return temp ; NEW_LINE DEDENT def insertRecursively ( itr , str , i ) : NEW_LINE INDENT if ( i < len ( str ) ) : NEW_LINE INDENT index = ord ( str [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( itr . child [ index ] == None ) : NEW_LINE INDENT itr . child [ index ] = createNode ( ) ; NEW_LINE DEDENT insertRecursively ( itr . child [ index ] , str , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT itr . endOfWord = True ; NEW_LINE DEDENT DEDENT def insert ( itr , str ) : NEW_LINE INDENT insertRecursively ( itr , str , 0 ) ; NEW_LINE DEDENT def isLeafNode ( root ) : NEW_LINE INDENT return root . endOfWord != False ; NEW_LINE DEDENT def displayContent ( root , str , level ) : NEW_LINE INDENT if ( isLeafNode ( root ) ) : NEW_LINE INDENT print ( " " . join ( str [ : level ] ) ) NEW_LINE DEDENT for i in range ( CHILDREN - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( root . child [ i ] ) : NEW_LINE INDENT str [ level ] = chr ( i + ord ( ' a ' ) ) ; NEW_LINE displayContent ( root . child [ i ] , str , level + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT def display ( itr ) : NEW_LINE INDENT level = 0 ; NEW_LINE str = [ ' ' for i in range ( MAX ) ] ; NEW_LINE displayContent ( itr , str , level ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = createNode ( ) ; NEW_LINE insert ( root , " their " ) ; NEW_LINE insert ( root , " there " ) ; NEW_LINE insert ( root , " answer " ) ; NEW_LINE insert ( root , " any " ) ; NEW_LINE display ( root ) ; NEW_LINE DEDENT |
Queries to find total number of duplicate character in range L to R in the string S | Python implementation to Find the total number of duplicate character in a range L to R for Q number of queries in a string S ; Vector of vector to store position of all characters as they appear in string ; Function to store position of each character ; Inserting position of each character as they appear ; Function to calculate duplicate characters for Q queries ; Variable to count duplicates ; Iterate over all 26 characters ; Finding the first element which is less than or equal to L ; Check if first pointer exists and is less than R ; Incrementing first pointer to check if the next duplicate element exists ; Check if the next element exists and is less than R ; Driver Code | import bisect NEW_LINE v = [ [ ] for _ in range ( 26 ) ] NEW_LINE def calculate ( s : str ) -> None : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT DEDENT def query ( L : int , R : int ) -> None : NEW_LINE INDENT duplicates = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT first = bisect . bisect_left ( v [ i ] , L - 1 ) NEW_LINE if ( first < len ( v [ i ] ) and v [ i ] [ first ] < R ) : NEW_LINE INDENT first += 1 NEW_LINE if ( first < len ( v [ i ] ) and v [ i ] [ first ] < R ) : NEW_LINE INDENT duplicates += 1 NEW_LINE DEDENT DEDENT DEDENT print ( duplicates ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE Q = 2 NEW_LINE l1 = 1 NEW_LINE r1 = 5 NEW_LINE l2 = 4 NEW_LINE r2 = 8 NEW_LINE calculate ( s ) NEW_LINE query ( l1 , r1 ) NEW_LINE query ( l2 , r2 ) NEW_LINE DEDENT |
Count the minimum number of groups formed in a string | Function to count the minimum number of groups formed in the given string s ; Initializing count as one since the string is not NULL ; Comparing adjacent characters ; Driver Code | def group_formed ( S ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( len ( S ) - 1 ) : NEW_LINE INDENT a = S [ i ] NEW_LINE b = S [ i + 1 ] NEW_LINE if ( a != b ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " TTWWW " NEW_LINE group_formed ( S ) NEW_LINE DEDENT |
Find the Substring with maximum product | Function to return the value of a character ; Function to find the maximum product sub ; To store subs ; Check if current product is maximum possible or not ; If product is 0 ; Return the sub with maximum product ; Driver code ; Function call | def value ( x ) : NEW_LINE INDENT return ( ord ( x ) - ord ( ' a ' ) ) NEW_LINE DEDENT def maximumProduct ( strr , n ) : NEW_LINE INDENT answer = " " NEW_LINE curr = " " NEW_LINE maxProduct = 0 NEW_LINE product = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT product *= value ( strr [ i ] ) NEW_LINE curr += strr [ i ] NEW_LINE if ( product >= maxProduct ) : NEW_LINE INDENT maxProduct = product NEW_LINE answer = curr NEW_LINE DEDENT if ( product == 0 ) : NEW_LINE INDENT product = 1 NEW_LINE curr = " " NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " sdtfakdhdahdzz " NEW_LINE n = len ( strr ) NEW_LINE print ( maximumProduct ( strr , n ) ) NEW_LINE DEDENT |
Sum of minimum and the maximum difference between two given Strings | Function to find the sum of the minimum and the maximum difference between two given strings ; Variables to store the minimum difference and the maximum difference ; Iterate through the length of the as both the given strings are of the same length ; For the maximum difference , we can replace " + " in both the strings with different char ; For the minimum difference , we can replace " + " in both the strings with the same char ; Driver code | def solve ( a , b ) : NEW_LINE INDENT l = len ( a ) NEW_LINE min = 0 NEW_LINE max = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( a [ i ] == ' + ' or b [ i ] == ' + ' or a [ i ] != b [ i ] ) : NEW_LINE INDENT max += 1 NEW_LINE DEDENT if ( a [ i ] != ' + ' and b [ i ] != ' + ' and a [ i ] != b [ i ] ) : NEW_LINE INDENT min += 1 NEW_LINE DEDENT DEDENT print ( min + max ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " a + c " NEW_LINE s2 = " + + b " NEW_LINE solve ( s1 , s2 ) NEW_LINE DEDENT |
Minimum letters to be removed to make all occurrences of a given letter continuous | Function to find the minimum number of deletions required to make the occurrences of the given character K continuous ; Find the first occurrence of the given letter ; Iterate from the first occurrence till the end of the sequence ; Find the index from where the occurrence of the character is not continuous ; Update the answer with the number of elements between non - consecutive occurrences of the given letter ; Update the count for all letters which are not equal to the given letter ; Return the count ; Driver code ; Calling the function ; Calling the function | def noOfDeletions ( string , k ) : NEW_LINE INDENT ans = 0 ; cnt = 0 ; pos = 0 ; NEW_LINE while ( pos < len ( string ) and string [ pos ] != k ) : NEW_LINE INDENT pos += 1 ; NEW_LINE DEDENT i = pos ; NEW_LINE while ( i < len ( string ) ) : NEW_LINE INDENT while ( i < len ( string ) and string [ i ] == k ) : NEW_LINE INDENT i = i + 1 ; NEW_LINE DEDENT ans = ans + cnt ; NEW_LINE cnt = 0 ; NEW_LINE while ( i < len ( string ) and string [ i ] != k ) : NEW_LINE INDENT i = i + 1 ; NEW_LINE cnt = cnt + 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " ababababa " ; NEW_LINE k1 = ' a ' ; NEW_LINE print ( noOfDeletions ( str1 , k1 ) ) ; NEW_LINE str2 = " kprkkoinkopt " ; NEW_LINE k2 = ' k ' ; NEW_LINE print ( noOfDeletions ( str2 , k2 ) ) ; NEW_LINE DEDENT |
Check whether an array of strings can correspond to a particular number X | Function to find the maximum base possible for the number N ; Function to find the decimal equivalent of the number ; Condition to check if the number is convertible to another base ; Function to check that the array can correspond to a number X ; counter to count the numbers those are convertible to X ; Loop to iterate over the array ; Convert the current string to every base for checking whether it will correspond to X from any base ; Condition to check if every number of the array can be converted to X ; Driver Code ; The set of strings in base from [ 2 , 36 ] | def val ( c ) : NEW_LINE INDENT if ( c >= '0' and c <= '9' ) : NEW_LINE INDENT return int ( c ) NEW_LINE DEDENT else : NEW_LINE INDENT return c - ' A ' + 10 NEW_LINE DEDENT DEDENT def toDeci ( strr , base ) : NEW_LINE INDENT lenn = len ( strr ) NEW_LINE power = 1 NEW_LINE num = 0 NEW_LINE for i in range ( lenn - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( val ( strr [ i ] ) >= base ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT num += val ( strr [ i ] ) * power NEW_LINE power = power * base NEW_LINE DEDENT return num NEW_LINE DEDENT def checkCorrespond ( strr , x ) : NEW_LINE INDENT counter = 0 NEW_LINE n = len ( strr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 , 37 ) : NEW_LINE INDENT if ( toDeci ( strr [ i ] , j ) == x ) : NEW_LINE INDENT counter += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( counter == n ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT x = 16 NEW_LINE strr = [ "10000" , "20" , "16" ] NEW_LINE checkCorrespond ( strr , x ) NEW_LINE |
Count of same length Strings that exists lexicographically in between two given Strings | Function to find the count of strings less than given string lexicographically ; Find length of string s ; Looping over the string characters and finding strings less than that character ; Function to find the count of same length Strings that exists lexicographically in between two given Strings ; Count string less than S1 ; Count string less than S2 ; Total strings between S1 and S2 would be difference between the counts - 1 ; If S1 is lexicographically greater than S2 then return 0 , otherwise return the value of totalString ; Driver code | def LexicoLesserStrings ( s ) : NEW_LINE INDENT count = 0 NEW_LINE length = len ( s ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT count += ( ( ord ( s [ i ] ) - ord ( ' a ' ) ) * pow ( 26 , length - i - 1 ) ) NEW_LINE DEDENT return count NEW_LINE DEDENT def countString ( S1 , S2 ) : NEW_LINE INDENT countS1 = LexicoLesserStrings ( S1 ) NEW_LINE countS2 = LexicoLesserStrings ( S2 ) NEW_LINE totalString = countS2 - countS1 - 1 ; NEW_LINE return ( 0 if totalString < 0 else totalString ) NEW_LINE DEDENT S1 = " cda " ; NEW_LINE S2 = " cef " ; NEW_LINE print ( countString ( S1 , S2 ) ) NEW_LINE |
Longest Subsequence of a String containing only vowels | Function to check whether a character is vowel or not ; Returns true if x is vowel ; Function to find the longest subsequence which contain all vowels ; Length of the string ; Iterating through the string ; Checking if the character is a vowel or not ; If it is a vowel , then add it to the final string ; 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 longestVowelSubsequence ( str ) : NEW_LINE INDENT answer = " " NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isVowel ( str [ i ] ) ) : NEW_LINE INDENT answer += str [ i ] NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE print ( longestVowelSubsequence ( str ) ) NEW_LINE |
Maximum repeated frequency of characters in a given string | Function to find the maximum repeated frequency of the characters in the given string ; Hash - Array to store the frequency of characters ; Loop to find the frequency of the characters ; Hash map to store the occurrence of frequencies of characters ; Loop to find the maximum Repeated frequency from hash - map ; Driver Code ; Function Call | def findMaxFrequency ( s ) : NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT arr [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT hash = { } NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT if arr [ i ] not in hash : NEW_LINE INDENT hash [ arr [ i ] ] = 0 NEW_LINE DEDENT hash [ arr [ i ] ] += 1 NEW_LINE DEDENT DEDENT max_count = 0 NEW_LINE res = - 1 NEW_LINE for i in hash : NEW_LINE INDENT if ( max_count < hash [ i ] ) : NEW_LINE INDENT res = i NEW_LINE max_count = hash [ i ] NEW_LINE DEDENT DEDENT print ( " Frequency " , res , " is β repeated " , max_count , " times " ) NEW_LINE DEDENT s = " geeksgeeks " NEW_LINE findMaxFrequency ( s ) NEW_LINE |
Generate string with Hamming Distance as half of the hamming distance between strings A and B | Function to find the required string ; Find the hamming distance between A and B ; If distance is odd , then resultant string is not possible ; Make the resultant string ; To store the final string ; Pick k characters from each string ; Pick K characters from string B ; Pick K characters from string A ; Append the res characters from string to the resultant string ; Print the resultant string ; Driver 's Code ; Function to find the resultant string | def findString ( A , B ) : NEW_LINE INDENT dist = 0 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT dist += 1 ; NEW_LINE DEDENT DEDENT if ( dist & 1 ) : NEW_LINE INDENT print ( " Not β Possible " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res = " " ; NEW_LINE K = dist // 2 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] and K > 0 ) : NEW_LINE INDENT res += B [ i ] ; NEW_LINE K -= 1 ; NEW_LINE DEDENT elif ( A [ i ] != B [ i ] ) : NEW_LINE INDENT res += A [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT res += A [ i ] ; NEW_LINE DEDENT DEDENT print ( res ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = "1001010" ; NEW_LINE B = "0101010" ; NEW_LINE findString ( A , B ) ; NEW_LINE DEDENT |
Longest suffix such that occurrence of each character is less than N after deleting atmost K characters | Function to find the maximum length suffix in the string ; Length of the string ; Map to store the number of occurrence of character ; Loop to iterate string from the last character ; Condition to check if the occurrence of each character is less than given number ; Condition when character cannot be deleted ; Longest suffix ; Driver Code ; Function call | def maximumSuffix ( s , n , k ) : NEW_LINE INDENT i = len ( s ) - 1 NEW_LINE arr = [ 0 for i in range ( 26 ) ] NEW_LINE suffix = " " NEW_LINE while ( i > - 1 ) : NEW_LINE INDENT index = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( arr [ index ] < n ) : NEW_LINE INDENT arr [ index ] += 1 NEW_LINE suffix += s [ i ] NEW_LINE i -= 1 NEW_LINE continue NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT k -= 1 NEW_LINE i -= 1 NEW_LINE DEDENT suffix = suffix [ : : - 1 ] NEW_LINE print ( suffix ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " iahagafedcba " NEW_LINE n = 1 NEW_LINE k = 2 NEW_LINE maximumSuffix ( str , n , k ) NEW_LINE DEDENT |
XOR of two Binary Strings | Function to find the XOR of the two Binary Strings ; Loop to iterate over the Binary Strings ; If the Character matches ; Driver Code | def xor ( a , b , n ) : NEW_LINE INDENT ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == b [ i ] ) : NEW_LINE INDENT ans += "0" NEW_LINE DEDENT else : NEW_LINE INDENT ans += "1" NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = "1010" NEW_LINE b = "1101" NEW_LINE n = len ( a ) NEW_LINE c = xor ( a , b , n ) NEW_LINE print ( c ) NEW_LINE DEDENT |
Find Kth largest string from the permutations of the string with two characters | Function to print the kth largest string ; loop to iterate through series ; total takes the position of second y ; i takes the position of first y ; calculating first y position ; calculating second y position from first y ; print all x before first y ; print first y ; print all x between first y and second y ; print second y ; print x which occur after second y ; Driver code | def kthString ( n , k ) : NEW_LINE INDENT total = 0 NEW_LINE i = 1 NEW_LINE while ( total < k ) : NEW_LINE INDENT total = total + n - i NEW_LINE i += 1 NEW_LINE DEDENT first_y_position = i - 1 NEW_LINE second_y_position = k - ( total - n + first_y_position ) NEW_LINE for j in range ( 1 , first_y_position , 1 ) : NEW_LINE INDENT print ( " x " , end = " " ) NEW_LINE DEDENT print ( " y " , end = " " ) NEW_LINE j = first_y_position + 1 NEW_LINE while ( second_y_position > 1 ) : NEW_LINE INDENT print ( " x " , end = " " ) NEW_LINE second_y_position -= 1 NEW_LINE j += 1 NEW_LINE DEDENT print ( " y " , end = " " ) NEW_LINE while ( j < n ) : NEW_LINE INDENT print ( " x " ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE k = 7 NEW_LINE kthString ( n , k ) NEW_LINE DEDENT |
Largest and Smallest N | Function to return the largest N - digit number in Octal Number System ; Append '7' N times ; Function to return the smallest N - digit number in Octal Number System ; Append '0' ( N - 1 ) times to 1 ; Function to print the largest and smallest N - digit Octal number ; Driver code ; Function Call | def findLargest ( N ) : NEW_LINE INDENT largest = strings ( N , '7' ) ; NEW_LINE return largest ; NEW_LINE DEDENT def findSmallest ( N ) : NEW_LINE INDENT smallest = "1" + strings ( ( N - 1 ) , '0' ) ; NEW_LINE return smallest ; NEW_LINE DEDENT def strings ( N , c ) : NEW_LINE INDENT temp = " " ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp += c ; NEW_LINE DEDENT return temp ; NEW_LINE DEDENT def printLargestSmallest ( N ) : NEW_LINE INDENT print ( " Largest : β " , findLargest ( N ) ) ; NEW_LINE print ( " Smallest : β " , findSmallest ( N ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE printLargestSmallest ( N ) ; NEW_LINE DEDENT |
Count of substrings whose Decimal equivalent is greater than or equal to K | Function to count number of substring whose decimal equivalent is greater than or equal to K ; Left pointer of the substring ; Right pointer of the substring ; Loop to maintain the last occurrence of the 1 in the string ; Variable to count the substring ; Loop to maintain the every possible end index of the substring ; Loop to find the substring whose decimal equivalent is greater than or equal to K ; Condition to check no of bits is out of bound ; Driver Code | def countSubstr ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE l = n - 1 NEW_LINE r = n - 1 NEW_LINE arr = [ 0 ] * n NEW_LINE last_indexof1 = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT arr [ i ] = i NEW_LINE last_indexof1 = i NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = last_indexof1 NEW_LINE DEDENT DEDENT no_of_substr = 0 NEW_LINE for r in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT l = r NEW_LINE while ( l >= 0 and ( r - l + 1 ) <= 64 and int ( s [ l : r + 1 ] , 2 ) < k ) : NEW_LINE INDENT l -= 1 NEW_LINE DEDENT if ( r - l + 1 <= 64 ) : NEW_LINE INDENT no_of_substr += l + 1 NEW_LINE DEDENT else : NEW_LINE INDENT no_of_substr += arr [ l + 1 ] + 1 NEW_LINE DEDENT DEDENT return no_of_substr NEW_LINE DEDENT s = "11100" NEW_LINE k = 3 NEW_LINE print ( countSubstr ( s , k ) ) NEW_LINE |
Perfect Cube String | Python3 program to find if str1ing is a perfect cube or not . ; Finding ASCII values of each character and finding its sum ; Find the cube root of sum ; Check if sum is a perfect cube ; Driver code | from math import ceil NEW_LINE def isPerfectCubeString ( str1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT sum += ord ( str1 [ i ] ) NEW_LINE DEDENT cr = ceil ( ( sum ) ** ( 1 / 3 ) ) NEW_LINE return ( cr * cr * cr == sum ) NEW_LINE DEDENT str1 = " ll " NEW_LINE if ( isPerfectCubeString ( str1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Program to find the XOR of ASCII values of characters in a string | Function to find the XOR of ASCII value of characters in str1ing ; store value of first character ; Traverse str1ing to find the XOR ; Return the XOR ; Driver code | def XorAscii ( str1 , len1 ) : NEW_LINE INDENT ans = ord ( str1 [ 0 ] ) NEW_LINE for i in range ( 1 , len1 ) : NEW_LINE INDENT ans = ( ans ^ ( ord ( str1 [ i ] ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT str1 = " geeksforgeeks " NEW_LINE len1 = len ( str1 ) NEW_LINE print ( XorAscii ( str1 , len1 ) ) NEW_LINE str1 = " GfG " NEW_LINE len1 = len ( str1 ) NEW_LINE print ( XorAscii ( str1 , len1 ) ) NEW_LINE |
CamelCase Pattern Matching | Function that prints the camel case pattern matching ; Map to store the hashing of each words with every uppercase letter found ; Traverse the words array that contains all the string ; Initialise str as empty ; length of string words [ i ] ; For every uppercase letter found map that uppercase to original words ; Traverse the map for pattern matching ; If pattern matches then print the corresponding mapped words ; If word not found print " No β match β found " ; Driver 's Code ; Pattern to be found ; Function call to find the words that match to the given pattern | def CamelCase ( words , pattern ) : NEW_LINE INDENT map = dict . fromkeys ( words , None ) ; NEW_LINE for i in range ( len ( words ) ) : NEW_LINE INDENT string = " " ; NEW_LINE l = len ( words [ i ] ) ; NEW_LINE for j in range ( l ) : NEW_LINE INDENT if ( words [ i ] [ j ] >= ' A ' and words [ i ] [ j ] <= ' Z ' ) : NEW_LINE INDENT string += words [ i ] [ j ] ; NEW_LINE if string not in map : NEW_LINE INDENT map [ string ] = [ words [ i ] ] NEW_LINE DEDENT elif map [ string ] is None : NEW_LINE INDENT map [ string ] = [ words [ i ] ] NEW_LINE DEDENT else : NEW_LINE INDENT map [ string ] . append ( words [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT wordFound = False ; NEW_LINE for key , value in map . items ( ) : NEW_LINE INDENT if ( key == pattern ) : NEW_LINE INDENT wordFound = True ; NEW_LINE for itt in value : NEW_LINE INDENT print ( itt ) ; NEW_LINE DEDENT DEDENT DEDENT if ( not wordFound ) : NEW_LINE INDENT print ( " No β match β found " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT words = [ " Hi " , " Hello " , " HelloWorld " , " HiTech " , " HiGeek " , " HiTechWorld " , " HiTechCity " , " HiTechLab " ] ; NEW_LINE pattern = " HT " ; NEW_LINE CamelCase ( words , pattern ) ; NEW_LINE DEDENT |
Encryption and Decryption of String according to given technique | Python3 implementation for Custom Encryption and Decryption of String ; Function to encrypt the ; Matrix to generate the Encrypted String ; Fill the matrix row - wise ; Loop to generate encrypted ; Function to decrypt the ; Matrix to generate the Encrypted String ; Fill the matrix column - wise ; Loop to generate decrypted ; Driver Code ; Encryption of String ; Decryption of String | from math import ceil , floor , sqrt NEW_LINE def encryption ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE b = ceil ( sqrt ( l ) ) NEW_LINE a = floor ( sqrt ( l ) ) NEW_LINE encrypted = " " NEW_LINE if ( b * a < l ) : NEW_LINE INDENT if ( min ( b , a ) == b ) : NEW_LINE INDENT b = b + 1 NEW_LINE DEDENT else : NEW_LINE INDENT a = a + 1 NEW_LINE DEDENT DEDENT arr = [ [ ' β ' for i in range ( a ) ] for j in range ( b ) ] NEW_LINE k = 0 NEW_LINE for j in range ( a ) : NEW_LINE INDENT for i in range ( b ) : NEW_LINE INDENT if ( k < l ) : NEW_LINE INDENT arr [ j ] [ i ] = s [ k ] NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT for j in range ( b ) : NEW_LINE INDENT for i in range ( a ) : NEW_LINE INDENT encrypted = encrypted + arr [ i ] [ j ] NEW_LINE DEDENT DEDENT return encrypted NEW_LINE DEDENT def decryption ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE b = ceil ( sqrt ( l ) ) NEW_LINE a = floor ( sqrt ( l ) ) NEW_LINE decrypted = " " NEW_LINE arr = [ [ ' β ' for i in range ( a ) ] for j in range ( b ) ] NEW_LINE k = 0 NEW_LINE for j in range ( b ) : NEW_LINE INDENT for i in range ( a ) : NEW_LINE INDENT if ( k < l ) : NEW_LINE INDENT arr [ j ] [ i ] = s [ k ] NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT for j in range ( a ) : NEW_LINE INDENT for i in range ( b ) : NEW_LINE INDENT decrypted = decrypted + arr [ i ] [ j ] NEW_LINE DEDENT DEDENT return decrypted NEW_LINE DEDENT s = " Geeks β For β Geeks " NEW_LINE encrypted = " " NEW_LINE decrypted = " " NEW_LINE encrypted = encryption ( s ) NEW_LINE print ( encrypted ) NEW_LINE decrypted = decryption ( encrypted ) NEW_LINE print ( decrypted ) NEW_LINE |
Program to accept String starting with Capital letter | Function to check if first character is Capital ; Function to check ; Driver function | def checkIfStartsWithCapital ( string ) : NEW_LINE INDENT if ( string [ 0 ] >= ' A ' and string [ 0 ] <= ' Z ' ) : 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 ( checkIfStartsWithCapital ( string ) ) : NEW_LINE INDENT print ( " Accepted " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Accepted " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GeeksforGeeks " ; NEW_LINE check ( string ) ; NEW_LINE string = " geeksforgeeks " ; NEW_LINE check ( string ) ; NEW_LINE DEDENT |
Program to accept a Strings which contains all the Vowels | Function to to check that a string contains all vowels ; Hash Array of size 5 such that the index 0 , 1 , 2 , 3 and 4 represent the vowels a , e , i , o and u ; Loop the string to mark the vowels which are present ; Loop to check if there is any vowel which is not present in the string ; Function to to check that a string contains all vowels ; Driver Code | def checkIfAllVowels ( string ) : NEW_LINE INDENT hash = [ 0 ] * 5 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ' A ' or string [ i ] == ' a ' ) : NEW_LINE INDENT hash [ 0 ] = 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' E ' or string [ i ] == ' e ' ) : NEW_LINE INDENT hash [ 1 ] = 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' I ' or string [ i ] == ' i ' ) : NEW_LINE INDENT hash [ 2 ] = 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' O ' or string [ i ] == ' o ' ) : NEW_LINE INDENT hash [ 3 ] = 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' U ' or string [ i ] == ' u ' ) : NEW_LINE INDENT hash [ 4 ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( 5 ) : NEW_LINE INDENT if ( hash [ i ] == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT return 0 ; NEW_LINE DEDENT def checkIfAllVowelsArePresent ( string ) : NEW_LINE INDENT if ( checkIfAllVowels ( 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 = " aeioubc " ; NEW_LINE checkIfAllVowelsArePresent ( string ) ; NEW_LINE DEDENT |
Smallest odd number with even sum of digits from the given number N | Function to find the smallest odd number whose sum of digits is even from the given string ; Converting the given string to a list of digits ; An empty array to store the digits ; For loop to iterate through each digit ; If the given digit is odd then the digit is appended to the array b ; Sorting the list of digits ; If the size of the list is greater than 1 then a 2 digit smallest odd number is returned Since the sum of two odd digits is always even ; Else , - 1 is returned ; Driver code | def smallest ( s ) : NEW_LINE INDENT a = list ( s ) NEW_LINE b = [ ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( int ( a [ i ] ) % 2 != 0 ) : NEW_LINE INDENT b . append ( a [ i ] ) NEW_LINE DEDENT DEDENT b = sorted ( b ) NEW_LINE if ( len ( b ) > 1 ) : NEW_LINE INDENT return int ( b [ 0 ] ) * 10 + int ( b [ 1 ] ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( smallest ( "15470" ) ) NEW_LINE DEDENT |
Number formed by deleting digits such that sum of the digits becomes even and the number odd | Function to convert a number into odd number such that digit - sum is odd ; Loop to find any first two odd number such that their sum is even and number is odd ; Print the result ; Driver Code | def converthenumber ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE res = " " ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' or s [ i ] == '3' or s [ i ] == '5' or s [ i ] == '7' or s [ i ] == '9' ) : NEW_LINE INDENT res += s [ i ] ; NEW_LINE DEDENT if ( len ( res ) == 2 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( len ( res ) == 2 ) : NEW_LINE INDENT print ( res ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 18720 ; NEW_LINE converthenumber ( n ) ; NEW_LINE DEDENT |
Longest palindromic String formed using concatenation of given strings in any order | Function to find the longest palindromic from given array of strings ; Loop to find the pair of strings which are reverse of each other ; Loop to find if any palindromic is still left in the array ; Update the answer with all strings of pair1 ; Update the answer with palindromic s1 ; Update the answer with all strings of pair2 ; Driver Code | def longestPalindrome ( a , n ) : NEW_LINE INDENT pair1 = [ 0 ] * n NEW_LINE pair2 = [ 0 ] * n NEW_LINE r = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = a [ i ] NEW_LINE s = s [ : : - 1 ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( a [ i ] != " " and a [ j ] != " " ) : NEW_LINE INDENT if ( s == a [ j ] ) : NEW_LINE INDENT pair1 [ r ] = a [ i ] NEW_LINE pair2 [ r ] = a [ j ] NEW_LINE r += 1 NEW_LINE a [ i ] = " " NEW_LINE a [ j ] = " " NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT s1 = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = a [ i ] NEW_LINE a [ i ] = a [ i ] [ : : - 1 ] NEW_LINE if ( a [ i ] != " " ) : NEW_LINE INDENT if ( a [ i ] == s ) : NEW_LINE INDENT s1 = a [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT ans = " " NEW_LINE for i in range ( r ) : NEW_LINE INDENT ans = ans + pair1 [ i ] NEW_LINE DEDENT if ( s1 != " " ) : NEW_LINE INDENT ans = ans + s1 NEW_LINE DEDENT for j in range ( r - 1 , - 1 , - 1 ) : NEW_LINE INDENT ans = ans + pair2 [ j ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT a1 = [ " aba " , " aba " ] NEW_LINE n1 = len ( a1 ) NEW_LINE longestPalindrome ( a1 , n1 ) NEW_LINE a2 = [ " abc " , " dba " , " kop " , " abd " , " cba " ] NEW_LINE n2 = len ( a2 ) NEW_LINE longestPalindrome ( a2 , n2 ) NEW_LINE |
Program to print the given digit in words | Function to return the word of the corresponding digit ; For digit 0 ; For digit 1 ; For digit 2 ; For digit 3 ; For digit 4 ; For digit 5 ; For digit 6 ; For digit 7 ; For digit 8 ; For digit 9 ; Function to iterate through every digit in the given number ; Finding each digit of the number ; Print the digit in words ; Driver code | def printValue ( digit ) : NEW_LINE INDENT if digit == '0' : NEW_LINE INDENT print ( " Zero β " , end = " β " ) NEW_LINE DEDENT elif digit == '1' : NEW_LINE INDENT print ( " One β " , end = " β " ) NEW_LINE DEDENT elif digit == '2' : NEW_LINE INDENT print ( " Two β " , end = " β " ) NEW_LINE DEDENT elif digit == '3' : NEW_LINE INDENT print ( " Three " , end = " β " ) NEW_LINE DEDENT elif digit == '4' : NEW_LINE INDENT print ( " Four β " , end = " β " ) NEW_LINE DEDENT elif digit == '5' : NEW_LINE INDENT print ( " Five β " , end = " β " ) NEW_LINE DEDENT elif digit == '6' : NEW_LINE INDENT print ( " Six β " , end = " β " ) NEW_LINE DEDENT elif digit == '7' : NEW_LINE INDENT print ( " Seven " , end = " β " ) NEW_LINE DEDENT elif digit == '8' : NEW_LINE INDENT print ( " Eight " , end = " β " ) NEW_LINE DEDENT elif digit == '9' : NEW_LINE INDENT print ( " Nine β " , end = " β " ) NEW_LINE DEDENT DEDENT def printWord ( N ) : NEW_LINE INDENT i = 0 NEW_LINE length = len ( N ) NEW_LINE while i < length : NEW_LINE INDENT printValue ( N [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT N = "123" NEW_LINE printWord ( N ) NEW_LINE |
Jaro and Jaro | Python3 implementation of above approach ; Function to calculate the Jaro Similarity of two s ; If the s are equal ; Length of two s ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first ; 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 ; Return the Jaro Similarity ; Driver code ; Prjaro Similarity of two s | from math import floor , ceil 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 max_dist = floor ( max ( len1 , len2 ) / 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 DEDENT DEDENT t = t // 2 NEW_LINE return ( match / len1 + match / len2 + ( match - t + 1 ) / match ) / 3.0 NEW_LINE DEDENT s1 = " CRATE " NEW_LINE s2 = " TRACE " NEW_LINE print ( round ( jaro_distance ( s1 , s2 ) , 6 ) ) NEW_LINE |
Find the resultant String after replacing X with Y and removing Z | Function to replace and remove ; Two pointer start and end points to beginning and end position in the string ; If start is having Z find X pos in end and replace Z with another character ; Find location for having different character instead of Z ; If found swap character at start and end ; Else increment start Also checkin for X at start position ; Driver code | def replaceRemove ( s , X , Y , Z ) : NEW_LINE INDENT s = list ( s ) ; NEW_LINE start = 0 ; NEW_LINE end = len ( s ) - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT if ( s [ start ] == Z ) : NEW_LINE INDENT while ( end >= 0 and s [ end ] == Z ) : NEW_LINE INDENT end -= 1 ; NEW_LINE DEDENT if ( end > start ) : NEW_LINE INDENT s [ start ] , s [ end ] = s [ end ] , s [ start ] NEW_LINE if ( s [ start ] == X ) : NEW_LINE INDENT s [ start ] = Y ; NEW_LINE DEDENT start += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s [ start ] == X ) : NEW_LINE INDENT s [ start ] = Y ; NEW_LINE DEDENT start += 1 ; NEW_LINE DEDENT DEDENT while ( len ( s ) > 0 and s [ len ( s ) - 1 ] == Z ) : NEW_LINE INDENT s . pop ( ) ; NEW_LINE DEDENT return " " . join ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " batman " ; NEW_LINE X = ' a ' ; Y = ' d ' ; Z = ' b ' ; NEW_LINE string = replaceRemove ( string , X , Y , Z ) ; NEW_LINE if ( len ( string ) == 0 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( string ) ; NEW_LINE DEDENT DEDENT |
Check if all bits can be made same by flipping two consecutive bits | Function to check if Binary string can be made equal ; Counting occurence of zero and one in binary string ; From above observation ; Driver code | def canMake ( s ) : NEW_LINE INDENT o = 0 ; z = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) == 1 ) : NEW_LINE INDENT o += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT z += 1 ; NEW_LINE DEDENT DEDENT if ( o % 2 == 1 and z % 2 == 1 ) : NEW_LINE INDENT return " NO " ; NEW_LINE DEDENT else : NEW_LINE INDENT return " YES " ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "01011" ; NEW_LINE print ( canMake ( s ) ) ; NEW_LINE DEDENT |
Count of non | Python3 implementation of the above approach ; Function to find the count of the number of strings ; Loop to iterate over the frequency of character of string ; Reduce the frequency of current element ; Recursive call ; Backtrack ; Function to count the number of non - empty sequences ; store the frequency of each character ; Maintain the frequency ; Driver Code ; Function Call | count = 0 NEW_LINE def countNumberOfStringsUtil ( freq , Count ) : NEW_LINE INDENT global count NEW_LINE count = Count NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT freq [ i ] -= 1 NEW_LINE count += 1 NEW_LINE countNumberOfStringsUtil ( freq , count ) ; NEW_LINE freq [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def countNumberOfStrings ( s ) : NEW_LINE INDENT global count NEW_LINE global freq NEW_LINE freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' A ' ) ] += 1 NEW_LINE DEDENT countNumberOfStringsUtil ( freq , count ) ; NEW_LINE return count NEW_LINE DEDENT s = " AAABBC " NEW_LINE print ( countNumberOfStrings ( s ) ) NEW_LINE |
Minimum swaps required to make a binary string divisible by 2 ^ k | Function to return the minimum swaps required ; To store the final answer ; To store the count of one and zero ; Loop from end of the string ; If s [ i ] = 1 ; If s [ i ] = 0 ; If c_zero = k ; If the result can 't be achieved ; Return the final answer ; Driver code | def findMinSwaps ( s , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE c_one = 0 ; c_zero = 0 ; NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT c_one += 1 ; NEW_LINE DEDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT c_zero += 1 ; NEW_LINE ans += c_one ; NEW_LINE DEDENT if ( c_zero == k ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( c_zero < k ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "100111" ; NEW_LINE k = 2 ; NEW_LINE print ( findMinSwaps ( s , k ) ) ; NEW_LINE DEDENT |
Remove vowels from a string stored in a Binary Tree | Structure Representing the Node in the Binary tree ; Function to perform a level order insertion of a Node in the Binary tree ; If the root is empty , make it point to the Node ; In case there are elements in the Binary tree , perform a level order traversal using a Queue ; If the left child does not exist , insert the Node as the left child ; In case the right child does not exist , insert the Node as the right child ; Function to print the level order traversal of the Binary tree ; Function to check if the character is a vowel or not . ; Function to remove the vowels in the Binary tree ; Declaring the root of the tree ; If the given character is not a vowel , add it to the Binary tree ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , _val ) : NEW_LINE INDENT self . data = _val NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def addinBT ( root , data ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT root = Node ( data ) NEW_LINE DEDENT else : NEW_LINE INDENT Q = [ ] NEW_LINE Q . append ( root ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT temp = Q [ - 1 ] NEW_LINE Q . pop ( ) NEW_LINE if ( temp . left == None ) : NEW_LINE INDENT temp . left = Node ( data ) NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT Q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right == None ) : NEW_LINE INDENT temp . right = Node ( data ) NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT Q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT return root NEW_LINE DEDENT def print_ ( root ) : NEW_LINE INDENT Q = [ ] NEW_LINE Q . append ( root ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT temp = Q [ - 1 ] NEW_LINE Q . pop ( ) NEW_LINE print ( temp . data , end = " β " ) NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT Q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT Q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT def checkvowel ( ch ) : NEW_LINE INDENT ch = ch . lower ( ) NEW_LINE if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def removevowels ( root ) : NEW_LINE INDENT Q = [ ] NEW_LINE Q . append ( root ) NEW_LINE root1 = None NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT temp = Q [ - 1 ] NEW_LINE Q . pop ( ) NEW_LINE if ( not checkvowel ( temp . data ) ) : NEW_LINE INDENT root1 = addinBT ( root1 , temp . data ) NEW_LINE DEDENT if ( temp . left != None ) : NEW_LINE INDENT Q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT Q . append ( temp . right ) NEW_LINE DEDENT DEDENT return root1 NEW_LINE DEDENT s = " geeks " NEW_LINE root = None NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT root = addinBT ( root , s [ i ] ) NEW_LINE DEDENT root = removevowels ( root ) NEW_LINE print_ ( root ) NEW_LINE |
Number of sub | Function to return the count of the required substrings ; To store the final answer ; Loop to find the answer ; Condition to update the answer ; Driver code | def countSubStr ( strr , lenn ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] == '0' ) : NEW_LINE INDENT ans += ( i + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT strr = "10010" NEW_LINE lenn = len ( strr ) NEW_LINE print ( countSubStr ( strr , lenn ) ) NEW_LINE |
Smallest non | Function to return the length of the smallest subdivisible by 2 ^ k ; To store the final answer ; Left pointer ; Right pointer ; Count of the number of zeros and ones in the current substring ; Loop for two pointers ; Condition satisfied ; Updated the answer ; Update the pointer and count ; Update the pointer and count ; Driver code | def findLength ( s , k ) : NEW_LINE INDENT ans = 10 ** 9 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE cnt_zero = 0 NEW_LINE cnt_one = 0 NEW_LINE while ( l < len ( s ) and r <= len ( s ) ) : NEW_LINE INDENT if ( cnt_zero >= k and cnt_one >= 1 ) : NEW_LINE INDENT ans = min ( ans , r - l ) NEW_LINE l += 1 NEW_LINE if ( s [ l - 1 ] == '0' ) : NEW_LINE INDENT cnt_zero -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt_one -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( r == len ( s ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( s [ r ] == '0' ) : NEW_LINE INDENT cnt_zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt_one += 1 NEW_LINE DEDENT r += 1 NEW_LINE DEDENT DEDENT if ( ans == 10 ** 9 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT s = "100" NEW_LINE k = 2 NEW_LINE print ( findLength ( s , k ) ) NEW_LINE |
Largest sub | Function to return the largest substring divisible by 2 ; While the last character of the string is '1' , pop it ; If the original string had no '0 ; Driver code | def largestSubStr ( s ) : NEW_LINE INDENT while ( len ( s ) and s [ len ( s ) - 1 ] == '1' ) : NEW_LINE INDENT s = s [ : len ( s ) - 1 ] ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return " - 1" ; NEW_LINE DEDENT else : NEW_LINE INDENT return s ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "11001" ; NEW_LINE print ( largestSubStr ( s ) ) ; NEW_LINE DEDENT |
Subsets and Splits