text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find whether X exists in Y after jumbling X | Python3 implementation of the approach ; Function that returns true if both the arrays have equal values ; Test the equality ; Function that returns true if any permutation of X exists as a sub in Y ; Base case ; To store cumulative frequency ; Finding the frequency of characters in X ; Finding the frequency of characters in Y upto the length of X ; Equality check ; Two pointer approach to generate the entire cumulative frequency ; Remove the first character of the previous window ; Add the last character of the current window ; Equality check ; Driver Code
MAX = 26 NEW_LINE def areEqual ( a , b ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def xExistsInY ( x , y ) : NEW_LINE INDENT if ( len ( x ) > len ( y ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT cnt_x = [ 0 ] * MAX NEW_LINE cnt = [ 0 ] * MAX NEW_LINE for i in range ( len ( x ) ) : NEW_LINE INDENT cnt_x [ ord ( x [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( len ( x ) ) : NEW_LINE INDENT cnt [ ord ( y [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT if ( areEqual ( cnt_x , cnt ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , len ( y ) - len ( x ) + 1 ) : NEW_LINE INDENT cnt [ ord ( y [ i - 1 ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE cnt [ ord ( y [ i + len ( x ) - 1 ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( areEqual ( cnt , cnt_x ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = " skege " NEW_LINE y = " geeksforgeeks " NEW_LINE if ( xExistsInY ( x , y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Reverse substrings between each pair of parenthesis | Function to return the modified string ; Push the index of the current opening bracket ; Reverse the substarting after the last encountered opening bracket till the current character ; To store the modified string ; Driver code
def reverseParentheses ( strr , lenn ) : NEW_LINE INDENT st = [ ] NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] == ' ( ' ) : NEW_LINE INDENT st . append ( i ) NEW_LINE DEDENT elif ( strr [ i ] == ' ) ' ) : NEW_LINE INDENT temp = strr [ st [ - 1 ] : i + 1 ] NEW_LINE strr = strr [ : st [ - 1 ] ] + temp [ : : - 1 ] + strr [ i + 1 : ] NEW_LINE del st [ - 1 ] NEW_LINE DEDENT DEDENT res = " " NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] != ' ) ' and strr [ i ] != ' ( ' ) : NEW_LINE INDENT res += ( strr [ i ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " ( skeeg ( for ) skeeg ) " NEW_LINE lenn = len ( strr ) NEW_LINE st = [ i for i in strr ] NEW_LINE print ( reverseParentheses ( strr , lenn ) ) NEW_LINE DEDENT
Count of times second string can be formed from the characters of first string | Python3 implementation of the approach ; Function to update the freq [ ] array to store the frequencies of all the characters of strr ; Update the frequency of the characters ; Function to return the maximum count of times patt can be formed using the characters of strr ; To store the frequencies of all the characters of strr ; To store the frequencies of all the characters of patt ; To store the result ; For every character ; If the current character doesn 't appear in patt ; Update the result ; Driver code
MAX = 26 NEW_LINE def updateFreq ( strr , freq ) : NEW_LINE INDENT lenn = len ( strr ) NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT freq [ ord ( strr [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT def maxCount ( strr , patt ) : NEW_LINE INDENT strrFreq = [ 0 for i in range ( MAX ) ] NEW_LINE updateFreq ( strr , strrFreq ) NEW_LINE pattFreq = [ 0 for i in range ( MAX ) ] NEW_LINE updateFreq ( patt , pattFreq ) NEW_LINE ans = 10 ** 9 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( pattFreq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans = min ( ans , strrFreq [ i ] // pattFreq [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT strr = " geeksforgeeks " NEW_LINE patt = " geeks " NEW_LINE print ( maxCount ( strr , patt ) ) NEW_LINE
Reduce the number to minimum multiple of 4 after removing the digits | Python3 implementation of the approach ; Function to return the minimum number that can be formed after removing the digits which is a multiple of 4 ; For every digit of the number ; Check if the current digit is divisible by 4 ; If any subsequence of two digits is divisible by 4 ; Driver code
import sys NEW_LINE TEN = 10 NEW_LINE def minNum ( str , len1 ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT if ( str [ i ] == '4' or str [ i ] == '8' ) : NEW_LINE INDENT res = min ( res , ord ( str [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT DEDENT for i in range ( len1 - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , len1 , 1 ) : NEW_LINE INDENT num = ( ord ( str [ i ] ) - ord ( '0' ) ) * TEN + ( ord ( str [ j ] ) - ord ( '0' ) ) NEW_LINE if ( num % 4 == 0 ) : NEW_LINE INDENT res = min ( res , num ) NEW_LINE DEDENT DEDENT DEDENT if ( res == sys . maxsize ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return res NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "17" NEW_LINE len1 = len ( str ) NEW_LINE print ( minNum ( str , len1 ) ) NEW_LINE DEDENT
Check if two strings can be made equal by swapping one character among each other | Function that returns true if the string can be made equal after one swap ; A and B are new a and b after we omit the same elements ; Take only the characters which are different in both the strings for every pair of indices ; If the current characters differ ; The strings were already equal ; If the lengths of the strings are two ; If swapping these characters can make the strings equal ; Driver code
def canBeEqual ( a , b , n ) : NEW_LINE INDENT A = [ ] NEW_LINE B = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] != b [ i ] : NEW_LINE INDENT A . append ( a [ i ] ) NEW_LINE B . append ( b [ i ] ) NEW_LINE DEDENT DEDENT if len ( A ) == len ( B ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if len ( A ) == len ( B ) == 2 : NEW_LINE INDENT if A [ 0 ] == A [ 1 ] and B [ 0 ] == B [ 1 ] : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT A = ' SEEKSFORGEEKS ' NEW_LINE B = ' GEEKSFORGEEKG ' NEW_LINE if ( canBeEqual ( A , B , len ( A ) ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find the Mid | Function to find the mid alphabets ; For every character pair ; Get the average of the characters ; Driver code
def findMidAlphabet ( s1 , s2 , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT mid = ( ord ( s1 [ i ] ) + ord ( s2 [ i ] ) ) // 2 NEW_LINE print ( chr ( mid ) , end = " " ) NEW_LINE DEDENT DEDENT s1 = " akzbqzgw " NEW_LINE s2 = " efhctcsz " NEW_LINE n = len ( s1 ) NEW_LINE findMidAlphabet ( s1 , s2 , n ) NEW_LINE
Queries to find the count of vowels in the substrings of the given string | Python 3 implementation of the approach ; Function that returns true if ch is a vowel ; pre [ i ] will store the count of vowels in the substring str [ 0. . . i ] ; Fill the pre [ ] array ; If current character is a vowel ; If its a consonant ; For every query ; Find the count of vowels for the current query ; Driver code
N = 2 NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) NEW_LINE DEDENT def performQueries ( str1 , len1 , queries , q ) : NEW_LINE INDENT pre = [ 0 for i in range ( len1 ) ] NEW_LINE if ( isVowel ( str1 [ 0 ] ) ) : NEW_LINE INDENT pre [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT pre [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 0 , len1 , 1 ) : NEW_LINE INDENT if ( isVowel ( str1 [ i ] ) ) : NEW_LINE INDENT pre [ i ] = 1 + pre [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT if ( queries [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT print ( pre [ queries [ i ] [ 1 ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( pre [ queries [ i ] [ 1 ] ] - pre [ queries [ i ] [ 0 ] - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE len1 = len ( str1 ) NEW_LINE queries = [ [ 1 , 3 ] , [ 2 , 4 ] , [ 1 , 9 ] ] NEW_LINE q = len ( queries ) NEW_LINE performQueries ( str1 , len1 , queries , q ) NEW_LINE DEDENT
Check whether the given decoded string is divisible by 6 | Function to return the sum of the digits of n ; Function that return true if the decoded string is divisible by 6 ; To store the sum of the digits ; For each character , get the sum of the digits ; If the sum of digits is not divisible by 3 ; Get the last digit of the number formed ; If the last digit is not divisible by 2 ; Driver code
def sumDigits ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 ; NEW_LINE sum += digit ; NEW_LINE n //= 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def isDivBySix ( string , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ( ord ( string [ i ] ) - ord ( ' a ' ) + 1 ) ; NEW_LINE DEDENT if ( sum % 3 != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT lastDigit = ( ord ( string [ n - 1 ] ) - ord ( ' a ' ) + 1 ) % 10 ; NEW_LINE if ( lastDigit % 2 != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ab " ; NEW_LINE n = len ( string ) ; NEW_LINE if ( isDivBySix ( string , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Check the divisibility of Hexadecimal numbers | Python3 implementation of the approach ; Function that returns true if s is divisible by m ; Map to map characters to real value ; To store the remainder at any stage ; Find the remainder ; Check the value of remainder ; Driver code
CHARS = "0123456789ABCDEF " ; NEW_LINE DIGITS = 16 ; NEW_LINE def isDivisible ( s , m ) : NEW_LINE INDENT mp = dict . fromkeys ( CHARS , 0 ) ; NEW_LINE for i in range ( DIGITS ) : NEW_LINE INDENT mp [ CHARS [ i ] ] = i ; NEW_LINE DEDENT r = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT r = ( r * 16 + mp [ s [ i ] ] ) % m ; NEW_LINE DEDENT if ( not r ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "10" ; NEW_LINE m = 3 ; NEW_LINE if ( isDivisible ( s , m ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Maximum number of splits of a binary number | Function to return the required count ; If the splitting is not possible ; To store the count of zeroes ; Counting the number of zeroes ; Return the final answer ; Driver code
def cntSplits ( s ) : NEW_LINE INDENT if ( s [ len ( s ) - 1 ] == '1' ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans += ( s [ i ] == '0' ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "10010" ; NEW_LINE print ( cntSplits ( s ) ) ; NEW_LINE DEDENT
Modify the string such that every character gets replaced with the next character in the keyboard | Python3 implementation of the approach ; Function to return the modified string ; Map to store the next character on the keyboard for every possible lowercase character ; Update the string ; Driver code
CHARS = " qwertyuiopasdfghjklzxcvbnm " ; NEW_LINE MAX = 26 ; NEW_LINE def getString ( string , n ) : NEW_LINE INDENT string = list ( string ) ; NEW_LINE uMap = { } ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT uMap [ CHARS [ i ] ] = CHARS [ ( i + 1 ) % MAX ] ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT string [ i ] = uMap [ string [ i ] ] ; NEW_LINE DEDENT return " " . join ( string ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeks " ; NEW_LINE n = len ( string ) ; NEW_LINE print ( getString ( string , n ) ) ; NEW_LINE DEDENT
Queries to find the count of characters preceding the given location | Python 3 implementation of the approach ; returns character at index pos - 1 ; Driver Code
def Count ( s , pos ) : NEW_LINE INDENT c = s [ pos - 1 ] NEW_LINE counter = 0 NEW_LINE for i in range ( pos - 1 ) : NEW_LINE INDENT if s [ i ] == c : NEW_LINE INDENT counter = counter + 1 NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abacsddaa " NEW_LINE n = len ( s ) NEW_LINE query = [ 9 , 3 , 2 ] NEW_LINE Q = len ( query ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT pos = query [ i ] NEW_LINE print ( Count ( s , pos ) ) NEW_LINE DEDENT DEDENT
Queries to find the count of characters preceding the given location | Python 3 implementation of the approach ; Driver Code
def Count ( temp ) : NEW_LINE INDENT query = [ 9 , 3 , 2 ] NEW_LINE Q = len ( query ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT pos = query [ i ] NEW_LINE print ( temp [ pos - 1 ] ) NEW_LINE DEDENT DEDENT def processing ( s ) : NEW_LINE INDENT temp = [ 0 ] * len ( s ) NEW_LINE d = dict ( ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] not in d : NEW_LINE INDENT d [ s [ i ] ] = i NEW_LINE DEDENT else : NEW_LINE INDENT temp [ i ] = temp [ d [ s [ i ] ] ] + 1 NEW_LINE d [ s [ i ] ] = i NEW_LINE DEDENT DEDENT return temp NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abacsddaa " NEW_LINE n = len ( s ) NEW_LINE temp = processing ( s ) NEW_LINE Count ( temp ) NEW_LINE DEDENT
Count of matchsticks required to represent the given number | stick [ i ] stores the count of sticks required to represent the digit i ; Function to return the count of matchsticks required to represent the given number ; For every digit of the given number ; Add the count of sticks required to represent the current digit ; Driver code
sticks = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] ; NEW_LINE def countSticks ( string , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt += ( sticks [ ord ( string [ i ] ) - ord ( '0' ) ] ) ; NEW_LINE DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "56" ; NEW_LINE n = len ( string ) ; NEW_LINE print ( countSticks ( string , n ) ) ; NEW_LINE DEDENT
Modulo of a large Binary String | Function to return the value of ( str % k ) ; pwrTwo [ i ] will store ( ( 2 ^ i ) % k ) ; To store the result ; If current bit is 1 ; Add the current power of 2 ; Driver code
def getMod ( _str , n , k ) : NEW_LINE INDENT pwrTwo = [ 0 ] * n NEW_LINE pwrTwo [ 0 ] = 1 % k NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pwrTwo [ i ] = pwrTwo [ i - 1 ] * ( 2 % k ) NEW_LINE pwrTwo [ i ] %= k NEW_LINE DEDENT res = 0 NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( _str [ j ] == '1' ) : NEW_LINE INDENT res += ( pwrTwo [ i ] ) NEW_LINE res %= k NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT _str = "1101" NEW_LINE n = len ( _str ) NEW_LINE k = 45 NEW_LINE print ( getMod ( _str , n , k ) ) NEW_LINE
Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1 's | Python3 implementation of the approach ; Function to return the count of all possible valid strings ; Initialise and fill 0 's in the dp array ; Base cases ; dp [ i ] [ j ] = number of possible strings such that '1' just appeared consecutively j times upto the ith index ; Taking previously calculated value ; Taking all possible cases that can appear at the Nth position ; Driver code
MOD = 1000000007 NEW_LINE def countStrings ( N ) : NEW_LINE INDENT dp = [ [ 0 ] * 3 for i in range ( N + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = 1 ; NEW_LINE dp [ 1 ] [ 1 ] = 1 ; NEW_LINE dp [ 1 ] [ 2 ] = 0 ; NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] + dp [ i - 1 ] [ 2 ] ) % MOD NEW_LINE dp [ i ] [ 1 ] = dp [ i - 1 ] [ 0 ] % MOD NEW_LINE dp [ i ] [ 2 ] = dp [ i - 1 ] [ 1 ] % MOD NEW_LINE DEDENT ans = ( dp [ N ] [ 0 ] + dp [ N ] [ 1 ] + dp [ N ] [ 2 ] ) % MOD NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( countStrings ( N ) ) NEW_LINE DEDENT
Find the maximum possible Binary Number from given string | Function to return maximum number that can be formed from the string ; To store the frequency of ' z ' and ' n ' in the given string ; Number of zeroes ; Number of ones ; To store the required number ; Add all the ones ; Add all the zeroes ; Driver code
def maxNumber ( string , n ) : NEW_LINE INDENT freq = [ 0 , 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( string [ i ] == ' z ' ) : NEW_LINE INDENT freq [ 0 ] += 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' n ' ) : NEW_LINE INDENT freq [ 1 ] += 1 ; NEW_LINE DEDENT DEDENT num = " " ; NEW_LINE for i in range ( freq [ 1 ] ) : NEW_LINE INDENT num += '1' ; NEW_LINE DEDENT for i in range ( freq [ 0 ] ) : NEW_LINE INDENT num += '0' ; NEW_LINE DEDENT return num ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " roenenzooe " ; NEW_LINE n = len ( string ) ; NEW_LINE print ( maxNumber ( string , n ) ) ; NEW_LINE DEDENT
Contiguous unique substrings with the given length L | Function to print the unique sub - string of length n ; set to store the strings ; if the size of the string is equal to 1 then insert ; inserting unique sub - string of length L ; Printing the set of strings ; Driver Code ; Function calling
def result ( s , n ) : NEW_LINE INDENT st = set ( ) ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans = " " ; NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT ans += s [ j ] ; NEW_LINE if ( len ( ans ) == n ) : NEW_LINE INDENT st . add ( ans ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT for it in st : NEW_LINE INDENT print ( it , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abca " ; NEW_LINE n = 3 ; NEW_LINE result ( s , n ) ; NEW_LINE DEDENT
Find the occurrence of the given binary pattern in the binary representation of the array elements | Function to return the binary representation of n ; Array to store binary representation ; Counter for binary array ; Storing remainder in binary array ; To store the binary representation as a string ; Function to return the frequency of pat in the given txt ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; If pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Function to find the occurrence of the given pattern in the binary representation of elements of arr [ ] ; For every element of the array ; Find its binary representation ; Print the occurrence of the given pattern in its binary representation ; Driver code
def decToBinary ( n ) : NEW_LINE INDENT binaryNum = [ 0 for i in range ( 32 ) ] NEW_LINE i = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT binaryNum [ i ] = n % 2 NEW_LINE n = n // 2 NEW_LINE i += 1 NEW_LINE DEDENT binary = " " NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT binary += str ( binaryNum [ j ] ) NEW_LINE DEDENT return binary NEW_LINE DEDENT def countFreq ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE res = 0 NEW_LINE for i in range ( N - M + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < M ) : NEW_LINE INDENT if ( txt [ i + j ] != pat [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == M ) : NEW_LINE INDENT res += 1 NEW_LINE j = 0 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def findOccurrence ( arr , n , pattern ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT binary = decToBinary ( arr [ i ] ) NEW_LINE print ( countFreq ( pattern , binary ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 5 , 106 , 7 , 8 ] NEW_LINE pattern = "10" NEW_LINE n = len ( arr ) NEW_LINE findOccurrence ( arr , n , pattern ) NEW_LINE
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Function that returns true if the sequence can be balanced by changing the position of at most one bracket ; Odd length string can never be balanced ; Add ' ( ' in the beginning and ' ) ' in the end of the string ; If its an opening bracket then append it to the temp string ; If its a closing bracket ; There was an opening bracket to match it with ; No opening bracket to match it with ; Sequence is balanced ; Driver code
def canBeBalanced ( s , n ) : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT k = " ( " k = k + s + " ) " NEW_LINE d = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( len ( k ) ) : NEW_LINE INDENT if k [ i ] == " ( " : NEW_LINE INDENT d . append ( " ( " ) NEW_LINE DEDENT else : NEW_LINE INDENT if len ( d ) != 0 : NEW_LINE INDENT d . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT if len ( d ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT S = " ) ( ( ) " NEW_LINE n = len ( S ) NEW_LINE if ( canBeBalanced ( S , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find the winner of the game | Function to find the winner of the game ; To store the strings for both the players ; If the index is even ; Append the current character to player A 's string ; If the index is odd ; Append the current character to player B 's string ; Sort both the strings to get the lexicographically smallest string possible ; Copmpare both the strings to find the winner of the game ; Driver code
def find_winner ( string , n ) : NEW_LINE INDENT string1 = " " ; string2 = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT string1 += string [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT string2 += string [ i ] ; NEW_LINE DEDENT DEDENT string1 = " " . join ( sorted ( string1 ) ) NEW_LINE string2 = " " . join ( sorted ( string2 ) ) NEW_LINE if ( string1 < string2 ) : NEW_LINE INDENT print ( " A " , end = " " ) ; NEW_LINE DEDENT elif ( string2 < string1 ) : NEW_LINE INDENT print ( " B " , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Tie " , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE n = len ( string ) ; NEW_LINE find_winner ( string , n ) ; NEW_LINE DEDENT
Count of characters in str1 such that after deleting anyone of them str1 becomes str2 | Function to return the count of required indices ; Solution doesn 't exist ; Find the length of the longest common prefix of strings ; Find the length of the longest common suffix of strings ; If solution does not exist ; Return the count of indices ; Driver code
def Find_Index ( str1 , str2 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE if ( n != m + 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if str1 [ i ] == str2 [ i ] : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT i = n - 1 NEW_LINE j = m - 1 NEW_LINE while i >= 0 and j >= 0 and str1 [ i ] == str2 [ j ] : NEW_LINE INDENT r += 1 NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT if l + r < m : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = max ( n - r , 1 ) NEW_LINE j = min ( l + 1 , n ) NEW_LINE return ( j - i + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " aaa " NEW_LINE str2 = " aa " NEW_LINE print ( Find_Index ( str1 , str2 ) ) NEW_LINE DEDENT
Expand the string according to the given conditions | Function to expand and print the given string ; Subtract '0' to convert char to int ; Characters within brackets ; Expanding ; Reset the variables ; Driver code
def expandString ( strin ) : NEW_LINE INDENT temp = " " NEW_LINE j = 0 NEW_LINE i = 0 NEW_LINE while ( i < len ( strin ) ) : NEW_LINE INDENT if ( strin [ i ] >= "0" ) : NEW_LINE INDENT num = ord ( strin [ i ] ) - ord ( "0" ) NEW_LINE if ( strin [ i + 1 ] == ' ( ' ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( strin [ j ] != ' ) ' ) : NEW_LINE INDENT if ( ( strin [ j ] >= ' a ' and strin [ j ] <= ' z ' ) or ( strin [ j ] >= ' A ' and strin [ j ] <= ' Z ' ) ) : NEW_LINE INDENT temp += strin [ j ] NEW_LINE DEDENT j += 1 NEW_LINE DEDENT for k in range ( 1 , num + 1 ) : NEW_LINE INDENT print ( temp , end = " " ) NEW_LINE DEDENT num = 0 NEW_LINE temp = " " NEW_LINE if ( j < len ( strin ) ) : NEW_LINE INDENT i = j NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT strin = "3 ( ab ) 4 ( cd ) " NEW_LINE expandString ( strin ) NEW_LINE
Largest substring of str2 which is a prefix of str1 | Python3 implementation of the approach ; Function to return the largest substring in str2 which is a prefix of str1 ; To store the index in str2 which matches the prefix in str1 ; While there are characters left in str1 ; If the prefix is not found in str2 ; Remove the last character ; Prefix found ; No substring found in str2 that matches the prefix of str1 ; Driver code
import operator NEW_LINE def findPrefix ( str1 , str2 ) : NEW_LINE INDENT pos = False ; NEW_LINE while ( len ( str1 ) != 0 ) : NEW_LINE INDENT if operator . contains ( str2 , str1 ) != True : NEW_LINE INDENT str1 = str1 [ 0 : len ( str1 ) - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT pos = operator . contains ( str2 , str1 ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( pos == False ) : NEW_LINE INDENT return " - 1" ; NEW_LINE DEDENT return str1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksfor " ; NEW_LINE str2 = " forgeeks " ; NEW_LINE print ( findPrefix ( str1 , str2 ) ) ; NEW_LINE DEDENT
Round the given number to nearest multiple of 10 | Set | Function to round the given number to the nearest multiple of 10 ; If string is empty ; If the last digit is less then or equal to 5 then it can be rounded to the nearest ( previous ) multiple of 10 by just replacing the last digit with 0 ; Set the last digit to 0 ; Print the updated number ; The number hast to be rounded to the next multiple of 10 ; To store the carry ; Replace the last digit with 0 ; Starting from the second last digit , add 1 to digits while there is carry ; While there are digits to consider and there is carry to add ; Get the current digit ; Add the carry ; If the digit exceeds 9 then the carry will be generated ; Else there will be no carry ; Update the current digit ; Get to the previous digit ; If the carry is still 1 then it must be inserted at the beginning of the string ; Prin the rest of the number ; Driver code
def roundToNearest ( str , n ) : NEW_LINE INDENT if ( str == " " ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ord ( str [ n - 1 ] ) - ord ( '0' ) <= 5 ) : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ n - 1 ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE print ( str [ 0 : n ] ) NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE str = list ( str ) NEW_LINE str [ n - 1 ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE i = n - 2 NEW_LINE carry = 1 NEW_LINE while ( i >= 0 and carry == 1 ) : NEW_LINE INDENT currentDigit = ord ( str [ i ] ) - ord ( '0' ) NEW_LINE currentDigit += carry NEW_LINE if ( currentDigit > 9 ) : NEW_LINE INDENT carry = 1 NEW_LINE currentDigit = 0 NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE DEDENT str [ i ] = chr ( currentDigit + '0' ) NEW_LINE i -= 1 NEW_LINE DEDENT if ( carry == 1 ) : NEW_LINE INDENT print ( carry ) NEW_LINE DEDENT print ( str [ 0 : n ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "99999999999999993" NEW_LINE n = len ( str ) NEW_LINE roundToNearest ( str , n ) NEW_LINE DEDENT
Repeat substrings of the given String required number of times | Function that returns true if the passed character is a digit ; Function to return the next index of a non - digit character in the string starting at the index i ( returns - 1 ifno such index is found ) ; If the character at index i is a digit then skip to the next character ; If no such index was found ; Function to append str the given number of times to the StringBuilder ; Function to return the string after performing the given operations ; To build the resultant string ; Index of the first non - digit character in the string ; While there are substrings that do not consist of digits ; Find the ending of the substring ; Starting index of the number ; If no digit appears after the current substring ; Find the index at which the current number ends ; Parse the number from the substring ; Repeat the current substring required number of times ; Find the next non - digit character index ; Return the resultant string ; Driver code
def isDigit ( ch ) : NEW_LINE INDENT if ch >= '0' and ch <= '9' : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def nextNonDigit ( string , i ) : NEW_LINE INDENT while i < len ( string ) and isDigit ( string [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if i >= len ( string ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return i NEW_LINE DEDENT def appendRepeated ( sb , string , times ) : NEW_LINE INDENT for i in range ( times ) : NEW_LINE INDENT sb . append ( string ) NEW_LINE DEDENT DEDENT def findString ( string , n ) : NEW_LINE INDENT sb = list ( ) NEW_LINE startStr = nextNonDigit ( string , 0 ) NEW_LINE while startStr != - 1 : NEW_LINE INDENT endStr = startStr NEW_LINE while ( endStr + 1 < n and not isDigit ( string [ endStr + 1 ] ) ) : NEW_LINE INDENT endStr += 1 NEW_LINE DEDENT startNum = endStr + 1 NEW_LINE if startNum == - 1 : NEW_LINE INDENT break NEW_LINE DEDENT endNum = startNum NEW_LINE while ( endNum + 1 < n and isDigit ( string [ endNum + 1 ] ) ) : NEW_LINE INDENT endNum += 1 NEW_LINE DEDENT num = int ( string [ startNum : endNum + 1 ] ) NEW_LINE appendRepeated ( sb , string [ startStr : endStr + 1 ] , num ) NEW_LINE startStr = nextNonDigit ( string , endStr + 1 ) NEW_LINE DEDENT sb = ' ' . join ( sb ) NEW_LINE return sb NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " g1ee1ks1for1g1e2ks1" NEW_LINE n = len ( string ) NEW_LINE print ( findString ( string , n ) ) NEW_LINE DEDENT
Check if the given string is vowel prime | Function that returns true if c is a vowel ; Function that returns true if all the vowels in the given string are only at prime indices ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries in it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; 0 and 1 are not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; For every character of the given String ; If current character is vowel and the index is not prime ; Driver code
def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isVowelPrime ( Str , n ) : NEW_LINE INDENT prime = [ True for i in range ( n ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , n ) : NEW_LINE INDENT if p * p > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , n , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( isVowel ( Str [ i ] ) and prime [ i ] == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT Str = " geeksforgeeks " ; NEW_LINE n = len ( Str ) NEW_LINE if ( isVowelPrime ( Str , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Swap all occurrences of two characters to get lexicographically smallest string | python3 implementation of the approach ; Function to return the lexicographically smallest after swapping all the occurrences of any two characters ; To store the first index of every character of str ; Store the first occurring index every character ; If current character is appearing for the first time in str ; Starting from the leftmost character ; For every character smaller than ord ( str [ i ] ) ; If there is a character in str which is smaller than ord ( str [ i ] ) and appears after it ; If the required character pair is found ; If swapping is possible ; Characters to be swapped ; For every character ; Replace every ch1 with ch2 and every ch2 with ch1 ; Driver code
MAX = 256 NEW_LINE def smallestStr ( str , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE chk = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT chk [ i ] = - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( chk [ ord ( str [ i ] ) ] == - 1 ) : NEW_LINE INDENT chk [ ord ( str [ i ] ) ] = i NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT flag = False NEW_LINE for j in range ( ord ( str [ i ] ) ) : NEW_LINE INDENT if ( chk [ j ] > chk [ ord ( str [ i ] ) ] ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i < n ) : NEW_LINE INDENT ch1 = ( str [ i ] ) NEW_LINE ch2 = chr ( j ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ch1 ) : NEW_LINE INDENT str [ i ] = ch2 NEW_LINE DEDENT elif ( str [ i ] == ch2 ) : NEW_LINE INDENT str [ i ] = ch1 NEW_LINE DEDENT DEDENT DEDENT return " " . join ( str ) NEW_LINE DEDENT st = " ccad " NEW_LINE str = [ i for i in st ] NEW_LINE n = len ( str ) NEW_LINE print ( smallestStr ( str , n ) ) NEW_LINE
Longest sub string of 0 's in a binary string which is repeated K times | Function to find the longest subof 0 's ; To store size of the string ; To store the required answer ; Find the longest subof 0 's ; Run a loop upto s [ i ] is zero ; Check the conditions ; Driver code ; Function call
def longest_substring ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if ( k > 1 ) : NEW_LINE INDENT s += s NEW_LINE n *= 2 NEW_LINE DEDENT ans = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT x = 0 NEW_LINE while ( i < n and s [ i ] == '0' ) : NEW_LINE INDENT x , i = x + 1 , i + 1 NEW_LINE DEDENT ans = max ( ans , x ) NEW_LINE i += 1 NEW_LINE DEDENT if ( k == 1 or ans != n ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT return ( ans // 2 ) * k NEW_LINE DEDENT DEDENT s = "010001000" NEW_LINE k = 4 NEW_LINE print ( longest_substring ( s , k ) ) NEW_LINE
Find the number of occurrences of a character upto preceding position | Function to find the number of occurrences of a character at position P upto p - 1 ; Return the required count ; Driver code ; Function call
def Occurrence ( s , position ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( position - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ position - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT s = " ababababab " ; NEW_LINE p = 9 NEW_LINE print ( Occurrence ( s , p ) ) NEW_LINE
Find the number of occurrences of a character upto preceding position | Function to find the number of occurrences of a character at position P upto p - 1 ; Iterate over the string ; Store the Occurrence of same character ; Increase its frequency ; Return the required count ; Driver code ; Function call
def countOccurrence ( s , position ) : NEW_LINE INDENT alpha = [ 0 ] * 26 NEW_LINE b = [ 0 ] * len ( s ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT b [ i ] = alpha [ ord ( s [ i ] ) - 97 ] NEW_LINE alpha [ ord ( s [ i ] ) - 97 ] = alpha [ ord ( s [ i ] ) - 97 ] + 1 NEW_LINE DEDENT return b [ position - 1 ] NEW_LINE DEDENT s = " ababababab " NEW_LINE p = 9 NEW_LINE print ( countOccurrence ( s , p ) ) NEW_LINE
Map every character of one string to another such that all occurrences are mapped to the same character | Python 3 implementation of the approach ; Function that returns true if the mapping is possible ; Both the strings are of un - equal lengths ; To store the frequencies of the characters in both the string ; Update frequencies of the characters ; For every character of s1 ; If current character is not present in s1 ; Find a character in s2 that has frequency equal to the current character 's frequency in s1 ; If such character is found ; Set the frequency to - 1 so that it doesn 't get picked again ; Set found to true ; If there is no character in s2 that could be mapped to the current character in s1 ; Driver code
MAX = 26 NEW_LINE def canBeMapped ( s1 , l1 , s2 , l2 ) : NEW_LINE INDENT if ( l1 != l2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT freq1 = [ 0 for i in range ( MAX ) ] NEW_LINE freq2 = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT freq1 [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT freq2 [ ord ( s2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq1 [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT found = False NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT if ( freq1 [ i ] == freq2 [ j ] ) : NEW_LINE INDENT freq2 [ j ] = - 1 NEW_LINE found = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " axx " NEW_LINE s2 = " cbc " NEW_LINE l1 = len ( s1 ) NEW_LINE l2 = len ( s2 ) NEW_LINE if ( canBeMapped ( s1 , l1 , s2 , l2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Distinct strings such that they contains given strings as sub | Set to store strings and aduplicates ; Recursive function to generate the required strings ; If currentis part of the result ; Insert it into the set ; If character from str1 can be chosen ; If character from str2 can be chosen ; Function to print the generated strings from the set ; Driver code
stringSet = dict ( ) NEW_LINE def find_permutation ( str1 , str2 , len1 , len2 , i , j , res ) : NEW_LINE INDENT if ( len ( res ) == len1 + len2 ) : NEW_LINE INDENT stringSet [ res ] = 1 NEW_LINE return NEW_LINE DEDENT if ( i < len1 ) : NEW_LINE INDENT find_permutation ( str1 , str2 , len1 , len2 , i + 1 , j , res + str1 [ i ] ) NEW_LINE DEDENT if ( j < len2 ) : NEW_LINE INDENT find_permutation ( str1 , str2 , len1 , len2 , i , j + 1 , res + str2 [ j ] ) NEW_LINE DEDENT DEDENT def print_set ( ) : NEW_LINE INDENT for i in stringSet : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT str1 = " aa " NEW_LINE str2 = " ab " NEW_LINE len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE find_permutation ( str1 , str2 , len1 , len2 , 0 , 0 , " " ) NEW_LINE print_set ( ) NEW_LINE
Generate all possible strings such that char at index i is either str1 [ i ] or str2 [ i ] | Recursive function to generate the required strings ; If length of the current string is equal to the length of the given strings then the current string is part of the result ; Choosing the current character from the string a ; Choosing the current character from the string b ; Driver code ; Third argument is an empty string that we will be appended in the recursion calls Fourth arguments is the length of the resultant string so far
def generateStr ( a , b , s , count , len ) : NEW_LINE INDENT if ( count == len ) : NEW_LINE INDENT print ( s ) ; NEW_LINE return ; NEW_LINE DEDENT generateStr ( a [ 1 : ] , b [ 1 : ] , s + a [ 0 ] , count + 1 , len ) ; NEW_LINE generateStr ( a [ 1 : ] , b [ 1 : ] , s + b [ 0 ] , count + 1 , len ) ; NEW_LINE DEDENT a = " abc " ; b = " def " ; NEW_LINE n = len ( a ) ; NEW_LINE generateStr ( a , b , " " , 0 , n ) ; NEW_LINE
Program to generate all possible valid IP addresses from given string | Set 2 | Function to get all the valid ip - addresses ; If index greater than givenString size and we have four block ; Remove the last dot ; Add ip - address to the results ; To add one index to ip - address ; Select one digit and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove two index ( one for the digit and other for the dot ) from the end ; Select two consecutive digits and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove three index from the end ; Select three consecutive digits and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove four index from the end ; Driver code ; Fill result vector with all valid ip - addresses ; Print all the generated ip - addresses
def GetAllValidIpAddress ( result , givenString , index , count , ipAddress ) : NEW_LINE INDENT if ( len ( givenString ) == index and count == 4 ) : NEW_LINE INDENT ipAddress . pop ( ) ; NEW_LINE result . append ( ipAddress ) ; NEW_LINE return ; NEW_LINE DEDENT if ( len ( givenString ) < index + 1 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ipAddress = ( ipAddress + givenString [ index : index + 1 ] + [ ' . ' ] ) ; NEW_LINE GetAllValidIpAddress ( result , givenString , index + 1 , count + 1 , ipAddress ) ; NEW_LINE ipAddress = ipAddress [ : - 2 ] ; NEW_LINE if ( len ( givenString ) < index + 2 or givenString [ index ] == '0' ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ipAddress = ipAddress + givenString [ index : index + 2 ] + [ ' . ' ] ; NEW_LINE GetAllValidIpAddress ( result , givenString , index + 2 , count + 1 , ipAddress ) ; NEW_LINE ipAddress = ipAddress [ : - 3 ] ; NEW_LINE if ( len ( givenString ) < index + 3 or int ( " " . join ( givenString [ index : index + 3 ] ) ) > 255 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT ipAddress += givenString [ index : index + 3 ] + [ ' . ' ] ; NEW_LINE GetAllValidIpAddress ( result , givenString , index + 3 , count + 1 , ipAddress ) ; NEW_LINE ipAddress = ipAddress [ : - 4 ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT givenString = list ( "25525511135" ) ; NEW_LINE result = [ ] ; NEW_LINE GetAllValidIpAddress ( result , givenString , 0 , 0 , [ ] ) ; NEW_LINE for i in range ( len ( result ) ) : NEW_LINE INDENT print ( " " . join ( result [ i ] ) ) ; NEW_LINE DEDENT DEDENT
Count of non | Function to return the count of required non - overlapping sub - strings ; To store the required count ; If "010" matches the sub - string starting at current index i ; If "101" matches the sub - string starting at current index i ; Driver code
def countSubStr ( s , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE i = 0 NEW_LINE while i < ( n - 2 ) : NEW_LINE INDENT if ( s [ i ] == '0' and s [ i + 1 ] == '1' and s [ i + 2 ] == '0' ) : NEW_LINE INDENT count += 1 ; NEW_LINE i += 3 ; NEW_LINE DEDENT elif ( s [ i ] == '1' and s [ i + 1 ] == '0' and s [ i + 2 ] == '1' ) : NEW_LINE INDENT count += 1 ; NEW_LINE i += 3 ; NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "10101010101" ; NEW_LINE n = len ( s ) ; NEW_LINE print ( countSubStr ( s , n ) ) ; NEW_LINE DEDENT
Find distinct characters in distinct substrings of a string | Function to return the count of distinct characters in all the distinct sub - strings of the given string ; To store all the sub - strings ; To store the current sub - string ; To store the characters of the current sub - string ; If current sub - string hasn 't been stored before ; Insert it into the set ; Update the count of distinct characters ; Driver code
def countTotalDistinct ( string ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE items = set ( ) ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT temp = " " ; NEW_LINE ans = set ( ) ; NEW_LINE for j in range ( i , len ( string ) ) : NEW_LINE INDENT temp = temp + string [ j ] ; NEW_LINE ans . add ( string [ j ] ) ; NEW_LINE if temp not in items : NEW_LINE INDENT items . add ( temp ) ; NEW_LINE cnt += len ( ans ) ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ABCA " ; NEW_LINE print ( countTotalDistinct ( string ) ) ; NEW_LINE DEDENT
Partition the string in two parts such that both parts have at least k different characters | Function to find the partition of the string such that both parts have at least k different characters ; Length of the string ; To check if the current character is already found ; Count number of different characters in the left part ; If current character is not already found , increase cnt by 1 ; If count becomes equal to k , we 've got the first part, therefore, store current index and break the loop ; Increment i by 1 ; Clear the map ; Assign cnt as 0 ; If the current character is not already found , increase cnt by 1 ; If cnt becomes equal to k , the second part also have k different characters so break it ; If the second part has less than k different characters , then print " Not ▁ Possible " ; Otherwise print both parts ; Driver code ; Function call
def division_of_string ( string , k ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE has = { } ; NEW_LINE cnt = 0 ; i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if string [ i ] not in has : NEW_LINE INDENT cnt += 1 ; NEW_LINE has [ string [ i ] ] = True ; NEW_LINE DEDENT if ( cnt == k ) : NEW_LINE INDENT ans = i ; NEW_LINE break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE has . clear ( ) ; NEW_LINE cnt = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( string [ i ] not in has ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE has [ string [ i ] ] = True ; NEW_LINE DEDENT if ( cnt == k ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT if ( cnt < k ) : NEW_LINE INDENT print ( " Not ▁ possible " , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT i = 0 ; NEW_LINE while ( i <= ans ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT print ( ) ; NEW_LINE while ( i < n ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE k = 4 ; NEW_LINE division_of_string ( string , k ) ; NEW_LINE DEDENT
Count substrings that contain all vowels | SET 2 | Function that returns true if c is a vowel ; Function to return the count of sub - strings that contain every vowel at least once and no consonant ; Map is used to store count of each vowel ; Start index is set to 0 initially ; If substring till now have all vowels atleast once increment start index until there are all vowels present between ( start , i ) and add n - i each time ; Function to extract all maximum length sub - strings in s that contain only vowels and then calls the countSubstringsUtil ( ) to find the count of valid sub - strings in that string ; If current character is a vowel then append it to the temp string ; The sub - string containing all vowels ends here ; If there was a valid sub - string ; Reset temp string ; For the last valid sub - string ; 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 countSubstringsUtil ( s ) : NEW_LINE INDENT count = 0 ; NEW_LINE mp = dict . fromkeys ( s , 0 ) ; NEW_LINE n = len ( s ) ; NEW_LINE start = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ s [ i ] ] += 1 ; NEW_LINE while ( mp [ ' a ' ] > 0 and mp [ ' e ' ] > 0 and mp [ ' i ' ] > 0 and mp [ ' o ' ] > 0 and mp [ ' u ' ] > 0 ) : NEW_LINE INDENT count += n - i ; NEW_LINE mp [ s [ start ] ] -= 1 ; NEW_LINE start += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT def countSubstrings ( s ) : NEW_LINE INDENT count = 0 ; NEW_LINE temp = " " ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) ) : NEW_LINE INDENT temp += s [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( len ( temp ) > 0 ) : NEW_LINE INDENT count += countSubstringsUtil ( temp ) ; NEW_LINE DEDENT temp = " " ; NEW_LINE DEDENT DEDENT if ( len ( temp ) > 0 ) : NEW_LINE INDENT count += countSubstringsUtil ( temp ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aeouisddaaeeiouua " ; NEW_LINE print ( countSubstrings ( s ) ) ; NEW_LINE DEDENT
Remove first adjacent pairs of similar characters until possible | Function to remove adjacent duplicates ; Iterate for every character in the string ; If ans string is empty or its last character does not match with the current character then append this character to the string ; Matches with the previous one ; Return the answer ; Driver Code
def removeDuplicates ( S ) : NEW_LINE INDENT ans = " " ; NEW_LINE for it in S : NEW_LINE INDENT if ( ans == " " or ans [ - 1 ] != it ) : NEW_LINE INDENT ans += it ; NEW_LINE DEDENT elif ( ans [ - 1 ] == it ) : NEW_LINE INDENT ans = ans [ : - 1 ] ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " keexxllx " ; NEW_LINE print ( removeDuplicates ( string ) ) ; NEW_LINE DEDENT
Reverse individual words with O ( 1 ) extra space | Function to resturn the after reversing the individual words ; Pointer to the first character of the first word ; If the current word has ended ; Pointer to the last character of the current word ; Reverse the current word ; Pointer to the first character of the next word ; Driver code
def reverseWords ( Str ) : NEW_LINE INDENT start = 0 NEW_LINE for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( Str [ i ] == ' ▁ ' or i == len ( Str ) - 1 ) : NEW_LINE INDENT end = i - 1 NEW_LINE if ( i == len ( Str ) - 1 ) : NEW_LINE INDENT end = i NEW_LINE DEDENT while ( start < end ) : NEW_LINE INDENT Str [ start ] , Str [ end ] = Str [ end ] , Str [ start ] NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT start = i + 1 NEW_LINE DEDENT DEDENT return " " . join ( Str ) NEW_LINE DEDENT Str = " Geeks ▁ for ▁ Geeks " NEW_LINE Str = [ i for i in Str ] NEW_LINE print ( reverseWords ( Str ) ) NEW_LINE
Reverse the Words of a String using Stack | Function to reverse the words of the given sentence ; Create an empty character array stack ; Push words into the stack ; Get the words in reverse order ; Driver code
def reverse ( k ) : NEW_LINE INDENT s = [ ] NEW_LINE token = k . split ( ) NEW_LINE for word in token : NEW_LINE INDENT s . append ( word ) ; NEW_LINE DEDENT while ( len ( s ) ) : NEW_LINE INDENT print ( s . pop ( ) , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = " geeks ▁ for ▁ geeks " ; NEW_LINE reverse ( k ) ; NEW_LINE DEDENT
Count of substrings which contains a given character K times | Function to count the number of substrings which contains the character C exactly K times ; left and right counters for characters on both sides of subwindow ; left and right pointer on both sides of subwindow ; Initialize the frequency ; result and Length of string ; initialize the left pointer ; initialize the right pointer ; traverse all the window substrings ; counting the characters on leftSide of subwindow ; counting the characters on rightSide of subwindow ; Add the possible substrings on both sides to result ; Setting the frequency for next subwindow ; reset the left , right counters ; Driver code
def countSubString ( s , c , k ) : NEW_LINE INDENT leftCount = 0 NEW_LINE rightCount = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE freq = 0 NEW_LINE result = 0 NEW_LINE Len = len ( s ) NEW_LINE while ( s [ left ] != c and left < Len ) : NEW_LINE INDENT left += 1 NEW_LINE leftCount += 1 NEW_LINE DEDENT right = left + 1 NEW_LINE while ( freq != ( k - 1 ) and ( right - 1 ) < Len ) : NEW_LINE INDENT if ( s [ right ] == c ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT right += 1 NEW_LINE DEDENT while ( left < Len and ( right - 1 ) < Len ) : NEW_LINE INDENT while ( s [ left ] != c and left < Len ) : NEW_LINE INDENT left += 1 NEW_LINE leftCount += 1 NEW_LINE DEDENT while ( right < Len and s [ right ] != c ) : NEW_LINE INDENT if ( s [ right ] == c ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT right += 1 NEW_LINE rightCount += 1 NEW_LINE DEDENT result = ( result + ( leftCount + 1 ) * ( rightCount + 1 ) ) NEW_LINE freq = k - 1 NEW_LINE leftCount = 0 NEW_LINE rightCount = 0 NEW_LINE left += 1 NEW_LINE right += 1 NEW_LINE DEDENT return result NEW_LINE DEDENT s = "3123231" NEW_LINE c = '3' NEW_LINE k = 2 NEW_LINE print ( countSubString ( s , c , k ) ) NEW_LINE
Count of sub | Python3 implementation of the approach ; Function to return the total required sub - sequences ; Find ways for all values of x ; x + 1 ; Removing all unnecessary digits ; Prefix Sum Array for X + 1 digit ; Sum of squares ; Previous sum of all possible pairs ; To find sum of multiplication of all possible pairs ; To prevent overcounting ; Adding ways for all possible x ; Driver code
MOD = 1000000007 NEW_LINE def solve ( test ) : NEW_LINE INDENT size = len ( test ) NEW_LINE total = 0 NEW_LINE for i in range ( 9 ) : NEW_LINE INDENT x = i NEW_LINE y = i + 1 NEW_LINE newtest = " " NEW_LINE for j in range ( size ) : NEW_LINE INDENT if ( ord ( test [ j ] ) == x + 48 or ord ( test [ j ] ) == y + 48 ) : NEW_LINE INDENT newtest += test [ j ] NEW_LINE DEDENT DEDENT if ( len ( newtest ) > 0 ) : NEW_LINE INDENT size1 = len ( newtest ) NEW_LINE prefix = [ 0 for i in range ( size1 ) ] NEW_LINE for j in range ( size1 ) : NEW_LINE INDENT if ( ord ( newtest [ j ] ) == y + 48 ) : NEW_LINE INDENT prefix [ j ] += 1 NEW_LINE DEDENT DEDENT for j in range ( 1 , size1 ) : NEW_LINE INDENT prefix [ j ] += prefix [ j - 1 ] NEW_LINE DEDENT count = 0 NEW_LINE firstcount = 0 NEW_LINE ss = 0 NEW_LINE prev = 0 NEW_LINE for j in range ( size1 ) : NEW_LINE INDENT if ( ord ( newtest [ j ] ) == x + 48 ) : NEW_LINE INDENT count += 1 NEW_LINE firstcount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ss += count * count NEW_LINE pairsum = ( firstcount * firstcount - ss ) // 2 NEW_LINE temp = pairsum NEW_LINE pairsum -= prev NEW_LINE prev = temp NEW_LINE secondway = prefix [ size1 - 1 ] NEW_LINE if ( j != 0 ) : NEW_LINE INDENT secondway -= prefix [ j - 1 ] NEW_LINE DEDENT answer = count * ( count - 1 ) * secondway * ( secondway - 1 ) NEW_LINE answer //= 4 NEW_LINE answer += ( pairsum * secondway * ( secondway - 1 ) ) // 2 NEW_LINE total += answer NEW_LINE count = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT return total NEW_LINE DEDENT test = "13134422" NEW_LINE print ( solve ( test ) ) NEW_LINE
Find if it is possible to make a binary string which contanins given number of "0" , "1" , "01" and "10" as sub sequences | Function that returns true if it is possible to make a binary string consisting of l 0 ' s , ▁ m ▁ 1' s , x "01" sub - sequences and y "10" sub - sequences ; Driver code
def isPossible ( l , m , x , y ) : NEW_LINE INDENT if ( l * m == x + y ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 3 ; m = 2 ; x = 4 ; y = 2 ; NEW_LINE if ( isPossible ( l , m , x , y ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Count pairs of characters in a string whose ASCII value difference is K | Python3 implementation of the approach ; Function to return the count of required pairs of characters ; Length of the string ; To store the frequency of each character ; Update the frequency of each character ; To store the required count of pairs ; If ascii value difference is zero ; If there exists similar characters more than once ; If there exits characters with ASCII value difference as k ; Return the required count ; Driver code
MAX = 26 NEW_LINE def countPairs ( string , k ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE if ( k == 0 ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] > 1 ) : NEW_LINE INDENT cnt += ( ( freq [ i ] * ( freq [ i ] - 1 ) ) // 2 ) ; NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] > 0 and i + k < MAX and freq [ i + k ] > 0 ) : NEW_LINE INDENT cnt += ( freq [ i ] * freq [ i + k ] ) ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcdab " ; NEW_LINE k = 0 ; NEW_LINE print ( countPairs ( string , k ) ) ; NEW_LINE DEDENT
Count of three non | Function that returns true if s [ i ... j ] + s [ k ... l ] + s [ p ... q ] is a palindrome ; Function to return the count of valid sub - strings ; To store the count of required sub - strings ; For choosing the first sub - string ; For choosing the second sub - string ; For choosing the third sub - string ; Check if the concatenation is a palindrome ; Driver code
def isPalin ( i , j , k , l , p , q , s ) : NEW_LINE INDENT start = i ; end = q ; NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( s [ start ] != s [ end ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT start += 1 ; NEW_LINE if ( start == j + 1 ) : NEW_LINE INDENT start = k ; NEW_LINE DEDENT end -= 1 ; NEW_LINE if ( end == p - 1 ) : NEW_LINE INDENT end = l ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def countSubStr ( s ) : NEW_LINE INDENT count = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT for j in range ( i , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in range ( k , n - 1 ) : NEW_LINE INDENT for p in range ( l + 1 , n ) : NEW_LINE INDENT for q in range ( p , n ) : NEW_LINE INDENT if ( isPalin ( i , j , k , l , p , q , s ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abca " ; NEW_LINE print ( countSubStr ( s ) ) ; NEW_LINE DEDENT
Find the sum of the ascii values of characters which are present at prime positions | Python3 implementation of the approach ; Function that returns true if n is prime ; Function to return the sum of the ascii values of the characters which are present at prime positions ; To store the sum ; For every character ; If current position is prime then add the ASCII value of the character at the current position ; Driver code
from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def sumAscii ( string , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isPrime ( i + 1 ) ) : NEW_LINE INDENT sum += ord ( string [ i ] ) ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE n = len ( string ) ; NEW_LINE print ( sumAscii ( string , n ) ) ; NEW_LINE DEDENT
Count the nodes of the tree which make a pangram when concatenated with the sub | Python3 implementation of the approach ; Function that returns if the string x is a pangram ; Function to return the count of nodes which make pangram with the sub - tree nodes ; Function to perform dfs and update the nodes such that weight [ i ] will store the weight [ i ] concatenated with the weights of all the nodes in the sub - tree ; Driver code ; Weights of the nodes ; Edges of the tree
graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE def Pangram ( x ) : NEW_LINE INDENT mp = { } NEW_LINE n = len ( x ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if x [ i ] not in mp : NEW_LINE INDENT mp [ x [ i ] ] = 0 NEW_LINE DEDENT mp [ x [ i ] ] += 1 NEW_LINE DEDENT if ( len ( mp ) == 26 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def countTotalPangram ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( Pangram ( weight [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT def dfs ( node , parent ) : NEW_LINE INDENT for to in graph [ node ] : NEW_LINE INDENT if ( to == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( to , node ) NEW_LINE weight [ node ] += weight [ to ] NEW_LINE DEDENT DEDENT n = 6 NEW_LINE weight [ 1 ] = " abcde " NEW_LINE weight [ 2 ] = " fghijkl " NEW_LINE weight [ 3 ] = " abcdefg " NEW_LINE weight [ 4 ] = " mnopqr " NEW_LINE weight [ 5 ] = " stuvwxy " NEW_LINE weight [ 6 ] = " zabcdef " NEW_LINE graph [ 1 ] . append ( 2 ) NEW_LINE graph [ 2 ] . append ( 3 ) NEW_LINE graph [ 2 ] . append ( 4 ) NEW_LINE graph [ 1 ] . append ( 5 ) NEW_LINE graph [ 5 ] . append ( 6 ) NEW_LINE dfs ( 1 , 1 ) NEW_LINE print ( countTotalPangram ( n ) ) NEW_LINE
Count the nodes of a tree whose weighted string does not contain any duplicate characters | Python3 implementation of the approach ; Function that returns true if the string contains unique characters ; Function to perform dfs ; If weight of the current node node contains unique characters ; Driver code ; Weights of the node ; Edges of the tree
cnt = 0 NEW_LINE graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE def uniqueChars ( x ) : NEW_LINE INDENT mp = { } NEW_LINE n = len ( x ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if x [ i ] not in mp : NEW_LINE INDENT mp [ x [ i ] ] = 0 NEW_LINE DEDENT mp [ x [ i ] ] += 1 NEW_LINE DEDENT if ( len ( mp ) == len ( x ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def dfs ( node , parent ) : NEW_LINE INDENT global cnt , x NEW_LINE if ( uniqueChars ( weight [ node ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT for to in graph [ node ] : NEW_LINE INDENT if ( to == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( to , node ) NEW_LINE DEDENT DEDENT x = 5 NEW_LINE weight [ 1 ] = " abc " NEW_LINE weight [ 2 ] = " aba " NEW_LINE weight [ 3 ] = " bcb " NEW_LINE weight [ 4 ] = " moh " NEW_LINE weight [ 5 ] = " aa " NEW_LINE graph [ 1 ] . append ( 2 ) NEW_LINE graph [ 2 ] . append ( 3 ) NEW_LINE graph [ 2 ] . append ( 4 ) NEW_LINE graph [ 1 ] . append ( 5 ) NEW_LINE dfs ( 1 , 1 ) NEW_LINE print ( cnt ) NEW_LINE
Check if a string contains two non overlapping sub | Function that returns true if s contains two non overlapping sub strings " geek " and " keeg " ; If " geek " and " keeg " are both present in s without over - lapping and " keeg " starts after " geek " ends ; Driver code
def isValid ( s ) : NEW_LINE INDENT p = " " NEW_LINE p = s . find ( " geek " ) NEW_LINE if ( s . find ( " keeg " , p + 4 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geekeekeeg " NEW_LINE if ( isValid ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Find the last non repeating character in string | Maximum distinct characters possible ; Function to return the last non - repeating character ; To store the frequency of each of the character of the given string ; Update the frequencies ; Starting from the last character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the string are repeating ; Driver code
MAX = 256 ; NEW_LINE def lastNonRepeating ( string , n ) : NEW_LINE INDENT freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) ] += 1 ; NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT ch = string [ i ] ; NEW_LINE if ( freq [ ord ( ch ) ] == 1 ) : NEW_LINE INDENT return ( " " + ch ) ; NEW_LINE DEDENT DEDENT return " - 1" ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GeeksForGeeks " ; NEW_LINE n = len ( string ) ; NEW_LINE print ( lastNonRepeating ( string , n ) ) ; NEW_LINE DEDENT
Minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B | Function to return the minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B ; Initialize result ; Loop through last b digits ; Driver code
def findCount ( s , n , a , b ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( b ) : NEW_LINE INDENT if ( i == a ) : NEW_LINE INDENT res += ( s [ n - i - 1 ] != '1' ) NEW_LINE DEDENT else : NEW_LINE INDENT res += ( s [ n - i - 1 ] != '0' ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "1001011001" NEW_LINE N = len ( str ) NEW_LINE A = 3 NEW_LINE B = 6 NEW_LINE print ( findCount ( str , N , A , B ) ) NEW_LINE DEDENT
Find letter 's position in Alphabet using Bit operation | Python3 implementation of the approach ; Function to calculate the position of characters ; Performing AND operation with number 31 ; Driver code
NUM = 31 NEW_LINE def positions ( str ) : NEW_LINE INDENT for i in str : NEW_LINE INDENT print ( ( ord ( i ) & NUM ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT str = " Geeks " NEW_LINE positions ( str ) NEW_LINE
Generate all permutations of a string that follow given constraints | Simple Python program to print all permutations of a string that follow given constraint ; Check if current permutation is valid ; Recursively generate all permutation ; Driver Code
def permute ( str , l , r ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT if " AB " not in ' ' . join ( str ) : NEW_LINE INDENT print ( ' ' . join ( str ) , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT str [ l ] , str [ i ] = str [ i ] , str [ l ] NEW_LINE permute ( str , l + 1 , r ) NEW_LINE str [ l ] , str [ i ] = str [ i ] , str [ l ] NEW_LINE DEDENT DEDENT str = " ABC " NEW_LINE permute ( list ( str ) , 0 , len ( str ) - 1 ) NEW_LINE
Length of the longest substring that do not contain any palindrome | Function to find the length of the longest substring ; initializing the variables ; checking palindrome of size 2 example : aa ; checking palindrome of size 3 example : aba ; else : incrementing length of substring ; If there exits single character then it is always palindrome ; Driver Code
def lenoflongestnonpalindrome ( s ) : NEW_LINE INDENT max1 , length = 1 , 0 NEW_LINE for i in range ( 0 , len ( s ) - 1 ) : NEW_LINE INDENT if s [ i ] == s [ i + 1 ] : NEW_LINE INDENT length = 0 NEW_LINE DEDENT elif s [ i + 1 ] == s [ i - 1 ] and i > 0 : NEW_LINE INDENT length = 1 NEW_LINE length += 1 NEW_LINE DEDENT DEDENT if max1 == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return max1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " synapse " NEW_LINE print ( lenoflongestnonpalindrome ( s ) ) NEW_LINE DEDENT
Calculate score for the given binary string | Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code
def calcScore ( str ) : NEW_LINE INDENT score = 0 NEW_LINE len1 = len ( str ) NEW_LINE i = 0 NEW_LINE while ( i < len1 ) : NEW_LINE INDENT chunkSize = 1 NEW_LINE currentChar = str [ i ] NEW_LINE i += 1 NEW_LINE while ( i < len1 and str [ i ] == currentChar ) : NEW_LINE INDENT chunkSize += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( currentChar == '1' ) : NEW_LINE INDENT score += pow ( chunkSize , 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT score -= pow ( chunkSize , 2 ) NEW_LINE DEDENT DEDENT return score NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "11011" NEW_LINE print ( calcScore ( str ) ) NEW_LINE DEDENT
Number of sub | Function to return the count of required sub - strings ; Left and right counters for characters on both sides of sub - string window ; Left and right pointer on both sides of sub - string window ; Initialize the frequency ; Result and length of string ; Initialize the left pointer ; Initialize the right pointer ; Traverse all the window sub - strings ; Counting the characters on left side of the sub - string window ; Counting the characters on right side of the sub - string window ; Add the possible sub - strings on both sides to result ; Setting the frequency for next sub - string window ; Reset the left and right counters ; Driver code
def countSubString ( s , c , k ) : NEW_LINE INDENT leftCount = 0 NEW_LINE rightCount = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE freq = 0 NEW_LINE result = 0 NEW_LINE len1 = len ( s ) NEW_LINE while ( s [ left ] != c and left < len1 ) : NEW_LINE INDENT left += 1 NEW_LINE leftCount += 1 NEW_LINE DEDENT right = left + 1 NEW_LINE while ( freq != ( k - 1 ) and ( right - 1 ) < len1 ) : NEW_LINE INDENT if ( s [ right ] == c ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT right += 1 NEW_LINE DEDENT while ( left < len1 and ( right - 1 ) < len1 ) : NEW_LINE INDENT while ( s [ left ] != c and left < len1 ) : NEW_LINE INDENT left += 1 NEW_LINE leftCount += 1 NEW_LINE DEDENT while ( right < len1 and s [ right ] != c ) : NEW_LINE INDENT if ( s [ right ] == c ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT right += 1 NEW_LINE rightCount += 1 NEW_LINE DEDENT result = ( result + ( leftCount + 1 ) * ( rightCount + 1 ) ) NEW_LINE freq = k - 1 NEW_LINE leftCount = 0 NEW_LINE rightCount = 0 NEW_LINE left += 1 NEW_LINE right += 1 NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " abada " NEW_LINE c = ' a ' NEW_LINE k = 2 NEW_LINE print ( countSubString ( s , c , k ) ) NEW_LINE DEDENT
Maximum length palindrome that can be created with characters in range L and R | Python3 implementation of the approach ; Function to return the length of the longest palindrome that can be formed using the characters in the range [ l , r ] ; 0 - based indexing ; Marks if there is an odd frequency character ; Length of the longest palindrome possible from characters in range ; Traverse for all characters and count their frequencies ; Find the frequency in range 1 - r ; Exclude the frequencies in range 1 - ( l - 1 ) ; If frequency is odd , then add 1 less than the original frequency to make it even ; Else completely add if even ; If any odd frequency character is present then add 1 ; Function to pre - calculate the frequencies of the characters to reduce complexity ; Iterate and increase the count ; Create a prefix type array ; Driver code ; Pre - calculate prefix array ; Perform queries
N = 4 NEW_LINE def performQueries ( l , r , prefix ) : NEW_LINE INDENT l -= 1 NEW_LINE r -= 1 NEW_LINE flag = False NEW_LINE count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT cnt = prefix [ r ] [ i ] NEW_LINE if ( l > 0 ) : NEW_LINE INDENT cnt -= prefix [ l - 1 ] [ i ] NEW_LINE DEDENT if ( cnt % 2 == 1 ) : NEW_LINE INDENT flag = True NEW_LINE count += cnt - 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += cnt NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def preCalculate ( s , prefix ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix [ i ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT prefix [ i ] [ j ] += prefix [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT s = " amim " NEW_LINE prefix = [ [ 0 for i in range ( 26 ) ] for i in range ( N ) ] NEW_LINE preCalculate ( s , prefix ) NEW_LINE queries = [ [ 1 , 4 ] , [ 3 , 4 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( performQueries ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , prefix ) ) NEW_LINE DEDENT
Number of times the given string occurs in the array in the range [ l , r ] | Python implementation of the approach ; Function to return the number of occurrences of ; To store the indices of strings in the array ; If current string doesn 't have an entry in the map then create the entry ; If the given string is not present in the array ; If the given string is present in the array ; Driver Code
from bisect import bisect_right as upper_bound NEW_LINE from collections import defaultdict NEW_LINE def numOccurences ( arr : list , n : int , string : str , L : int , R : int ) -> int : NEW_LINE INDENT M = defaultdict ( lambda : list ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if temp not in M : NEW_LINE INDENT A = [ ] NEW_LINE A . append ( i + 1 ) NEW_LINE M [ temp ] = A NEW_LINE DEDENT else : NEW_LINE INDENT M [ temp ] . append ( i + 1 ) NEW_LINE DEDENT DEDENT if string not in M : NEW_LINE INDENT return 0 NEW_LINE DEDENT A = M [ string ] NEW_LINE y = upper_bound ( A , R ) NEW_LINE x = upper_bound ( A , L - 1 ) NEW_LINE return ( y - x ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " abc " , " abcabc " , " abc " ] NEW_LINE n = len ( arr ) NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE string = " abc " NEW_LINE print ( numOccurences ( arr , n , string , L , R ) ) NEW_LINE DEDENT
Check whether the given string is a valid identifier | Function that returns true if str1 is a valid identifier ; If first character is invalid ; Traverse the for the rest of the characters ; is a valid identifier ; Driver code
def isValid ( str1 , n ) : NEW_LINE INDENT if ( ( ( ord ( str1 [ 0 ] ) >= ord ( ' a ' ) and ord ( str1 [ 0 ] ) <= ord ( ' z ' ) ) or ( ord ( str1 [ 0 ] ) >= ord ( ' A ' ) and ord ( str1 [ 0 ] ) <= ord ( ' Z ' ) ) or ord ( str1 [ 0 ] ) == ord ( ' _ ' ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 1 , len ( str1 ) ) : NEW_LINE INDENT if ( ( ( ord ( str1 [ i ] ) >= ord ( ' a ' ) and ord ( str1 [ i ] ) <= ord ( ' z ' ) ) or ( ord ( str1 [ i ] ) >= ord ( ' A ' ) and ord ( str1 [ i ] ) <= ord ( ' Z ' ) ) or ( ord ( str1 [ i ] ) >= ord ( '0' ) and ord ( str1 [ i ] ) <= ord ( '9' ) ) or ord ( str1 [ i ] ) == ord ( ' _ ' ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT str1 = " _ geeks123" NEW_LINE n = len ( str1 ) NEW_LINE if ( isValid ( str1 , n ) ) : NEW_LINE INDENT print ( " Valid " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE DEDENT
Check if all the 1 's in a binary string are equidistant or not | Function that returns true if all the 1 's in the binary s are equidistant ; Initialize vector to store the position of 1 's ; Store the positions of 1 's ; Size of the position vector ; If condition isn 't satisfied ; Driver code
def check ( s , l ) : NEW_LINE INDENT pos = [ ] NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT DEDENT t = len ( pos ) NEW_LINE for i in range ( 1 , t ) : NEW_LINE INDENT if ( ( pos [ i ] - pos [ i - 1 ] ) != ( pos [ 1 ] - pos [ 0 ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = "100010001000" NEW_LINE l = len ( s ) NEW_LINE if ( check ( s , l ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Capitalize the first and last character of each word in a string | Python3 program to capitalise the first and last character of each word in a string . ; Create an equivalent char array of given string ; k stores index of first character and i is going to store index of last character . ; Check if the character is a small letter If yes , then Capitalise ; Driver code
def FirstAndLast ( string ) : NEW_LINE INDENT ch = list ( string ) ; NEW_LINE i = 0 ; NEW_LINE while i < len ( ch ) : NEW_LINE INDENT k = i ; NEW_LINE while ( i < len ( ch ) and ch [ i ] != ' ▁ ' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( ord ( ch [ k ] ) >= 97 and ord ( ch [ k ] ) <= 122 ) : NEW_LINE INDENT ch [ k ] = chr ( ord ( ch [ k ] ) - 32 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ch [ k ] = ch [ k ] NEW_LINE DEDENT if ( ord ( ch [ i - 1 ] ) >= 90 and ord ( ch [ i - 1 ] ) <= 122 ) : NEW_LINE INDENT ch [ i - 1 ] = chr ( ord ( ch [ i - 1 ] ) - 32 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ch [ i - 1 ] = ch [ i - 1 ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return " " . join ( ch ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " Geeks ▁ for ▁ Geeks " ; NEW_LINE print ( string ) ; NEW_LINE print ( FirstAndLast ( string ) ) ; NEW_LINE DEDENT
Find the number of players who roll the dice when the dice output sequence is given | Function to return the number of players ; Initialize cnt as 0 ; Iterate in the string ; Check for numbers other than x ; Driver code
def findM ( s , x ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) != x ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "3662123" NEW_LINE x = 6 NEW_LINE print ( findM ( s , x ) ) NEW_LINE DEDENT
Print the first and last character of each word in a String | Python3 program to print the first and last character of each word in a String ; Function to print the first and last character of each word . ; If it is the first word of the string then print it . ; If it is the last word of the string then also print it . ; If there is a space print the successor and predecessor to space . ; Driver code
' NEW_LINE def FirstAndLast ( string ) : NEW_LINE INDENT for i in range ( len ( string ) ) : NEW_LINE INDENT if i == 0 : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT if i == len ( string ) - 1 : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT if string [ i ] == " ▁ " : NEW_LINE INDENT print ( string [ i - 1 ] , string [ i + 1 ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " Geeks ▁ for ▁ Geeks " NEW_LINE FirstAndLast ( string ) NEW_LINE DEDENT
Find the longest sub | Function to find longest prefix suffix ; To store longest prefix suffix ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Loop calculates lps [ i ] for i = 1 to n - 1 ; ( pat [ i ] != pat [ Len ] ) ; If Len = 0 ; Function to find the longest substring which is prefix as well as a sub - of s [ 1. . . n - 2 ] ; Find longest prefix suffix ; If lps of n - 1 is zero ; At any position lps [ i ] equals to lps [ n - 1 ] ; If answer is not possible ; Driver code ; function call
def compute_lps ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lps = [ 0 for i in range ( n ) ] NEW_LINE Len = 0 NEW_LINE lps [ 0 ] = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( s [ i ] == s [ Len ] ) : NEW_LINE INDENT Len += 1 NEW_LINE lps [ i ] = Len NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( Len != 0 ) : NEW_LINE INDENT Len = lps [ Len - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lps [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT return lps NEW_LINE DEDENT def Longestsubstring ( s ) : NEW_LINE INDENT lps = compute_lps ( s ) NEW_LINE n = len ( s ) NEW_LINE if ( lps [ n - 1 ] == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE exit ( ) NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( lps [ i ] == lps [ n - 1 ] ) : NEW_LINE INDENT print ( s [ 0 : lps [ i ] ] ) NEW_LINE exit ( ) NEW_LINE DEDENT DEDENT if ( lps [ lps [ n - 1 ] - 1 ] == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ 0 : lps [ lps [ n - 1 ] - 1 ] ] ) NEW_LINE DEDENT DEDENT s = " fixprefixsuffix " NEW_LINE Longestsubstring ( s ) NEW_LINE
Pairs of strings which on concatenating contains each character of " string " | Python3 implementation of the approach ; Function to return the bitmask for the string ; Function to return the count of pairs ; bitMask [ i ] will store the count of strings from the array whose bitmask is i ; To store the count of pairs ; MAX - 1 = 63 i . e . 111111 in binary ; arr [ i ] cannot make s pair with itself i . e . ( arr [ i ] , arr [ i ] ) ; Driver code
MAX = 64 NEW_LINE def getBitmask ( s ) : NEW_LINE INDENT temp = 0 NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ j ] == ' s ' ) : NEW_LINE INDENT temp = temp | 1 NEW_LINE DEDENT elif ( s [ j ] == ' t ' ) : NEW_LINE INDENT temp = temp | 2 NEW_LINE DEDENT elif ( s [ j ] == ' r ' ) : NEW_LINE INDENT temp = temp | 4 NEW_LINE DEDENT elif ( s [ j ] == ' i ' ) : NEW_LINE INDENT temp = temp | 8 NEW_LINE DEDENT elif ( s [ j ] == ' n ' ) : NEW_LINE INDENT temp = temp | 16 NEW_LINE DEDENT elif ( s [ j ] == ' g ' ) : NEW_LINE INDENT temp = temp | 32 NEW_LINE DEDENT DEDENT return temp NEW_LINE DEDENT def countPairs ( arr , n ) : NEW_LINE INDENT bitMask = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT bitMask [ getBitmask ( arr [ i ] ) ] += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT for j in range ( i , MAX ) : NEW_LINE INDENT if ( ( i j ) == ( MAX - 1 ) ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT cnt += ( ( bitMask [ i ] * bitMask [ i ] - 1 ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT cnt += ( bitMask [ i ] * bitMask [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ " strrr " , " string " , " gstrin " ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE
Count of pairs of strings which differ in exactly one position | Function to return the count of same pairs ; Function to return total number of strings which satisfy required condition ; Dictionary changed will store strings with wild cards Dictionary same will store strings that are equal ; Iterating for all strings in the given array ; If we found the string then increment by 1 Else it will get default value 0 ; Iterating on a single string ; Incrementing the string if found Else it will get default value 0 ; Return counted pairs - equal pairs ; Driver code
def pair_count ( d ) : NEW_LINE INDENT return sum ( ( i * ( i - 1 ) ) // 2 for i in d . values ( ) ) NEW_LINE DEDENT def Difference ( array , m ) : NEW_LINE INDENT changed , same = { } , { } NEW_LINE for s in array : NEW_LINE INDENT same [ s ] = same . get ( s , 0 ) + 1 NEW_LINE for i in range ( m ) : NEW_LINE INDENT changed [ t ] = changed . get ( t , 0 ) + 1 NEW_LINE DEDENT DEDENT return pair_count ( changed ) - pair_count ( same ) * m NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m = 3 , 3 NEW_LINE array = [ " abc " , " abd " , " bbd " ] NEW_LINE print ( Difference ( array , m ) ) NEW_LINE DEDENT
Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | Function to return the number of ways to form the sub - string ; Initialize a hash - table with 0 ; Iterate in the string and count the frequency of characters that do not lie in the range L and R ; Out of range characters ; Stores the final number of ways ; Iterate for the sub - string in the range L and R ; If exists then multiply the number of ways and decrement the frequency ; If does not exist the sub - string cannot be formed ; Return the answer ; Driver code
def calculateWays ( s , n , l , r ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < l or i > r ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ways = 1 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT if ( freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT ways = ways * freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT ways = 0 NEW_LINE break NEW_LINE DEDENT DEDENT return ways NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " cabcaab " NEW_LINE n = len ( s ) NEW_LINE l = 1 NEW_LINE r = 3 NEW_LINE print ( calculateWays ( s , n , l , r ) ) NEW_LINE DEDENT
Program to find the kth character after decrypting a string | Function to print kth character of String s after decrypting it ; Get the length of string ; Initialise pointer to character of input string to zero ; Total length of resultant string ; Traverse the string from starting and check if each character is alphabet then increment total_len ; If total_leg equal to k then return string else increment i ; Parse the number ; Update next_total_len ; Get the position of kth character ; Position not found then update position with total_len ; Recursively find the kth position ; Else update total_len by next_total_len ; Return - 1 if character not found ; Driver code
def findKthChar ( s , k ) : NEW_LINE INDENT len1 = len ( s ) NEW_LINE i = 0 NEW_LINE total_len = 0 NEW_LINE while ( i < len1 ) : NEW_LINE INDENT if ( s [ i ] . isalpha ( ) ) : NEW_LINE INDENT total_len += 1 NEW_LINE if ( total_len == k ) : NEW_LINE INDENT return s [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT n = 0 NEW_LINE while ( i < len1 and s [ i ] . isalpha ( ) == False ) : NEW_LINE INDENT n = n * 10 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE i += 1 NEW_LINE DEDENT next_total_len = total_len * n NEW_LINE if ( k <= next_total_len ) : NEW_LINE INDENT pos = k % total_len NEW_LINE if ( pos == 0 ) : NEW_LINE INDENT pos = total_len NEW_LINE DEDENT return findKthChar ( s , pos ) NEW_LINE DEDENT else : NEW_LINE INDENT total_len = next_total_len NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " ab2c3" NEW_LINE k = 5 NEW_LINE print ( findKthChar ( s , k ) ) NEW_LINE DEDENT
Check whether the Average Character of the String is present or not | Python 3 program to check if the average character is present in the string or not ; Checks if the character is present ; Get the length of string ; Iterate from i = 0 to the length of the string to check if the character is present in the string ; Finds the average character of the string ; Calculate the sum of ASCII values of each character ; Calculate average of ascii values ; Convert the ASCII value to character and return it ; Driver code ; Get the average character ; Check if the average character is present in string or not
from math import floor NEW_LINE def check_char ( st , ch ) : NEW_LINE INDENT l = len ( st ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( st [ i ] == ch ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def find_avg ( st ) : NEW_LINE INDENT sm = 0 NEW_LINE l = len ( st ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT ch = st [ i ] NEW_LINE sm = sm + ord ( ch ) NEW_LINE DEDENT avg = int ( floor ( sm / l ) ) NEW_LINE return ( chr ( avg ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT st = " ag23sdfa " NEW_LINE ch = find_avg ( st ) NEW_LINE print ( ch ) NEW_LINE if ( check_char ( st , ch ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Convert the ASCII value sentence to its equivalent string | Function to print the character sequence for the given ASCII sentence ; Append the current digit ; If num is within the required range ; Convert num to char ; Reset num to 0 ; Driver code
def asciiToSentence ( string , length ) : NEW_LINE INDENT num = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT num = num * 10 + ( ord ( string [ i ] ) - ord ( '0' ) ) ; NEW_LINE if ( num >= 32 and num <= 122 ) : NEW_LINE INDENT ch = chr ( num ) ; NEW_LINE print ( ch , end = " " ) ; NEW_LINE num = 0 ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "7110110110711510211111471101101107115" ; NEW_LINE length = len ( string ) ; NEW_LINE asciiToSentence ( string , length ) ; NEW_LINE DEDENT
Distinct state codes that appear in a string as contiguous sub | Function to return the count of distinct state codes ; Insert every sub - string of length 2 in the set ; Return the size of the set ; Driver code
def countDistinctCode ( string ) : NEW_LINE INDENT codes = set ( ) NEW_LINE for i in range ( 0 , len ( string ) - 1 ) : NEW_LINE INDENT codes . add ( string [ i : i + 2 ] ) NEW_LINE DEDENT return len ( codes ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " UPUP " NEW_LINE print ( countDistinctCode ( string ) ) NEW_LINE DEDENT
Count of buttons pressed in a keypad mobile | Array to store how many times a button has to be pressed for typing a particular character ; Function to return the count of buttons pressed to type the given string ; Count the key presses ; Return the required count ; Driver code
arr = [ 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 4 , 1 , 2 , 3 , 1 , 2 , 3 , 4 ] ; NEW_LINE def countKeyPressed ( string , length ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT count += arr [ ord ( string [ i ] ) - ord ( ' a ' ) ] ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcdef " ; NEW_LINE length = len ( string ) ; NEW_LINE print ( countKeyPressed ( string , length ) ) ; NEW_LINE DEDENT
First string from the given array whose reverse is also present in the same array | Function that returns true if s1 is equal to reverse of s2 ; If both the strings differ in length ; In case of any character mismatch ; Function to return the first word whose reverse is also present in the array ; Check every string ; Pair with every other string appearing after the current string ; If first string is equal to the reverse of the second string ; No such string exists ; Driver code
def isReverseEqual ( s1 , s2 ) : NEW_LINE INDENT if len ( s1 ) != len ( s2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT l = len ( s1 ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if s1 [ i ] != s2 [ l - i - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def getWord ( str , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( isReverseEqual ( str [ i ] , str [ j ] ) ) : NEW_LINE INDENT return str [ i ] NEW_LINE DEDENT DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = [ " geeks " , " for " , " skeeg " ] NEW_LINE print ( getWord ( str , 3 ) ) NEW_LINE DEDENT
Check if the given string is K | Function that returns true if sub - string of length k starting at index i is also a prefix of the string ; k length sub - string cannot start at index i ; Character mismatch between the prefix and the sub - string starting at index i ; Function that returns true if str is K - periodic ; Check whether all the sub - strings str [ 0 , k - 1 ] , str [ k , 2 k - 1 ] ... are equal to the k length prefix of the string ; Driver code
def isPrefix ( string , length , i , k ) : NEW_LINE INDENT if i + k > length : NEW_LINE INDENT return False NEW_LINE DEDENT for j in range ( 0 , k ) : NEW_LINE INDENT if string [ i ] != string [ j ] : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def isKPeriodic ( string , length , k ) : NEW_LINE INDENT for i in range ( k , length , k ) : NEW_LINE INDENT if isPrefix ( string , length , i , k ) == False : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksgeeks " NEW_LINE length = len ( string ) NEW_LINE k = 5 NEW_LINE if isKPeriodic ( string , length , k ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimum number of letters needed to make a total of n | Function to return the minimum letters required to make a total of n ; Driver code
def minLettersNeeded ( n ) : NEW_LINE INDENT if n % 26 == 0 : NEW_LINE INDENT return ( n // 26 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n // 26 ) + 1 ) NEW_LINE DEDENT DEDENT n = 52 NEW_LINE print ( minLettersNeeded ( n ) ) NEW_LINE
Find the first maximum length even word from a string | Function to find maximum length even word ; To store length of current word . ; To store length of maximum length word . ; To store starting index of maximum length word . ; If current character is space then word has ended . Check if it is even length word or not . If yes then compare length with maximum length found so far . ; Set currlen to zero for next word . ; Update length of current word . ; Check length of last word . ; If no even length word is present then return - 1. ; Driver code
def findMaxLenEven ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE i = 0 NEW_LINE currlen = 0 NEW_LINE maxlen = 0 NEW_LINE st = - 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( str [ i ] == ' ▁ ' ) : NEW_LINE INDENT if ( currlen % 2 == 0 ) : NEW_LINE INDENT if ( maxlen < currlen ) : NEW_LINE INDENT maxlen = currlen NEW_LINE st = i - currlen NEW_LINE DEDENT DEDENT currlen = 0 NEW_LINE DEDENT else : NEW_LINE INDENT currlen += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( currlen % 2 == 0 ) : NEW_LINE INDENT if ( maxlen < currlen ) : NEW_LINE INDENT maxlen = currlen NEW_LINE st = i - currlen NEW_LINE DEDENT DEDENT if ( st == - 1 ) : NEW_LINE INDENT print ( " trie " ) NEW_LINE return " - 1" NEW_LINE DEDENT return str [ st : st + maxlen ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " this ▁ is ▁ a ▁ test ▁ string " NEW_LINE print ( findMaxLenEven ( str ) ) NEW_LINE DEDENT
Minimum length substring with exactly K distinct characters | Function to find minimum length substring having exactly k distinct character . ; Starting index of sliding window . ; Ending index of sliding window . ; To store count of character . ; To store count of distinct character in current sliding window . ; To store length of current sliding window . ; To store minimum length . ; To store starting index of minimum length substring . ; Increment count of current character If this count is one then a new distinct character is found in sliding window . ; If number of distinct characters is is greater than k , then move starting point of sliding window forward , until count is k . ; Remove characters from the beginning of sliding window having count more than 1 to minimize length . ; Compare length with minimum length and update if required . ; Return minimum length substring . ; Driver code
def findMinLenStr ( str , k ) : NEW_LINE INDENT n = len ( str ) NEW_LINE st = 0 NEW_LINE end = 0 NEW_LINE cnt = [ 0 ] * 26 NEW_LINE distEle = 0 NEW_LINE currlen = 0 NEW_LINE minlen = n NEW_LINE startInd = - 1 NEW_LINE while ( end < n ) : NEW_LINE INDENT cnt [ ord ( str [ end ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( cnt [ ord ( str [ end ] ) - ord ( ' a ' ) ] == 1 ) : NEW_LINE INDENT distEle += 1 NEW_LINE DEDENT if ( distEle > k ) : NEW_LINE INDENT while ( st < end and distEle > k ) : NEW_LINE INDENT if ( cnt [ ord ( str [ st ] ) - ord ( ' a ' ) ] == 1 ) : NEW_LINE INDENT distEle -= 1 NEW_LINE DEDENT cnt [ ord ( str [ st ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE st += 1 NEW_LINE DEDENT DEDENT if ( distEle == k ) : NEW_LINE INDENT while ( st < end and cnt [ ord ( str [ st ] ) - ord ( ' a ' ) ] > 1 ) : NEW_LINE INDENT cnt [ ord ( str [ st ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE st += 1 NEW_LINE DEDENT currlen = end - st + 1 NEW_LINE if ( currlen < minlen ) : NEW_LINE INDENT minlen = currlen NEW_LINE startInd = st NEW_LINE DEDENT DEDENT end += 1 NEW_LINE DEDENT return str [ startInd : startInd + minlen ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " efecfefd " NEW_LINE k = 4 NEW_LINE print ( findMinLenStr ( str , k ) ) NEW_LINE DEDENT
Minimum number of replacements to make the binary string alternating | Set 2 | Function to return the minimum number of characters of the given binary string to be replaced to make the string alternating ; If there is 1 at even index positions ; If there is 0 at odd index positions ; Driver code
def minReplacement ( s , length ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if i % 2 == 0 and s [ i ] == '1' : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT if i % 2 == 1 and s [ i ] == '0' : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return min ( ans , length - ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "1100" NEW_LINE length = len ( s ) NEW_LINE print ( minReplacement ( s , length ) ) NEW_LINE DEDENT
Deletions of "01" or "10" in binary string to make it free from "01" or "10" | Function to return the count of deletions of sub - strings "01" or "10" ; To store the count of 0 s and 1 s ; Driver code
def substrDeletion ( string , length ) : NEW_LINE INDENT count0 = 0 ; NEW_LINE count1 = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT count0 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count1 += 1 ; NEW_LINE DEDENT DEDENT return min ( count0 , count1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "010" ; NEW_LINE length = len ( string ) ; NEW_LINE print ( substrDeletion ( string , length ) ) ; NEW_LINE DEDENT
Group consecutive characters of same type in a string | Function to return the modified string ; Store original string ; Remove all white spaces ; To store the resultant string ; Traverse the string ; Group upper case characters ; Group numeric characters ; Group arithmetic operators ; Return the resultant string ; Driver code
def groupCharacters ( s , l ) : NEW_LINE INDENT temp = " " NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( s [ i ] != ' ▁ ' ) : NEW_LINE INDENT temp = temp + s [ i ] NEW_LINE DEDENT DEDENT l = len ( temp ) NEW_LINE ans = " " NEW_LINE i = 0 NEW_LINE while ( i < l ) : NEW_LINE INDENT if ( ord ( temp [ i ] ) >= ord ( ' A ' ) and ord ( temp [ i ] ) <= ord ( ' Z ' ) ) : NEW_LINE INDENT while ( i < l and ord ( temp [ i ] ) >= ord ( ' A ' ) and ord ( temp [ i ] ) <= ord ( ' Z ' ) ) : NEW_LINE INDENT ans = ans + temp [ i ] NEW_LINE i += 1 NEW_LINE DEDENT ans = ans + " ▁ " NEW_LINE DEDENT elif ( ord ( temp [ i ] ) >= ord ( '0' ) and ord ( temp [ i ] ) <= ord ( '9' ) ) : NEW_LINE INDENT while ( i < l and ord ( temp [ i ] ) >= ord ( '0' ) and ord ( temp [ i ] ) <= ord ( '9' ) ) : NEW_LINE INDENT ans = ans + temp [ i ] NEW_LINE i += 1 NEW_LINE DEDENT ans = ans + " ▁ " NEW_LINE DEDENT else : NEW_LINE INDENT while ( i < l and ord ( temp [ i ] ) >= ord ( ' * ' ) and ord ( temp [ i ] ) <= ord ( ' / ' ) ) : NEW_LINE INDENT ans = ans + temp [ i ] NEW_LINE i += 1 NEW_LINE DEDENT ans = ans + " ▁ " NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "34FTG234 + ▁ + - ▁ * " NEW_LINE l = len ( s ) NEW_LINE print ( groupCharacters ( s , l ) ) NEW_LINE DEDENT
Find the minimum number of preprocess moves required to make two strings equal | Function to return the minimum number of pre - processing moves required on string A ; Length of the given strings ; To store the required answer ; Run a loop upto n / 2 ; To store frequency of 4 characters ; If size is 4 ; If size is 3 ; If size is 2 ; If n is odd ; Driver code
def Preprocess ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE ans = 0 NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE mp [ A [ i ] ] = 1 NEW_LINE if A [ i ] == A [ n - i - 1 ] : NEW_LINE INDENT mp [ A [ n - i - 1 ] ] += 1 NEW_LINE DEDENT if B [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ B [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ B [ i ] ] = 1 NEW_LINE DEDENT if B [ n - i - 1 ] in mp . keys ( ) : NEW_LINE INDENT mp [ B [ n - 1 - i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ B [ n - 1 - i ] ] = 1 NEW_LINE DEDENT sz = len ( mp ) NEW_LINE if ( sz == 4 ) : NEW_LINE INDENT ans += 2 NEW_LINE DEDENT elif ( sz == 3 ) : NEW_LINE INDENT ans += 1 + ( A [ i ] == A [ n - i - 1 ] ) NEW_LINE DEDENT elif ( sz == 2 ) : NEW_LINE INDENT ans += mp [ A [ i ] ] != 2 NEW_LINE DEDENT DEDENT if ( n % 2 == 1 and A [ n // 2 ] != B [ n // 2 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT A = " abacaba " NEW_LINE B = " bacabaa " NEW_LINE print ( Preprocess ( A , B ) ) NEW_LINE
Check whether two strings are equivalent or not according to given condition | This function returns the least lexicogr aphical string obtained from its two halves ; Base Case - If string size is 1 ; Divide the string into its two halves ; Form least lexicographical string ; Driver Code
def leastLexiString ( s ) : NEW_LINE INDENT if ( len ( s ) & 1 != 0 ) : NEW_LINE INDENT return s NEW_LINE DEDENT x = leastLexiString ( s [ 0 : int ( len ( s ) / 2 ) ] ) NEW_LINE y = leastLexiString ( s [ int ( len ( s ) / 2 ) : len ( s ) ] ) NEW_LINE return min ( x + y , y + x ) NEW_LINE DEDENT def areEquivalent ( a , b ) : NEW_LINE INDENT return ( leastLexiString ( a ) == leastLexiString ( b ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = " aaba " NEW_LINE b = " abaa " NEW_LINE if ( areEquivalent ( a , b ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT a = " aabb " NEW_LINE b = " abab " NEW_LINE if ( areEquivalent ( a , b ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Check if a string can be converted to another string by replacing vowels and consonants | Function to check if the character is vowel or not ; Function that checks if a string can be converted to another string ; Find length of string ; If length is not same ; Iterate for every character ; If both vowel ; Both are consonants ; Driver Code
def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def checkPossibility ( s1 , s2 ) : NEW_LINE INDENT l1 = len ( s1 ) NEW_LINE l2 = len ( s2 ) NEW_LINE if ( l1 != l2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( l1 ) : NEW_LINE INDENT if ( isVowel ( s1 [ i ] ) and isVowel ( s2 [ i ] ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( ( isVowel ( s1 [ i ] ) ) == False and ( isVowel ( s2 [ i ] ) == False ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT S1 , S2 = " abcgle " , " ezggli " NEW_LINE if ( checkPossibility ( S1 , S2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Generate a string consisting of characters ' a ' and ' b ' that satisfy the given conditions | Function to generate and print the required string ; More ' b ' , append " bba " ; More ' a ' , append " aab " ; Equal number of ' a ' and ' b ' append " ab " ; Driver code
def generateString ( A , B ) : NEW_LINE INDENT rt = " " NEW_LINE while ( 0 < A or 0 < B ) : NEW_LINE INDENT if ( A < B ) : NEW_LINE INDENT if ( 0 < B ) : NEW_LINE INDENT rt = rt + ' b ' NEW_LINE B -= 1 NEW_LINE DEDENT if ( 0 < B ) : NEW_LINE INDENT rt += ' b ' NEW_LINE B -= 1 NEW_LINE DEDENT if ( 0 < A ) : NEW_LINE INDENT rt += ' a ' NEW_LINE A -= 1 NEW_LINE DEDENT DEDENT elif ( B < A ) : NEW_LINE INDENT if ( 0 < A ) : NEW_LINE INDENT rt += ' a ' NEW_LINE A -= 1 NEW_LINE DEDENT if ( 0 < A ) : NEW_LINE INDENT rt += ' a ' NEW_LINE A -= 1 NEW_LINE DEDENT if ( 0 < B ) : NEW_LINE INDENT rt += ' b ' NEW_LINE B -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( 0 < A ) : NEW_LINE INDENT rt += ' a ' NEW_LINE A -= 1 NEW_LINE DEDENT if ( 0 < B ) : NEW_LINE INDENT rt += ' b ' NEW_LINE B -= 1 NEW_LINE DEDENT DEDENT DEDENT print ( rt ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 2 NEW_LINE B = 6 NEW_LINE generateString ( A , B ) NEW_LINE DEDENT
Number of strings that satisfy the given condition | Function to return the count of valid strings ; Set to store indices of valid strings ; Find the maximum digit for current position ; Add indices of all the strings in the set that contain maximal digit ; Return number of strings in the set ; Driver code
def countStrings ( n , m , s ) : NEW_LINE INDENT ind = dict ( ) NEW_LINE for j in range ( m ) : NEW_LINE INDENT mx = 0 NEW_LINE str1 = s [ j ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT mx = max ( mx , int ( str1 [ i ] ) ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if int ( str1 [ i ] ) == mx : NEW_LINE INDENT ind [ i ] = 1 NEW_LINE DEDENT DEDENT DEDENT return len ( ind ) NEW_LINE DEDENT s = [ "223" , "232" , "112" ] NEW_LINE m = len ( s [ 0 ] ) NEW_LINE n = len ( s ) NEW_LINE print ( countStrings ( n , m , s ) ) NEW_LINE
Lexicographically largest sub | Function to return the lexicographically largest sub - sequence of s ; Get the max character from the string ; Use all the occurrences of the current maximum character ; Repeat the steps for the remaining string ; Driver code
def getSubSeq ( s , n ) : NEW_LINE INDENT res = " " NEW_LINE cr = 0 NEW_LINE while ( cr < n ) : NEW_LINE INDENT mx = s [ cr ] NEW_LINE for i in range ( cr + 1 , n ) : NEW_LINE INDENT mx = max ( mx , s [ i ] ) NEW_LINE DEDENT lst = cr NEW_LINE for i in range ( cr , n ) : NEW_LINE INDENT if ( s [ i ] == mx ) : NEW_LINE INDENT res += s [ i ] NEW_LINE lst = i NEW_LINE DEDENT DEDENT cr = lst + 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE n = len ( s ) NEW_LINE print ( getSubSeq ( s , n ) ) NEW_LINE DEDENT
Validation of Equation Given as String | Function that returns true if the equation is valid ; If it is an integer then add it to another string array ; Evaluation of 1 st operator ; Evaluation of 2 nd operator ; Evaluation of 3 rd operator ; If the LHS result is equal to the RHS ; Driver code
def isValid ( string ) : NEW_LINE INDENT k = 0 ; NEW_LINE operands = [ " " ] * 5 ; NEW_LINE operators = [ " " ] * 4 ; NEW_LINE ans = 0 ; ans1 = 0 ; ans2 = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] != ' + ' and string [ i ] != ' = ' and string [ i ] != ' - ' ) : NEW_LINE INDENT operands [ k ] += string [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT operators [ k ] = string [ i ] ; NEW_LINE if ( k == 1 ) : NEW_LINE INDENT if ( operators [ k - 1 ] == ' + ' ) : NEW_LINE INDENT ans += int ( operands [ k - 1 ] ) + int ( operands [ k ] ) ; NEW_LINE DEDENT if ( operators [ k - 1 ] == ' - ' ) : NEW_LINE INDENT ans += int ( operands [ k - 1 ] ) - int ( operands [ k ] ) ; NEW_LINE DEDENT DEDENT if ( k == 2 ) : NEW_LINE INDENT if ( operators [ k - 1 ] == ' + ' ) : NEW_LINE INDENT ans1 += ans + int ( operands [ k ] ) ; NEW_LINE DEDENT if ( operators [ k - 1 ] == ' - ' ) : NEW_LINE INDENT ans1 -= ans - int ( operands [ k ] ) ; NEW_LINE DEDENT DEDENT if ( k == 3 ) : NEW_LINE INDENT if ( operators [ k - 1 ] == ' + ' ) : NEW_LINE INDENT ans2 += ans1 + int ( operands [ k ] ) ; NEW_LINE DEDENT if ( operators [ k - 1 ] == ' - ' ) : NEW_LINE INDENT ans2 -= ans1 - int ( operands [ k ] ) ; NEW_LINE DEDENT DEDENT k += 1 NEW_LINE DEDENT DEDENT if ( ans2 == int ( operands [ 4 ] ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "2 ▁ + ▁ 5 ▁ + ▁ 3 ▁ + ▁ 1 ▁ = ▁ 11" ; NEW_LINE if ( isValid ( string ) ) : NEW_LINE INDENT print ( " Valid " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) ; NEW_LINE DEDENT DEDENT
Count of sub | Function to return the count of sub - strings of str that are divisible by k ; Take all sub - strings starting from i ; If current sub - string is divisible by k ; Return the required count ; Driver code
def countSubStr ( str , l , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT n = 0 NEW_LINE for j in range ( i , l , 1 ) : NEW_LINE INDENT n = n * 10 + ( ord ( str [ j ] ) - ord ( '0' ) ) NEW_LINE if ( n % k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "33445" NEW_LINE l = len ( str ) NEW_LINE k = 11 NEW_LINE print ( countSubStr ( str , l , k ) ) NEW_LINE DEDENT
Find the resulting Colour Combination | Function to return Colour Combination ; Check for B * G = Y ; Check for B * Y = G ; Check for Y * G = B ; Driver Code
def Colour_Combination ( s ) : NEW_LINE INDENT temp = s [ 0 ] NEW_LINE for i in range ( 1 , len ( s ) , 1 ) : NEW_LINE INDENT if ( temp != s [ i ] ) : NEW_LINE INDENT if ( ( temp == ' B ' or temp == ' G ' ) and ( s [ i ] == ' G ' or s [ i ] == ' B ' ) ) : NEW_LINE INDENT temp = ' Y ' NEW_LINE DEDENT elif ( ( temp == ' B ' or temp == ' Y ' ) and ( s [ i ] == ' Y ' or s [ i ] == ' B ' ) ) : NEW_LINE INDENT temp = ' G ' NEW_LINE DEDENT else : NEW_LINE INDENT temp = ' B ' NEW_LINE DEDENT DEDENT DEDENT return temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " GBYGB " NEW_LINE print ( Colour_Combination ( s ) ) NEW_LINE DEDENT
Reverse Middle X Characters | Function to reverse the middle x characters in a str1ing ; Find the position from where the characters have to be reversed ; Print the first n characters ; Print the middle x characters in reverse ; Print the last n characters ; Driver code
def reverse ( str1 , x ) : NEW_LINE INDENT n = ( len ( str1 ) - x ) // 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( str1 [ i ] , end = " " ) NEW_LINE DEDENT for i in range ( n + x - 1 , n - 1 , - 1 ) : NEW_LINE INDENT print ( str1 [ i ] , end = " " ) NEW_LINE DEDENT for i in range ( n + x , len ( str1 ) ) : NEW_LINE INDENT print ( str1 [ i ] , end = " " ) NEW_LINE DEDENT DEDENT str1 = " geeksforgeeks " NEW_LINE x = 3 NEW_LINE reverse ( str1 , x ) NEW_LINE
Minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | Function to count numbers ; Count the number of ' a ' , ' b ' and ' c ' in string ; If equal previously ; If not a multiple of 3 ; Increase the number of a ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' b ' and c ; Check if it is ' b ' and it more than n / 3 ; Check if it is ' c ' and it more than n / 3 ; Increase the number of b ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' c ; Check if it is ' c ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of b 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' b ' and it more than n / 3 ; Driver Code
def lexoSmallest ( s , n ) : NEW_LINE INDENT ca = 0 NEW_LINE cb = 0 NEW_LINE cc = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT ca += 1 NEW_LINE DEDENT elif ( s [ i ] == ' b ' ) : NEW_LINE INDENT cb += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT DEDENT if ( ca == cb and cb == cc ) : NEW_LINE INDENT return s NEW_LINE DEDENT cnt = n // 3 NEW_LINE if ( cnt * 3 != n ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT i = 0 NEW_LINE while ( ca < cnt and i < n ) : NEW_LINE INDENT if ( s [ i ] == ' b ' and cb > cnt ) : NEW_LINE INDENT cb -= 1 NEW_LINE s [ i ] = ' a ' NEW_LINE ca += 1 NEW_LINE DEDENT elif ( s [ i ] == ' c ' and cc > cnt ) : NEW_LINE INDENT cc -= 1 NEW_LINE s [ i ] = ' a ' NEW_LINE ca += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT i = 0 NEW_LINE DEDENT ' NEW_LINE INDENT while ( cb < cnt and i < n ) : NEW_LINE INDENT if ( s [ i ] == ' c ' and cc > cnt ) : NEW_LINE INDENT cc -= 1 NEW_LINE s [ i ] = '1' NEW_LINE cb += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( cc < cnt and i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == ' a ' and ca > cnt ) : NEW_LINE INDENT ca -= 1 NEW_LINE s [ i ] = ' c ' NEW_LINE cc += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( cb < cnt and i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == ' a ' and ca > cnt ) : NEW_LINE INDENT ca -= 1 NEW_LINE s [ i ] = ' b ' NEW_LINE cb += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT i = n - 1 NEW_LINE while ( cc < cnt and i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == ' b ' and cb > cnt ) : NEW_LINE INDENT cb -= 1 NEW_LINE s [ i ] = ' c ' NEW_LINE cc += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT s = " aaaaaa " NEW_LINE n = len ( s ) NEW_LINE print ( * lexoSmallest ( list ( s ) , n ) , sep = " " ) NEW_LINE
Minimum moves to reach from i to j in a cyclic string | Function to return the count of steps required to move from i to j ; Starting from i + 1 ; Count of steps ; Current character ; If current character is different from previous ; Increment steps ; Update current character ; Return total steps ; Function to return the minimum number of steps required to reach j from i ; Swap the values so that i <= j ; Steps to go from i to j ( left to right ) ; While going from i to j ( right to left ) First go from i to 0 then from ( n - 1 ) to j ; If first and last character is different then it 'll add a step to stepsToLeft ; Return the minimum of two paths ; Driver code
def getSteps ( str , i , j , n ) : NEW_LINE INDENT k = i + 1 NEW_LINE steps = 0 NEW_LINE ch = str [ i ] NEW_LINE while ( k <= j ) : NEW_LINE INDENT if ( str [ k ] != ch ) : NEW_LINE INDENT steps = steps + 1 NEW_LINE ch = str [ k ] NEW_LINE DEDENT k = k + 1 NEW_LINE DEDENT return steps NEW_LINE DEDENT def getMinSteps ( str , i , j , n ) : NEW_LINE INDENT if ( j < i ) : NEW_LINE INDENT temp = i NEW_LINE i = j NEW_LINE j = temp NEW_LINE DEDENT stepsToRight = getSteps ( str , i , j , n ) NEW_LINE stepsToLeft = getSteps ( str , 0 , i , n ) + getSteps ( str , j , n - 1 , n ) NEW_LINE if ( str [ 0 ] != str [ n - 1 ] ) : NEW_LINE INDENT stepsToLeft = stepsToLeft + 1 NEW_LINE DEDENT return min ( stepsToLeft , stepsToRight ) NEW_LINE DEDENT str = " SSNSS " NEW_LINE n = len ( str ) NEW_LINE i = 0 NEW_LINE j = 3 NEW_LINE print ( getMinSteps ( str , i , j , n ) ) NEW_LINE
Count distinct substrings that contain some characters at most k times | Python3 implementation of the approach ; Function to return the count of valid sub - strings ; Store all characters of anotherStr in a direct index table for quick lookup . ; To store distinct output substrings ; Traverse through the given string and one by one generate substrings beginning from s [ i ] . ; One by one generate substrings ending with s [ j ] ; If character is illegal ; If current substring is valid ; If current substring is invalid , adding more characters would not help . ; Return the count of distinct sub - strings ; Driver code
MAX_CHAR = 256 NEW_LINE def countSubStrings ( s , anotherStr , k ) : NEW_LINE INDENT illegal = [ False ] * MAX_CHAR NEW_LINE for i in range ( len ( anotherStr ) ) : NEW_LINE INDENT illegal [ ord ( anotherStr [ i ] ) ] = True NEW_LINE DEDENT us = set ( ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ss = " " NEW_LINE count = 0 NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT if ( illegal [ ord ( s [ j ] ) ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT ss = ss + s [ j ] NEW_LINE if ( count <= k ) : NEW_LINE INDENT us . add ( ss ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return len ( us ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " acbacbacaa " NEW_LINE anotherStr = " abcdefghijklmnopqrstuvwxyz " NEW_LINE k = 2 NEW_LINE print ( countSubStrings ( string , anotherStr , k ) ) NEW_LINE DEDENT
Count pairs of parentheses sequences such that parentheses are balanced | Python3 program to count the number of pairs of balanced parentheses ; Function to count the number of pairs ; Hashing function to count the opening and closing brackets ; Traverse for all bracket sequences ; Get the string ; Counts the opening and closing required ; Traverse in the string ; If it is a opening bracket ; If openings are there , then close it ; else : Else increase count of closing ; If requirements of openings are there and no closing ; If requirements of closing are there and no opening ; Perfect ; Divide by two since two perfect makes one pair ; Traverse in the open and find corresponding minimum ; Driver Code
import math as mt NEW_LINE def countPairs ( bracks , num ) : NEW_LINE INDENT openn = dict ( ) NEW_LINE close = dict ( ) NEW_LINE cnt = 0 NEW_LINE for i in range ( num ) : NEW_LINE INDENT s = bracks [ i ] NEW_LINE l = len ( s ) NEW_LINE op , cl = 0 , 0 NEW_LINE for j in range ( l ) : NEW_LINE INDENT if ( s [ j ] == ' ( ' ) : NEW_LINE INDENT op += 1 NEW_LINE if ( op ) : NEW_LINE INDENT op -= 1 NEW_LINE cl += 1 NEW_LINE DEDENT DEDENT DEDENT if ( op and cl == 0 ) : NEW_LINE INDENT if op in openn . keys ( ) : NEW_LINE INDENT openn [ op ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT openn [ op ] = 1 NEW_LINE DEDENT DEDENT if ( cl and op == 0 ) : NEW_LINE INDENT if cl in openn . keys ( ) : NEW_LINE INDENT close [ cl ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT close [ cl ] = 1 NEW_LINE DEDENT DEDENT if ( op == 0 and cl == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT cnt = cnt // 2 NEW_LINE for it in openn : NEW_LINE INDENT cnt += min ( openn [ it ] , close [ it ] ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT bracks = [ " ) ( ) ) " , " ) " , " ( ( " , " ( ( " , " ( " , " ) " , " ) " ] NEW_LINE num = len ( bracks ) NEW_LINE print ( countPairs ( bracks , num ) ) NEW_LINE
Decrypt a string according to given rules | Function to return the original string after decryption ; Stores the decrypted string ; If length is odd ; Step counter ; Starting and ending index ; Iterate till all characters are decrypted ; Even step ; Odd step ; If length is even ; Step counter ; Starting and ending index ; Even step ; Odd step ; Reverse the decrypted string ; Driver Code
def decrypt ( s , l ) : NEW_LINE INDENT ans = " " NEW_LINE if ( l % 2 ) : NEW_LINE INDENT cnt = 0 NEW_LINE indl = 0 NEW_LINE indr = l - 1 NEW_LINE while ( len ( ans ) != l ) : NEW_LINE INDENT if ( cnt % 2 == 0 ) : NEW_LINE INDENT ans += s [ indl ] NEW_LINE indl += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += s [ indr ] NEW_LINE indr -= 1 NEW_LINE DEDENT cnt += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT cnt = 0 NEW_LINE indl = 0 NEW_LINE indr = l - 1 NEW_LINE while ( len ( ans ) != l ) : NEW_LINE INDENT if ( cnt % 2 == 0 ) : NEW_LINE INDENT ans += s [ indr ] NEW_LINE indr -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += s [ indl ] NEW_LINE indl += 1 NEW_LINE DEDENT cnt += 1 NEW_LINE DEDENT DEDENT string = list ( ans ) NEW_LINE string . reverse ( ) NEW_LINE ans = ' ' . join ( string ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " segosegekfrek " NEW_LINE l = len ( s ) NEW_LINE print ( decrypt ( s , l ) ) NEW_LINE DEDENT
Remove consecutive alphabets which are in same case | Function to return the modified string ; Traverse through the remaining characters in the string ; If the current and the previous characters are not in the same case then take the character ; Driver code
def removeChars ( s ) : NEW_LINE INDENT modifiedStr = " " NEW_LINE modifiedStr += s [ 0 ] NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] . isupper ( ) and s [ i - 1 ] . islower ( ) or s [ i ] . islower ( ) and s [ i - 1 ] . isupper ( ) ) : NEW_LINE INDENT modifiedStr += s [ i ] NEW_LINE DEDENT DEDENT return modifiedStr NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " GeeksForGeeks " NEW_LINE print ( removeChars ( s ) ) NEW_LINE DEDENT
Cost to make a string Panagram | Function to return the total cost required to make the string Pangram ; Mark all the alphabets that occurred in the string ; Calculate the total cost for the missing alphabets ; Driver Code
def pangramCost ( arr , string ) : NEW_LINE INDENT cost = 0 NEW_LINE occurred = [ False ] * 26 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT occurred [ ord ( string [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( not occurred [ i ] ) : NEW_LINE INDENT cost += arr [ i ] NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 ] NEW_LINE string = " abcdefghijklmopqrstuvwz " NEW_LINE print ( pangramCost ( arr , string ) ) NEW_LINE DEDENT
Recursive program to insert a star between pair of identical characters | Function to insert * at desired position ; Append current character ; If we reached last character ; If next character is same , append '* ; Driver code
def pairStar ( Input , Output , i = 0 ) : NEW_LINE INDENT Output = Output + Input [ i ] NEW_LINE if ( i == len ( Input ) - 1 ) : NEW_LINE INDENT print ( Output ) NEW_LINE return ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( Input [ i ] == Input [ i + 1 ] ) : NEW_LINE INDENT Output = Output + ' * ' ; NEW_LINE DEDENT pairStar ( Input , Output , i + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Input = " geeks " NEW_LINE Output = " " NEW_LINE pairStar ( Input , Output ) ; NEW_LINE DEDENT