text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Reduce Hamming distance by swapping two characters | Python 3 code to decrease hamming distance using swap . ; Function to return the swapped indexes to get minimum hamming distance . ; Find the initial hamming distance ; Case - I : To decrease distance by two ; ASCII values of present character . ; If two same letters appear in different positions print their indexes ; Store the index of letters which is in wrong position ; Case : II ; If misplaced letter is found , print its original index and its new index ; Store the index of letters in wrong position ; Case - III ; Driver code | MAX = 26 NEW_LINE def Swap ( s , t , n ) : NEW_LINE INDENT dp = [ [ - 1 for x in range ( MAX ) ] for y in range ( MAX ) ] NEW_LINE tot = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] != t [ i ] ) : NEW_LINE INDENT tot += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT a = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE b = ord ( t [ i ] ) - ord ( ' a ' ) NEW_LINE if ( a == b ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( dp [ a ] [ b ] != - 1 ) : NEW_LINE INDENT print ( i + 1 , " β " , dp [ a ] [ b ] + 1 ) NEW_LINE return NEW_LINE DEDENT dp [ b ] [ a ] = i NEW_LINE DEDENT A = [ - 1 ] * MAX NEW_LINE B = [ - 1 ] * MAX NEW_LINE for i in range ( n ) : NEW_LINE INDENT a = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE b = ord ( t [ i ] ) - ord ( ' a ' ) NEW_LINE if ( a == b ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( A [ b ] != - 1 ) : NEW_LINE INDENT print ( i + 1 , A [ b ] + 1 ) NEW_LINE return NEW_LINE DEDENT if ( B [ a ] != - 1 ) : NEW_LINE INDENT print ( i + 1 , B [ a ] + 1 ) NEW_LINE return NEW_LINE DEDENT A [ a ] = i NEW_LINE B [ b ] = i NEW_LINE DEDENT print ( " - 1" ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " permanent " NEW_LINE T = " pergament " NEW_LINE n = len ( S ) NEW_LINE if ( S == " " or T == " " ) : NEW_LINE INDENT print ( " Required β string β is β empty . " ) NEW_LINE DEDENT else : NEW_LINE INDENT Swap ( S , T , n ) NEW_LINE DEDENT DEDENT |
Convert string X to an anagram of string Y with minimum replacements | Python3 program to convert string X to string Y which minimum number of changes . ; Function that converts string X into lexicographically smallest anagram of string Y with minimal changes ; Counting frequency of characters in each string . ; We maintain two more counter arrays ctrx [ ] and ctry [ ] Ctrx [ ] maintains the count of extra elements present in string X than string Y Ctry [ ] maintains the count of characters missing from string X which should be present in string Y . ; This means that we cannot edit the current character as it 's frequency in string X is equal to or less than the frequency in string Y. Thus, we go to the next position ; Here , we try to find that character , which has more frequency in string Y and less in string X . We try to find this character in lexicographical order so that we get lexicographically smaller string ; This portion deals with the lexicographical property . Now , we put a character in string X when either this character has smaller value than the character present there right now or if this is the last position for it to exchange , else we fix the character already present here in this position . ; Driver Code | MAX = 26 NEW_LINE def printAnagramAndChanges ( x , y ) : NEW_LINE INDENT x = list ( x ) NEW_LINE y = list ( y ) NEW_LINE countx , county = [ 0 ] * MAX , [ 0 ] * MAX NEW_LINE ctrx , ctry = [ 0 ] * MAX , [ 0 ] * MAX NEW_LINE change = 0 NEW_LINE l = len ( x ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT countx [ ord ( x [ i ] ) - ord ( ' A ' ) ] += 1 NEW_LINE county [ ord ( y [ i ] ) - ord ( ' A ' ) ] += 1 NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if countx [ i ] > county [ i ] : NEW_LINE INDENT ctrx [ i ] += ( countx [ i ] - county [ i ] ) NEW_LINE DEDENT elif countx [ i ] < county [ i ] : NEW_LINE INDENT ctry [ i ] += ( county [ i ] - countx [ i ] ) NEW_LINE DEDENT change += abs ( county [ i ] - countx [ i ] ) NEW_LINE DEDENT for i in range ( l ) : NEW_LINE INDENT if ctrx [ ord ( x [ i ] ) - ord ( ' A ' ) ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT j = 0 NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT if ctry [ j ] > 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if countx [ ord ( x [ i ] ) - ord ( ' A ' ) ] == ctrx [ ord ( x [ i ] ) - ord ( ' A ' ) ] or ord ( x [ i ] ) - ord ( ' A ' ) > j : NEW_LINE INDENT countx [ ord ( x [ i ] ) - ord ( ' A ' ) ] -= 1 NEW_LINE ctrx [ ord ( x [ i ] ) - ord ( ' A ' ) ] -= 1 NEW_LINE ctry [ j ] -= 1 NEW_LINE x [ i ] = chr ( ord ( ' A ' ) + j ) NEW_LINE DEDENT else : NEW_LINE INDENT countx [ ord ( x [ i ] ) - ord ( ' A ' ) ] -= 1 NEW_LINE DEDENT DEDENT print ( " Anagram β : " , ' ' . join ( x ) ) NEW_LINE print ( " Number β of β changes β made β : " , change // 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = " CDBABC " NEW_LINE y = " ADCABD " NEW_LINE printAnagramAndChanges ( x , y ) NEW_LINE DEDENT |
Count number of equal pairs in a string | Python3 program to count the number of pairs ; Function to count the number of equal pairs ; Hash table ; Traverse the string and count occurrence ; Stores the answer ; Traverse and check the occurrence of every character ; Driver code | MAX = 256 NEW_LINE def countPairs ( s ) : NEW_LINE INDENT cnt = [ 0 for i in range ( 0 , MAX ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - 97 ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 0 , MAX ) : NEW_LINE INDENT ans += cnt [ i ] * cnt [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE print ( countPairs ( s ) ) NEW_LINE DEDENT |
Find a string in lexicographic order which is in between given two strings | Function to find the lexicographically next string ; Iterate from last character ; If not ' z ' , increase by one ; if ' z ' , change it to 'a ; Driver Code ; If not equal , print the resultant string | def lexNext ( s , n ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if s [ i ] != ' z ' : NEW_LINE INDENT k = ord ( s [ i ] ) NEW_LINE s [ i ] = chr ( k + 1 ) NEW_LINE return ' ' . join ( s ) NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT s [ i ] = ' a ' NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " abcdeg " NEW_LINE T = " abcfgh " NEW_LINE n = len ( S ) NEW_LINE S = list ( S ) NEW_LINE res = lexNext ( S , n ) NEW_LINE if res != T : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT |
Find the arrangement of queue at given time | prints the arrangement at time = t ; Checking the entire queue for every moment from time = 1 to time = t . ; If current index contains ' B ' and next index contains ' G ' then swap ; Driver code | def solve ( n , t , p ) : NEW_LINE INDENT s = list ( p ) NEW_LINE for i in range ( 0 , t ) : NEW_LINE INDENT for j in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( s [ j ] == ' B ' and s [ j + 1 ] == ' G ' ) : NEW_LINE INDENT temp = s [ j ] ; NEW_LINE s [ j ] = s [ j + 1 ] ; NEW_LINE s [ j + 1 ] = temp ; NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT DEDENT print ( ' ' . join ( s ) ) NEW_LINE DEDENT n = 6 NEW_LINE t = 2 NEW_LINE p = " BBGBBG " NEW_LINE solve ( n , t , p ) NEW_LINE |
Add two numbers represented by two arrays | Return sum of two number represented by the arrays . Size of a [ ] is greater than b [ ] . It is made sure be the wrapper function ; array to store sum . ; Until we reach beginning of array . we are comparing only for second array because we have already compare the size of array in wrapper function . ; find sum of corresponding element of both array . ; Finding carry for next sum . ; If second array size is less the first array size . ; Add carry to first array elements . ; If there is carry on adding 0 index elements . append 1 to total sum . ; Converting array into number . ; Wrapper Function ; Making first array which have greater number of element ; Driven Code | def calSumUtil ( a , b , n , m ) : NEW_LINE INDENT sum = [ 0 ] * n NEW_LINE i = n - 1 NEW_LINE j = m - 1 NEW_LINE k = n - 1 NEW_LINE carry = 0 NEW_LINE s = 0 NEW_LINE while j >= 0 : NEW_LINE INDENT s = a [ i ] + b [ j ] + carry NEW_LINE sum [ k ] = ( s % 10 ) NEW_LINE carry = s // 10 NEW_LINE k -= 1 NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT while i >= 0 : NEW_LINE INDENT s = a [ i ] + carry NEW_LINE sum [ k ] = ( s % 10 ) NEW_LINE carry = s // 10 NEW_LINE i -= 1 NEW_LINE k -= 1 NEW_LINE DEDENT ans = 0 NEW_LINE if carry : NEW_LINE INDENT ans = 10 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT ans += sum [ i ] NEW_LINE ans *= 10 NEW_LINE DEDENT return ans // 10 NEW_LINE DEDENT def calSum ( a , b , n , m ) : NEW_LINE INDENT if n >= m : NEW_LINE INDENT return calSumUtil ( a , b , n , m ) NEW_LINE DEDENT else : NEW_LINE INDENT return calSumUtil ( b , a , m , n ) NEW_LINE DEDENT DEDENT a = [ 9 , 3 , 9 ] NEW_LINE b = [ 6 , 1 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE print ( calSum ( a , b , n , m ) ) NEW_LINE |
Longest Common Anagram Subsequence | Python 3 implementation to find the length of the longest common anagram subsequence ; function to find the length of the longest common anagram subsequence ; List for storing frequencies of each character ; calculate frequency of each character of 'str1[] ; calculate frequency of each character of 'str2[] ; for each character add its minimum frequency out of the two strings in 'len ; required length ; Driver Code | SIZE = 26 NEW_LINE def longCommomAnagramSubseq ( str1 , str2 , n1 , n2 ) : NEW_LINE INDENT freq1 = [ 0 ] * SIZE NEW_LINE freq2 = [ 0 ] * SIZE NEW_LINE l = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( n1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( n2 ) : NEW_LINE INDENT freq2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( SIZE ) : NEW_LINE INDENT l += min ( freq1 [ i ] , freq2 [ i ] ) NEW_LINE DEDENT return l NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " abdacp " NEW_LINE str2 = " ckamb " NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE print ( " Length β = β " , longCommomAnagramSubseq ( str1 , str2 , n1 , n2 ) ) NEW_LINE DEDENT |
Panalphabetic window in a string | Return if given string contain panalphabetic window . ; traversing the string ; if character of string is equal to ch , increment ch . ; if all characters are found , return true . ; Driver Code | def isPanalphabeticWindow ( s , n ) : NEW_LINE INDENT ch = ' a ' NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == ch ) : NEW_LINE INDENT ch = chr ( ord ( ch ) + 1 ) NEW_LINE DEDENT if ( ch == ' z ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s = " abujm β zvcd β acefc β deghf β gijkle β m β n β o β p β pafqrstuvwxyzfap " NEW_LINE n = len ( s ) NEW_LINE if ( isPanalphabeticWindow ( s , n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Program to print characters present at prime indexes in a given string | Python3 program to print Characters at Prime index in a given String ; Corner case ; Check from 2 to n - 1 ; Function to print character at prime index ; Loop to check if index prime or not ; Driver Code | def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def prime_index ( input ) : NEW_LINE INDENT p = list ( input ) NEW_LINE s = " " NEW_LINE for i in range ( 2 , len ( p ) + 1 ) : NEW_LINE INDENT if isPrime ( i ) : NEW_LINE INDENT s = s + input [ i - 1 ] NEW_LINE DEDENT DEDENT print ( s ) NEW_LINE DEDENT input = " GeeksforGeeks " NEW_LINE prime_index ( input ) NEW_LINE |
Check whether a given string is Heterogram or not | Python3 code to check whether the given string is Heterogram or not . ; traversing the string . ; ignore the space ; if already encountered ; else return false . ; Driven Code | def isHeterogram ( s , n ) : NEW_LINE INDENT hash = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] != ' β ' : NEW_LINE INDENT if hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] == 0 : NEW_LINE INDENT hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT s = " the β big β dwarf β only β jumps " NEW_LINE n = len ( s ) NEW_LINE print ( " YES " if isHeterogram ( s , n ) else " NO " ) NEW_LINE |
Print given sentence into its equivalent ASCII form | Function to compute the ASCII value of each character one by one ; Driver code | def ASCIISentence ( str ) : NEW_LINE INDENT for i in str : NEW_LINE INDENT print ( ord ( i ) , end = ' ' ) NEW_LINE DEDENT print ( ' ' , β end β = β ' ' ) NEW_LINE DEDENT str = " GeeksforGeeks " NEW_LINE print ( " ASCII β Sentence : " ) NEW_LINE ASCIISentence ( str ) NEW_LINE |
Snake case of a given sentence | Function to replace spaces and convert into snake case ; Converting space to underscor ; If not space , convert into lower character ; Driver program ; Calling function | def convert ( string ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE string = list ( string ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( string [ i ] == ' β ' ) : NEW_LINE INDENT string [ i ] = ' _ ' ; NEW_LINE DEDENT else : NEW_LINE INDENT string [ i ] = string [ i ] . lower ( ) ; NEW_LINE DEDENT DEDENT string = " " . join ( string ) NEW_LINE print ( string ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " I β got β intern β at β geeksforgeeks " ; NEW_LINE convert ( string ) ; NEW_LINE DEDENT |
Find the size of largest subset of anagram words | Utility function to find size of largest subset of anagram ; sort the string ; Increment the count of string ; Compute the maximum size of string ; Driver code | def largestAnagramSet ( arr , n ) : NEW_LINE INDENT maxSize = 0 NEW_LINE count = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = ' ' . join ( sorted ( arr [ i ] ) ) NEW_LINE if arr [ i ] in count : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ arr [ i ] ] = 1 NEW_LINE DEDENT maxSize = max ( maxSize , count [ arr [ i ] ] ) NEW_LINE DEDENT return maxSize NEW_LINE DEDENT arr = [ " ant " , " magenta " , " magnate " , " tan " , " gnamate " ] NEW_LINE n = len ( arr ) NEW_LINE print ( largestAnagramSet ( arr , n ) ) NEW_LINE arr1 = [ " cars " , " bikes " , " arcs " , " steer " ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( largestAnagramSet ( arr1 , n ) ) NEW_LINE |
Program to count vowels , consonant , digits and special characters in string . | Function to count number of vowels , consonant , digits and special character in a string . ; Declare the variable vowels , consonant , digit and special characters ; str . length ( ) function to count number of character in given string . ; To handle upper case letters ; Driver function . | def countCharacterType ( str ) : NEW_LINE INDENT vowels = 0 NEW_LINE consonant = 0 NEW_LINE specialChar = 0 NEW_LINE digit = 0 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT ch = str [ i ] NEW_LINE if ( ( ch >= ' a ' and ch <= ' z ' ) or ( ch >= ' A ' and ch <= ' Z ' ) ) : NEW_LINE INDENT ch = ch . lower ( ) NEW_LINE if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT vowels += 1 NEW_LINE DEDENT else : NEW_LINE INDENT consonant += 1 NEW_LINE DEDENT DEDENT elif ( ch >= '0' and ch <= '9' ) : NEW_LINE INDENT digit += 1 NEW_LINE DEDENT else : NEW_LINE INDENT specialChar += 1 NEW_LINE DEDENT DEDENT print ( " Vowels : " , vowels ) NEW_LINE print ( " Consonant : " , consonant ) NEW_LINE print ( " Digit : " , digit ) NEW_LINE print ( " Special β Character : " , specialChar ) NEW_LINE DEDENT str = " geeks β for β geeks121" NEW_LINE countCharacterType ( str ) NEW_LINE |
Next word that does not contain a palindrome and has characters from first k | Function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ASCII value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th alphabet not in first k letters then make it as " a " and then increase ( i - 1 ) th letter ; to check whether formed string palindrome or not . ; increment i . ; if i less than or equals to one that means we not formed such word . ; Driver code | def findNextWord ( s , m ) : NEW_LINE INDENT m += 97 NEW_LINE n = len ( s ) NEW_LINE i = len ( s ) - 1 NEW_LINE s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE while i >= 0 and i <= n - 1 : NEW_LINE INDENT if ord ( s [ i ] ) >= m : NEW_LINE INDENT s [ i ] = ' a ' NEW_LINE i -= 1 NEW_LINE s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] or s [ i ] == s [ i - 2 ] : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT if i <= - 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ' . join ( s ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcd " NEW_LINE k = 4 NEW_LINE findNextWord ( list ( string ) , k ) NEW_LINE DEDENT |
Replace a character c1 with c2 and c2 with c1 in a string S | Python3 program to replace c1 with c2 and c2 with c1 ; loop to traverse in the string ; check for c1 and replace ; check for c2 and replace ; Driver Code | def replace ( s , c1 , c2 ) : NEW_LINE INDENT l = len ( s ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( s [ i ] == c1 ) : NEW_LINE INDENT s = s [ 0 : i ] + c2 + s [ i + 1 : ] NEW_LINE DEDENT elif ( s [ i ] == c2 ) : NEW_LINE INDENT s = s [ 0 : i ] + c1 + s [ i + 1 : ] NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " grrksfoegrrks " NEW_LINE c1 = ' e ' NEW_LINE c2 = ' r ' NEW_LINE print ( replace ( s , c1 , c2 ) ) NEW_LINE DEDENT |
Fibonacci Word | Returns n - th Fibonacci word ; driver program | def fibWord ( n ) : NEW_LINE INDENT Sn_1 = "0" NEW_LINE Sn = "01" NEW_LINE tmp = " " NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT tmp = Sn NEW_LINE Sn += Sn_1 NEW_LINE Sn_1 = tmp NEW_LINE DEDENT return Sn NEW_LINE DEDENT n = 6 NEW_LINE print ( fibWord ( n ) ) NEW_LINE |
Change string to a new character set | function for converting the string ; find the index of each element of the string in the modified set of alphabets replace the element with the one having the same index in the actual set of alphabets ; Driver Code | def conversion ( charSet , str1 ) : NEW_LINE INDENT s2 = " " NEW_LINE for i in str1 : NEW_LINE INDENT s2 += alphabets [ charSet . index ( i ) ] NEW_LINE DEDENT return s2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT alphabets = " abcdefghijklmnopqrstuvwxyz " NEW_LINE charSet = " qwertyuiopasdfghjklzxcvbnm " NEW_LINE str1 = " egrt " NEW_LINE print ( conversion ( charSet , str1 ) ) NEW_LINE DEDENT |
Different substrings in a string that start and end with given strings | function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; We use a hash to make sure that same substring is not counted twice . ; go through all the positions to find occurrence of " a " first . ; if we found occurrence of " a " . ; then go through all the positions to find occurrence of " b " . ; if we do found " b " at index j then add it to already existed substring . ; if we found occurrence of " b " . ; now add string " b " to already existed substring . ; If current substring is not included already . ; put any non negative integer to make this string as already existed . ; make substring null . ; return answer . ; Driver Code | def numberOfDifferentSubstrings ( s , a , b ) : NEW_LINE INDENT ans = 0 NEW_LINE ls = len ( s ) NEW_LINE la = len ( a ) NEW_LINE lb = len ( b ) NEW_LINE x = [ 0 ] * ls NEW_LINE y = [ 0 ] * ls NEW_LINE for i in range ( ls ) : NEW_LINE INDENT if ( s [ i : la + i ] == a ) : NEW_LINE INDENT x [ i ] = 1 NEW_LINE DEDENT if ( s [ i : lb + i ] == b ) : NEW_LINE INDENT y [ i ] = 1 NEW_LINE DEDENT DEDENT hash = [ ] NEW_LINE curr_substr = " " NEW_LINE for i in range ( ls ) : NEW_LINE INDENT if ( x [ i ] ) : NEW_LINE INDENT for j in range ( i , ls ) : NEW_LINE INDENT if ( not y [ j ] ) : NEW_LINE INDENT curr_substr += s [ j ] NEW_LINE DEDENT if ( y [ j ] ) : NEW_LINE INDENT curr_substr += s [ j : lb + j ] NEW_LINE if curr_substr not in hash : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT hash . append ( curr_substr ) NEW_LINE DEDENT DEDENT curr_substr = " " NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " codecppforfood " NEW_LINE begin = " c " NEW_LINE end = " d " NEW_LINE print ( numberOfDifferentSubstrings ( s , begin , end ) ) NEW_LINE DEDENT |
Printing string in plus β + β pattern in the matrix | Python 3 program to print the string in ' plus ' pattern ; Function to make a cross in the matrix ; As , it is not possible to make the cross exactly in the middle of the matrix with an even length string . ; declaring a 2D array i . e a matrix ; Now , we will fill all the elements of the array with 'X ; Now , we will place the characters of the string in the matrix , such that a cross is formed in it . ; here the characters of the string will be added in the middle column of our array . ; here the characters of the string will be added in the middle row of our array . ; Now finally , we will print the array ; Driver Code | max = 100 NEW_LINE def carveCross ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT print ( " Not β possible . β Please β enter β " , " odd length string . " ) NEW_LINE DEDENT else : NEW_LINE INDENT arr = [ [ False for x in range ( max ) ] for y in range ( max ) ] NEW_LINE m = n // 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT arr [ i ] [ j ] = ' X ' NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] [ m ] = str [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ m ] [ i ] = str [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " PICTURE " NEW_LINE carveCross ( str ) NEW_LINE DEDENT |
Binary String of given length that without a palindrome of size 3 | Python3 program find a binary String of given length that doesn 't contain a palindrome of size 3. ; Printing the character according to i ; Driver code | def generateString ( n ) : NEW_LINE INDENT s = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( i & 2 ) > 1 ) : NEW_LINE INDENT s += ' b ' ; NEW_LINE DEDENT else : NEW_LINE INDENT s += ' a ' ; NEW_LINE DEDENT DEDENT print ( s ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE generateString ( n ) ; NEW_LINE n = 8 ; NEW_LINE generateString ( n ) ; NEW_LINE n = 10 ; NEW_LINE generateString ( n ) ; NEW_LINE DEDENT |
Print all subsequences of a string | Iterative Method | function to find subsequence ; check if jth bit in binary is 1 ; if jth bit is 1 , include it in subsequence ; function to print all subsequences ; map to store subsequence lexicographically by length ; Total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; subsequence for binary pattern i ; storing sub in map ; it . first is length of Subsequence it . second is set < string > ; ii is iterator of type set < string > ; Driver Code | def subsequence ( s , binary , length ) : NEW_LINE INDENT sub = " " NEW_LINE for j in range ( length ) : NEW_LINE INDENT if ( binary & ( 1 << j ) ) : NEW_LINE INDENT sub += s [ j ] NEW_LINE DEDENT DEDENT return sub NEW_LINE DEDENT def possibleSubsequences ( s ) : NEW_LINE INDENT sorted_subsequence = { } NEW_LINE length = len ( s ) NEW_LINE limit = 2 ** length NEW_LINE for i in range ( 1 , limit ) : NEW_LINE INDENT sub = subsequence ( s , i , length ) NEW_LINE if len ( sub ) in sorted_subsequence . keys ( ) : NEW_LINE INDENT sorted_subsequence [ len ( sub ) ] = tuple ( list ( sorted_subsequence [ len ( sub ) ] ) + [ sub ] ) NEW_LINE DEDENT else : NEW_LINE INDENT sorted_subsequence [ len ( sub ) ] = [ sub ] NEW_LINE DEDENT DEDENT for it in sorted_subsequence : NEW_LINE INDENT print ( " Subsequences β of β length β = " , it , " are : " ) NEW_LINE for ii in sorted ( set ( sorted_subsequence [ it ] ) ) : NEW_LINE INDENT print ( ii , end = ' β ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT s = " aabc " NEW_LINE possibleSubsequences ( s ) NEW_LINE |
Print all subsequences of a string | Iterative Method | Python3 program to print all Subsequences of a string in an iterative manner ; function to find subsequence ; loop while binary is greater than ; get the position of rightmost set bit ; append at beginning as we are going from LSB to MSB ; resets bit at pos in binary ; function to print all subsequences ; map to store subsequence lexicographically by length ; Total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; subsequence for binary pattern i ; storing sub in map ; it . first is length of Subsequence it . second is set < string > ; ii is iterator of type set < string > ; Driver Code | from math import log2 , floor NEW_LINE def subsequence ( s , binary ) : NEW_LINE INDENT sub = " " NEW_LINE while ( binary > 0 ) : NEW_LINE INDENT pos = floor ( log2 ( binary & - binary ) + 1 ) NEW_LINE sub = s [ pos - 1 ] + sub NEW_LINE binary = ( binary & ~ ( 1 << ( pos - 1 ) ) ) NEW_LINE DEDENT sub = sub [ : : - 1 ] NEW_LINE return sub NEW_LINE DEDENT def possibleSubsequences ( s ) : NEW_LINE INDENT sorted_subsequence = { } NEW_LINE length = len ( s ) NEW_LINE limit = 2 ** length NEW_LINE for i in range ( 1 , limit ) : NEW_LINE INDENT sub = subsequence ( s , i ) NEW_LINE if len ( sub ) in sorted_subsequence . keys ( ) : NEW_LINE INDENT sorted_subsequence [ len ( sub ) ] = tuple ( list ( sorted_subsequence [ len ( sub ) ] ) + [ sub ] ) NEW_LINE DEDENT else : NEW_LINE INDENT sorted_subsequence [ len ( sub ) ] = [ sub ] NEW_LINE DEDENT DEDENT for it in sorted_subsequence : NEW_LINE INDENT print ( " Subsequences β of β length β = " , it , " are : " ) NEW_LINE for ii in sorted ( set ( sorted_subsequence [ it ] ) ) : NEW_LINE INDENT print ( ii , end = ' β ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT s = " aabc " NEW_LINE possibleSubsequences ( s ) NEW_LINE |
Program to find remainder when large number is divided by 11 | Function to return remainder ; len is variable to store the length of number string . ; loop that find remainder ; Driver code | def remainder ( st ) : NEW_LINE INDENT ln = len ( st ) NEW_LINE rem = 0 NEW_LINE for i in range ( 0 , ln ) : NEW_LINE INDENT num = rem * 10 + ( int ) ( st [ i ] ) NEW_LINE rem = num % 11 NEW_LINE DEDENT return rem NEW_LINE DEDENT st = "3435346456547566345436457867978" NEW_LINE print ( remainder ( st ) ) NEW_LINE |
Longest subsequence of the form 0 * 1 * 0 * in a binary string | Returns length of the longest subsequence of the form 0 * 1 * 0 * ; Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ] ; string is made up of all 0 s or all 1 s ; Compute result using precomputed values ; Driver Code | def longestSubseq ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE pre_count_0 = [ 0 for i in range ( n + 2 ) ] NEW_LINE pre_count_1 = [ 0 for i in range ( n + 1 ) ] NEW_LINE post_count_0 = [ 0 for i in range ( n + 2 ) ] NEW_LINE pre_count_0 [ 0 ] = 0 NEW_LINE post_count_0 [ n + 1 ] = 0 NEW_LINE pre_count_1 [ 0 ] = 0 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT pre_count_0 [ j ] = pre_count_0 [ j - 1 ] NEW_LINE pre_count_1 [ j ] = pre_count_1 [ j - 1 ] NEW_LINE post_count_0 [ n - j + 1 ] = post_count_0 [ n - j + 2 ] NEW_LINE if ( s [ j - 1 ] == '0' ) : NEW_LINE INDENT pre_count_0 [ j ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT pre_count_1 [ j ] += 1 NEW_LINE DEDENT if ( s [ n - j ] == '0' ) : NEW_LINE INDENT post_count_0 [ n - j + 1 ] += 1 NEW_LINE DEDENT DEDENT if ( pre_count_0 [ n ] == n or pre_count_0 [ n ] == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 , 1 ) : NEW_LINE INDENT ans = max ( pre_count_0 [ i - 1 ] + pre_count_1 [ j ] - pre_count_1 [ i - 1 ] + post_count_0 [ j + 1 ] , ans ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "000011100000" NEW_LINE print ( longestSubseq ( s ) ) NEW_LINE DEDENT |
Distinct permutations of the string | Set 2 | Returns true if str [ curr ] does not matches with any of the characters after str [ start ] ; Prints all distinct permutations in str [ 0. . n - 1 ] ; Proceed further for str [ i ] only if it doesn 't match with any of the characters after str[index] ; Driver code | def shouldSwap ( string , start , curr ) : NEW_LINE INDENT for i in range ( start , curr ) : NEW_LINE INDENT if string [ i ] == string [ curr ] : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def findPermutations ( string , index , n ) : NEW_LINE INDENT if index >= n : NEW_LINE INDENT print ( ' ' . join ( string ) ) NEW_LINE return NEW_LINE DEDENT for i in range ( index , n ) : NEW_LINE INDENT check = shouldSwap ( string , index , i ) NEW_LINE if check : NEW_LINE INDENT string [ index ] , string [ i ] = string [ i ] , string [ index ] NEW_LINE findPermutations ( string , index + 1 , n ) NEW_LINE string [ index ] , string [ i ] = string [ i ] , string [ index ] NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = list ( " ABCA " ) NEW_LINE n = len ( string ) NEW_LINE findPermutations ( string , 0 , n ) NEW_LINE DEDENT |
Generate permutations with only adjacent swaps allowed | Python3 program to generate permutations with only one swap allowed . ; don 't swap the current position ; Swap with the next character and revert the changes . As explained above , swapping with previous is is not needed as it anyways happens for next character . ; Driver Code | def findPermutations ( string , index , n ) : NEW_LINE INDENT if index >= n or ( index + 1 ) >= n : NEW_LINE INDENT print ( ' ' . join ( string ) ) NEW_LINE return NEW_LINE DEDENT findPermutations ( string , index + 1 , n ) NEW_LINE string [ index ] , string [ index + 1 ] = string [ index + 1 ] , string [ index ] NEW_LINE findPermutations ( string , index + 2 , n ) NEW_LINE string [ index ] , string [ index + 1 ] = string [ index + 1 ] , string [ index ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = list ( "12345" ) NEW_LINE n = len ( string ) NEW_LINE findPermutations ( string , 0 , n ) NEW_LINE DEDENT |
Decode a median string to the original string | function to calculate the median back string ; length of string ; initialize a blank string ; Flag to check if length is even or odd ; traverse from first to last ; if len is even then add first character to beginning of new string and second character to end ; if current length is odd and is greater than 1 ; add first character to end and second character to beginning ; if length is 1 , add character to end ; Driver Code | def decodeMedianString ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE s1 = " " NEW_LINE if ( l % 2 == 0 ) : NEW_LINE INDENT isEven = True NEW_LINE DEDENT else : NEW_LINE INDENT isEven = False NEW_LINE DEDENT for i in range ( 0 , l , 2 ) : NEW_LINE INDENT if ( isEven ) : NEW_LINE INDENT s1 = s [ i ] + s1 NEW_LINE s1 += s [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT if ( l - i > 1 ) : NEW_LINE INDENT s1 += s [ i ] NEW_LINE s1 = s [ i + 1 ] + s1 NEW_LINE DEDENT else : NEW_LINE INDENT s1 += s [ i ] NEW_LINE DEDENT DEDENT DEDENT return s1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " eekgs " NEW_LINE print ( decodeMedianString ( s ) ) NEW_LINE DEDENT |
Maximum number of characters between any two same character in a string | Simple Python3 program to find maximum number of characters between two occurrences of same character ; Driver code | def maximumChars ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = - 1 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT res = max ( res , abs ( j - i - 1 ) ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " abba " NEW_LINE print ( maximumChars ( str ) ) NEW_LINE DEDENT |
Maximum number of characters between any two same character in a string | Efficient Python3 program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ) . ; Driver code | MAX_CHAR = 256 NEW_LINE def maximumChars ( str1 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = - 1 NEW_LINE firstInd = [ - 1 for i in range ( MAX_CHAR ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT first_ind = firstInd [ ord ( str1 [ i ] ) ] NEW_LINE if ( first_ind == - 1 ) : NEW_LINE INDENT firstInd [ ord ( str1 [ i ] ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( res , abs ( i - first_ind - 1 ) ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT str1 = " abba " NEW_LINE print ( maximumChars ( str1 ) ) NEW_LINE |
Check if an encoding represents a unique binary string | Python 3 program to check if given encoding represents a single string . ; Return true if sum becomes k ; Driver Code | def isUnique ( a , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT sum += n - 1 NEW_LINE return ( sum == k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 3 , 3 , 3 ] NEW_LINE n = len ( a ) NEW_LINE k = 12 NEW_LINE if ( isUnique ( a , n , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Lexicographically next string | Python 3 program to find lexicographically next string ; If string is empty . ; Find first character from right which is not z . ; If all characters are ' z ' , append an ' a ' at the end . ; If there are some non - z characters ; Driver code | def nextWord ( s ) : NEW_LINE INDENT if ( s == " β " ) : NEW_LINE INDENT return " a " NEW_LINE DEDENT i = len ( s ) - 1 NEW_LINE while ( s [ i ] == ' z ' and i >= 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT s = s + ' a ' NEW_LINE DEDENT else : NEW_LINE INDENT s = s . replace ( s [ i ] , chr ( ord ( s [ i ] ) + 1 ) , 1 ) NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " samez " NEW_LINE print ( nextWord ( str ) ) NEW_LINE DEDENT |
Length of the longest substring with equal 1 s and 0 s | Function to check if a contains equal number of one and zeros or not ; Function to find the length of the longest balanced substring ; Driver code ; Function call | def isValid ( p ) : NEW_LINE INDENT n = len ( p ) NEW_LINE c1 = 0 NEW_LINE c0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] == '0' ) : NEW_LINE INDENT c0 += 1 NEW_LINE DEDENT if ( p [ i ] == '1' ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT DEDENT if ( c0 == c1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def longestSub ( s ) : NEW_LINE INDENT max_len = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( isValid ( s [ i : j - i + 1 ] ) and max_len < j - i + 1 ) : NEW_LINE INDENT max_len = j - i + 1 NEW_LINE DEDENT DEDENT DEDENT return max_len NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "101001000" NEW_LINE print ( longestSub ( s ) ) NEW_LINE DEDENT |
Common characters in n strings | Python3 Program to find all the common characters in n strings ; primary array for common characters we assume all characters are seen before . ; for each strings ; secondary array for common characters Initially marked false ; for every character of ith strings ; if character is present in all strings before , mark it . ; copy whole secondary array into primary ; displaying common characters ; Driver 's Code | MAX_CHAR = 26 NEW_LINE def commonCharacters ( strings , n ) : NEW_LINE INDENT prim = [ True ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT sec = [ False ] * MAX_CHAR NEW_LINE for j in range ( len ( strings [ i ] ) ) : NEW_LINE INDENT if ( prim [ ord ( strings [ i ] [ j ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT sec [ ord ( strings [ i ] [ j ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT DEDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT prim [ i ] = sec [ i ] NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( prim [ i ] ) : NEW_LINE INDENT print ( " % c β " % ( i + ord ( ' a ' ) ) , end = " " ) NEW_LINE DEDENT DEDENT DEDENT strings = [ " geeksforgeeks " , " gemkstones " , " acknowledges " , " aguelikes " ] NEW_LINE n = len ( strings ) NEW_LINE commonCharacters ( strings , n ) NEW_LINE |
Number of positions where a letter can be inserted such that a string becomes palindrome | Function to check if the string is palindrome ; to know the length of string ; if the given string is a palindrome ( Case - I ) ; Sub - case - III ) ; if ( n % 2 == 0 ) : if the length is even ; count = 2 * count + 1 sub - case - I ; count = 2 * count + 2 sub - case - II ; insertion point ; Case - I ; Case - II ; Driver code | def isPalindrome ( s , i , j ) : NEW_LINE INDENT p = j NEW_LINE for k in range ( i , p + 1 ) : NEW_LINE INDENT if ( s [ k ] != s [ p ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT p -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def countWays ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE count = 0 NEW_LINE if ( isPalindrome ( s , 0 , n - 1 ) ) : NEW_LINE INDENT for i in range ( n // 2 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE DEDENT else : NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n // 2 ) : NEW_LINE INDENT if ( s [ i ] != s [ n - 1 - i ] ) : NEW_LINE INDENT j = n - 1 - i NEW_LINE if ( isPalindrome ( s , i , n - 2 - i ) ) : NEW_LINE INDENT for k in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ k ] != s [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE DEDENT count += 1 NEW_LINE DEDENT if ( isPalindrome ( s , i + 1 , n - 1 - i ) ) : NEW_LINE INDENT for k in range ( n - i , n ) : NEW_LINE INDENT if ( s [ k ] != s [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE DEDENT count += 1 NEW_LINE DEDENT break NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abca " NEW_LINE print ( countWays ( s ) ) NEW_LINE DEDENT |
Count of substrings of a binary string containing K ones | method returns total number of substring having K ones ; initialize index having zero sum as 1 ; loop over binary characters of string ; update countOfOne variable with value of ith character ; if value reaches more than K , then update result ; add frequency of indices , having sum ( current sum - K ) , to the result ; update frequency of one 's count ; Driver code | def countOfSubstringWithKOnes ( s , K ) : NEW_LINE INDENT N = len ( s ) NEW_LINE res = 0 NEW_LINE countOfOne = 0 NEW_LINE freq = [ 0 for i in range ( N + 1 ) ] NEW_LINE freq [ 0 ] = 1 NEW_LINE for i in range ( 0 , N , 1 ) : NEW_LINE INDENT countOfOne += ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( countOfOne >= K ) : NEW_LINE INDENT res += freq [ countOfOne - K ] NEW_LINE DEDENT freq [ countOfOne ] += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "10010" NEW_LINE K = 1 NEW_LINE print ( countOfSubstringWithKOnes ( s , K ) ) NEW_LINE DEDENT |
Generate two output strings depending upon occurrence of character in input string . | Python3 program to print two strings made of character occurring once and multiple times ; function to print two strings generated from single string one with characters occurring onces other with character occurring multiple of times ; initialize hashtable with zero entry ; perform hashing for input string ; generate string ( str1 ) consisting char occurring once and string ( str2 ) consisting char occurring multiple times ; print both strings ; Driver Code | MAX_CHAR = 256 NEW_LINE def printDuo ( string ) : NEW_LINE INDENT countChar = [ 0 for i in range ( MAX_CHAR ) ] NEW_LINE n = len ( string ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT countChar [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT str1 = " " NEW_LINE str2 = " " NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( countChar [ i ] > 1 ) : NEW_LINE INDENT str2 = str2 + chr ( i + ord ( ' a ' ) ) NEW_LINE DEDENT elif ( countChar [ i ] == 1 ) : NEW_LINE INDENT str1 = str1 + chr ( i + ord ( ' a ' ) ) NEW_LINE DEDENT DEDENT print ( " String β with β characters β occurring β once : " , " " , str1 ) NEW_LINE print ( " String β with β characters β occurring " , " multiple β times : " , " " , str2 ) NEW_LINE DEDENT string = " lovetocode " NEW_LINE printDuo ( string ) NEW_LINE |
Next higher palindromic number using the same set of digits | function to reverse the digits in the range i to j in 'num ; function to find next higher palindromic number using the same set of digits ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in the 1 st half of 'num ; Start from the ( mid - 1 ) th digit and find the first digit that is smaller than the digit next to it . ; If no such digit is found , then all digits are in descending order which means there cannot be a greater palindromic number with same set of digits ; Find the smallest digit on right side of ith digit which is greater than num [ i ] up to index 'mid ; swap num [ i ] with num [ smallest ] ; as the number is a palindrome , the same swap of digits should be performed in the 2 nd half of 'num ; reverse digits in the range ( i + 1 ) to mid ; if n is even , then reverse digits in the range mid + 1 to n - i - 2 ; else if n is odd , then reverse digits in the range mid + 2 to n - i - 2 ; required next higher palindromic number ; Driver Code | ' NEW_LINE def reverse ( num , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT temp = num [ i ] NEW_LINE num [ i ] = num [ j ] NEW_LINE num [ j ] = temp NEW_LINE i = i + 1 NEW_LINE j = j - 1 NEW_LINE DEDENT DEDENT def nextPalin ( num , n ) : NEW_LINE INDENT if ( n <= 3 ) : NEW_LINE INDENT print " Not β Possible " NEW_LINE return NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT mid = n / 2 - 1 NEW_LINE i = mid - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( num [ i ] < num [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i = i - 1 NEW_LINE DEDENT if ( i < 0 ) : NEW_LINE INDENT print " Not β Possible " NEW_LINE return NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT smallest = i + 1 NEW_LINE j = i + 2 NEW_LINE while j <= mid : NEW_LINE INDENT if ( num [ j ] > num [ i ] and num [ j ] < num [ smallest ] ) : NEW_LINE INDENT smallest = j NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT temp = num [ i ] NEW_LINE num [ i ] = num [ smallest ] NEW_LINE num [ smallest ] = temp NEW_LINE DEDENT ' NEW_LINE INDENT temp = num [ n - i - 1 ] NEW_LINE num [ n - i - 1 ] = num [ n - smallest - 1 ] NEW_LINE num [ n - smallest - 1 ] = temp NEW_LINE reverse ( num , i + 1 , mid ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT reverse ( num , mid + 1 , n - i - 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT reverse ( num , mid + 2 , n - i - 2 ) NEW_LINE DEDENT result = ' ' . join ( num ) NEW_LINE print " Next β Palindrome : β " , result NEW_LINE DEDENT st = "4697557964" NEW_LINE num = list ( st ) NEW_LINE n = len ( st ) NEW_LINE nextPalin ( num , n ) NEW_LINE |
Print N | function to generate n digit numbers ; if number generated ; Append 1 at the current number and reduce the remaining places by one ; If more ones than zeros , append 0 to the current number and reduce the remaining places by one ; Driver Code ; Function call | def printRec ( number , extraOnes , remainingPlaces ) : NEW_LINE INDENT if ( 0 == remainingPlaces ) : NEW_LINE INDENT print ( number , end = " β " ) NEW_LINE return NEW_LINE DEDENT printRec ( number + "1" , extraOnes + 1 , remainingPlaces - 1 ) NEW_LINE if ( 0 < extraOnes ) : NEW_LINE INDENT printRec ( number + "0" , extraOnes - 1 , remainingPlaces - 1 ) NEW_LINE DEDENT DEDENT def printNums ( n ) : NEW_LINE INDENT str = " " NEW_LINE printRec ( str , 0 , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE printNums ( n ) NEW_LINE DEDENT |
Longest Common Substring in an Array of Strings | function to find the stem ( longestcommon substring ) from the string array ; Determine size of the array ; Take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; Check if the generated stem is common to all words ; If current substring is present in all strings and its length is greater than current result ; Driver Code ; Function call | def findstem ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE s = arr [ 0 ] NEW_LINE l = len ( s ) NEW_LINE res = " " NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( i + 1 , l + 1 ) : NEW_LINE INDENT stem = s [ i : j ] NEW_LINE k = 1 NEW_LINE for k in range ( 1 , n ) : NEW_LINE INDENT if stem not in arr [ k ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( k + 1 == n and len ( res ) < len ( stem ) ) : NEW_LINE INDENT res = stem NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " grace " , " graceful " , " disgraceful " , " gracefully " ] NEW_LINE stems = findstem ( arr ) NEW_LINE print ( stems ) NEW_LINE DEDENT |
Make a string from another by deletion and rearrangement of characters | Python 3 program to find if it is possible to make a string from characters present in other string . ; Returns true if it is possible to make s1 from characters present in s2 . ; Count occurrences of all characters present in s2 . . ; For every character , present in s1 , reduce its count if count is more than 0. ; Driver code | MAX_CHAR = 256 NEW_LINE def isPossible ( s1 , s2 ) : NEW_LINE INDENT count = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( len ( s2 ) ) : NEW_LINE INDENT count [ ord ( s2 [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( count [ ord ( s1 [ i ] ) ] == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT count [ ord ( s1 [ i ] ) ] -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " GeeksforGeeks " NEW_LINE s2 = " rteksfoGrdsskGeggehes " NEW_LINE if ( isPossible ( s1 , s2 ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT |
Next higher number using atmost one swap operation | function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of rightmost digit which has a digit greater to it on its right side ; required digit found , store its ' index ' and break ; if no such digit is found which has a larger digit on its right side ; to store the index of the smallest digit greater than the digit at ' index ' and right to it ; finding the index of the smallest digit greater than the digit at ' index ' and right to it ; swapping the digits ; required number ; Driver program to test above | def nextHighUsingAtMostOneSwap ( st ) : NEW_LINE INDENT num = list ( st ) NEW_LINE l = len ( num ) NEW_LINE posRMax = l - 1 NEW_LINE index = - 1 NEW_LINE i = l - 2 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( num [ i ] >= num [ posRMax ] ) : NEW_LINE INDENT posRMax = i NEW_LINE DEDENT else : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT i = i - 1 NEW_LINE DEDENT if ( index == - 1 ) : NEW_LINE INDENT return " Not β Possible " NEW_LINE DEDENT greatSmallDgt = - 1 NEW_LINE i = l - 1 NEW_LINE while i > index : NEW_LINE INDENT if ( num [ i ] > num [ index ] ) : NEW_LINE INDENT if ( greatSmallDgt == - 1 ) : NEW_LINE INDENT greatSmallDgt = i NEW_LINE DEDENT elif ( num [ i ] <= num [ greatSmallDgt ] ) : NEW_LINE INDENT greatSmallDgt = i NEW_LINE DEDENT DEDENT i = i - 1 NEW_LINE DEDENT temp = num [ index ] NEW_LINE num [ index ] = num [ greatSmallDgt ] ; NEW_LINE num [ greatSmallDgt ] = temp ; NEW_LINE return ' ' . join ( num ) NEW_LINE DEDENT num = "218765" NEW_LINE print " Original β number : β " , num NEW_LINE print " Next β higher β number : β " , nextHighUsingAtMostOneSwap ( num ) NEW_LINE |
Longest substring of vowels | Python3 program to find the longest substring of vowels . ; Increment current count if s [ i ] is vowel ; check previous value is greater then or not ; 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 longestVowel ( s ) : NEW_LINE INDENT count , res = 0 , 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( res , count ) NEW_LINE count = 0 NEW_LINE DEDENT DEDENT return max ( res , count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " theeare " NEW_LINE print ( longestVowel ( s ) ) NEW_LINE DEDENT |
Number of substrings with count of each character as k | Python3 program to count number of substrings with counts of distinct characters as k . ; Returns true if all values in freq [ ] are either 0 or k . ; Returns count of substrings where frequency of every present character is k ; Pick a starting point ; Initialize all frequencies as 0 for this starting point ; One by one pick ending points ; Increment frequency of current char ; If frequency becomes more than k , we can 't have more substrings starting with i ; If frequency becomes k , then check other frequencies as well ; Driver Code | MAX_CHAR = 26 NEW_LINE def check ( freq , k ) : NEW_LINE INDENT for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT if ( freq [ i ] and freq [ i ] != k ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def substrings ( s , k ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT freq = [ 0 ] * MAX_CHAR NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT index = ord ( s [ j ] ) - ord ( ' a ' ) NEW_LINE freq [ index ] += 1 NEW_LINE if ( freq [ index ] > k ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( freq [ index ] == k and check ( freq , k ) == True ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabbcc " NEW_LINE k = 2 NEW_LINE print ( substrings ( s , k ) ) NEW_LINE s = " aabbc " ; NEW_LINE k = 2 ; NEW_LINE print ( substrings ( s , k ) ) NEW_LINE DEDENT |
Number of substrings with count of each character as k | | from collections import defaultdict NEW_LINE def have_same_frequency ( freq : defaultdict , k : int ) : NEW_LINE INDENT return all ( [ freq [ i ] == k or freq [ i ] == 0 for i in freq ] ) NEW_LINE DEDENT def count_substrings ( s : str , k : int ) -> int : NEW_LINE INDENT count = 0 NEW_LINE distinct = len ( set ( [ i for i in s ] ) ) NEW_LINE for length in range ( 1 , distinct + 1 ) : NEW_LINE INDENT window_length = length * k NEW_LINE freq = defaultdict ( int ) NEW_LINE window_start = 0 NEW_LINE window_end = window_start + window_length - 1 NEW_LINE for i in range ( window_start , min ( window_end + 1 , len ( s ) ) ) : NEW_LINE INDENT freq [ s [ i ] ] += 1 NEW_LINE DEDENT while window_end < len ( s ) : NEW_LINE INDENT if have_same_frequency ( freq , k ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT freq [ s [ window_start ] ] -= 1 NEW_LINE window_start += 1 NEW_LINE window_end += 1 NEW_LINE if window_end < len ( s ) : NEW_LINE INDENT freq [ s [ window_end ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " aabbcc " NEW_LINE k = 2 NEW_LINE print ( count_substrings ( s , k ) ) NEW_LINE s = " aabbc " NEW_LINE k = 2 NEW_LINE print ( count_substrings ( s , k ) ) NEW_LINE DEDENT |
Frequency of a string in an array of strings | Python3 program to count number of times a string appears in an array of strings ; To store number of times a string is present . It is 0 is string is not present ; function to insert a string into the Trie ; calculation ascii value ; If the given node is not already present in the Trie than create the new node ; Returns count of occurrences of s in Trie ; inserting in Trie ; searching the strings in Trie ; Driver code | MAX_CHAR = 26 NEW_LINE class Trie : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . cnt = 0 NEW_LINE self . node = [ None for i in range ( MAX_CHAR ) ] NEW_LINE DEDENT DEDENT def insert ( root , s ) : NEW_LINE INDENT temp = root NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( not root . node [ index ] ) : NEW_LINE INDENT root . node [ index ] = Trie ( ) NEW_LINE DEDENT root = root . node [ index ] NEW_LINE DEDENT root . cnt += 1 NEW_LINE return temp NEW_LINE DEDENT def search ( root , s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( not root . node [ index ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT root = root . node [ index ] NEW_LINE DEDENT return root . cnt NEW_LINE DEDENT def answerQueries ( arr , n , q , m ) : NEW_LINE INDENT root = Trie ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT root = insert ( root , arr [ i ] ) NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT print ( search ( root , q [ i ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " aba " , " baba " , " aba " , " xzxb " ] NEW_LINE n = len ( arr ) NEW_LINE q = [ " aba " , " xzxb " , " ab " ] NEW_LINE m = len ( q ) NEW_LINE answerQueries ( arr , n , q , m ) NEW_LINE DEDENT |
Longest subsequence where every character appears at | Python3 program to Find longest subsequence where every character appears at - least k times ; Count frequencies of all characters ; Traverse given string again and print all those characters whose frequency is more than or equal to k . ; Driver code | MAX_CHARS = 26 NEW_LINE def longestSubseqWithK ( str , k ) : NEW_LINE INDENT n = len ( str ) NEW_LINE freq = [ 0 ] * MAX_CHARS NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] >= k ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE k = 2 NEW_LINE longestSubseqWithK ( str , k ) NEW_LINE DEDENT |
Generating distinct subsequences of a given string in lexicographic order | Finds and stores result in st for a given string s . ; If current string is not already present . ; Traverse current string , one by one remove every character and recur . ; Driver Code | def generate ( st , s ) : NEW_LINE INDENT if len ( s ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT if s not in st : NEW_LINE INDENT st . add ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT t = list ( s ) . copy ( ) NEW_LINE t . remove ( s [ i ] ) NEW_LINE t = ' ' . join ( t ) NEW_LINE generate ( st , t ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " xyz " NEW_LINE st = set ( ) NEW_LINE generate ( st , s ) NEW_LINE for i in st : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT |
Recursive solution to count substrings with same first and last characters | Function to count substrings with same first and last characters ; base cases ; driver code | def countSubstrs ( str , i , j , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = ( countSubstrs ( str , i + 1 , j , n - 1 ) + countSubstrs ( str , i , j - 1 , n - 1 ) - countSubstrs ( str , i + 1 , j - 1 , n - 2 ) ) NEW_LINE if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT str = " abcab " NEW_LINE n = len ( str ) NEW_LINE print ( countSubstrs ( str , 0 , n - 1 , n ) ) NEW_LINE |
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Counts the no of manipulations required ; store the count of character ; iterate though the first String and update count ; iterate through the second string update char_count . if character is not found in char_count then increase count ; Driver code | def countManipulations ( s1 , s2 ) : NEW_LINE INDENT count = 0 NEW_LINE char_count = [ 0 ] * 26 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT char_count [ i ] = 0 NEW_LINE DEDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT char_count [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( s2 ) ) : NEW_LINE INDENT char_count [ ord ( s2 [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if char_count [ i ] != 0 : NEW_LINE INDENT count += abs ( char_count [ i ] ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " ddcf " NEW_LINE s2 = " cedk " NEW_LINE print ( countManipulations ( s1 , s2 ) ) NEW_LINE DEDENT |
Least number of manipulations needed to ensure two strings have identical characters | Python3 program to count least number of manipulations to have two strings set of same characters ; return the count of manipulations required ; count the number of different characters in both strings ; check the difference in characters by comparing count arrays ; Driver Code | MAX_CHAR = 26 NEW_LINE def leastCount ( s1 , s2 , n ) : NEW_LINE INDENT count1 = [ 0 ] * MAX_CHAR NEW_LINE count2 = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT count1 [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE count2 [ ord ( s2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( count1 [ i ] != 0 ) : NEW_LINE INDENT res += abs ( count1 [ i ] - count2 [ i ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " abc " NEW_LINE s2 = " cdd " NEW_LINE l = len ( s1 ) NEW_LINE res = leastCount ( s1 , s2 , l ) NEW_LINE print ( res ) NEW_LINE DEDENT |
Given two strings check which string makes a palindrome first | Given two strings , check which string makes palindrome first . ; returns winner of two strings ; Count frequencies of characters in both given strings ; Check if there is a character that appears more than once in A and does not appear in B ; Driver Code | MAX_CHAR = 26 NEW_LINE def stringPalindrome ( A , B ) : NEW_LINE INDENT countA = [ 0 ] * MAX_CHAR NEW_LINE countB = [ 0 ] * MAX_CHAR NEW_LINE l1 = len ( A ) NEW_LINE l2 = len ( B ) NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT countA [ ord ( A [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT countB [ ord ( B [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( ( countA [ i ] > 1 and countB [ i ] == 0 ) ) : NEW_LINE INDENT return ' A ' NEW_LINE DEDENT DEDENT return ' B ' NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = " abcdea " NEW_LINE b = " bcdesg " NEW_LINE print ( stringPalindrome ( a , b ) ) NEW_LINE DEDENT |
Print the longest common substring | function to find and print the longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of longest common suffix of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] . The first row and first column entries have no logical meaning , they are used only for simplicity of program ; To store length of the longest common substring ; To store the index of the cell which contains the maximum value . This cell 's index helps in building up the longest common substring from right to left. ; Following steps build LCSuff [ m + 1 ] [ n + 1 ] in bottom up fashion . ; if true , then no common substring exists ; allocate space for the longest common substring ; traverse up diagonally form the ( row , col ) cell until LCSuff [ row ] [ col ] != 0 ; move diagonally up to previous cell ; required longest common substring ; Driver Code | def printLCSSubStr ( X : str , Y : str , m : int , n : int ) : NEW_LINE INDENT LCSuff = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE length = 0 NEW_LINE row , col = 0 , 0 NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if i == 0 or j == 0 : NEW_LINE INDENT LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT elif X [ i - 1 ] == Y [ j - 1 ] : NEW_LINE INDENT LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 NEW_LINE if length < LCSuff [ i ] [ j ] : NEW_LINE INDENT length = LCSuff [ i ] [ j ] NEW_LINE row = i NEW_LINE col = j NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT if length == 0 : NEW_LINE INDENT print ( " No β Common β Substring " ) NEW_LINE return NEW_LINE DEDENT resultStr = [ '0' ] * length NEW_LINE while LCSuff [ row ] [ col ] != 0 : NEW_LINE INDENT length -= 1 NEW_LINE row -= 1 NEW_LINE col -= 1 NEW_LINE DEDENT print ( ' ' . join ( resultStr ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " OldSite : GeeksforGeeks . org " NEW_LINE Y = " NewSite : GeeksQuiz . com " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE printLCSSubStr ( X , Y , m , n ) NEW_LINE DEDENT |
Convert all substrings of length ' k ' from base ' b ' to decimal | Simple Python3 program to convert all substrings from decimal to given base . ; Saving substring in sub ; Evaluating decimal for current substring and printing it . ; Driver code | import math NEW_LINE def substringConversions ( s , k , b ) : NEW_LINE INDENT l = len ( s ) ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( ( i + k ) < l + 1 ) : NEW_LINE INDENT sub = s [ i : i + k ] ; NEW_LINE sum , counter = 0 , 0 ; NEW_LINE for i in range ( len ( sub ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = sum + ( ( ord ( sub [ i ] ) - ord ( '0' ) ) * pow ( b , counter ) ) ; NEW_LINE counter += 1 ; NEW_LINE DEDENT print ( sum , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT s = "12212" ; NEW_LINE b , k = 3 , 3 ; NEW_LINE substringConversions ( s , b , k ) ; NEW_LINE |
Longest Possible Chunked Palindrome | Here curr_str is the string whose LCP is needed leng is length of string evaluated till now and s is original string ; If there is nothing at all ! ! ; If a single letter is left out ; For each length of substring chunk in string ; If left side chunk and right side chunk are same ; Call LCP for the part between the chunks and add 2 to the result . Length of string evaluated till now is increased by ( i + 1 ) * 2 ; Wrapper over LPCRec ( ) ; Driver code | def LPCRec ( curr_str , count , leng , s ) : NEW_LINE INDENT if not curr_str : NEW_LINE INDENT return 0 NEW_LINE DEDENT if len ( curr_str ) <= 1 : NEW_LINE INDENT if count != 0 and len ( s ) - leng <= 1 : NEW_LINE INDENT return ( count + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT n = len ( curr_str ) NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if ( curr_str [ 0 : i + 1 ] == curr_str [ n - 1 - i : n ] ) : NEW_LINE INDENT return LPCRec ( curr_str [ i + 1 : n - 1 - i ] , count + 2 , leng + ( i + 1 ) * 2 , s ) NEW_LINE DEDENT DEDENT return count + 1 NEW_LINE DEDENT def LPC ( s ) : NEW_LINE INDENT return LPCRec ( s , 0 , 0 , s ) NEW_LINE DEDENT print ( " V β : " , LPC ( " V " ) ) NEW_LINE print ( " VOLVO β : " , LPC ( " VOLVO " ) ) NEW_LINE print ( " VOLVOV β : " , LPC ( " VOLVOV " ) ) NEW_LINE print ( " ghiabcdefhelloadamhelloabcdefghi β : " , LPC ( " ghiabcdefhelloadamhelloabcdefghi " ) ) NEW_LINE print ( " ghiabcdefhelloadamhelloabcdefghik β : " , LPC ( " ghiabcdefhelloadamhelloabcdefghik " ) ) NEW_LINE print ( " antaprezatepzapreanta β : " , LPC ( " antaprezatepzapreanta " ) ) NEW_LINE |
Find numbers of balancing positions in string | Python3 program to find number of balancing points in string ; function to return number of balancing points ; hash array for storing hash of string initialized by 0 being global ; process string initially for rightVisited ; check for balancing points ; for every position inc left hash & dec rightVisited ; check whether both hash have same character or not ; Either both leftVisited [ j ] and rightVisited [ j ] should have none zero value or both should have zero value ; if both have same character increment count ; Driver Code | MAX_CHAR = 256 NEW_LINE def countBalance ( string ) : NEW_LINE INDENT leftVisited = [ 0 ] * ( MAX_CHAR ) NEW_LINE rightVisited = [ 0 ] * ( MAX_CHAR ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT rightVisited [ ord ( string [ i ] ) ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT leftVisited [ ord ( string [ i ] ) ] += 1 NEW_LINE rightVisited [ ord ( string [ i ] ) ] -= 1 NEW_LINE j = 0 NEW_LINE while j < MAX_CHAR : NEW_LINE INDENT if ( ( leftVisited [ j ] == 0 and rightVisited [ j ] != 0 ) or ( leftVisited [ j ] != 0 and rightVisited [ j ] == 0 ) ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == MAX_CHAR : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abaababa " NEW_LINE print ( countBalance ( string ) ) NEW_LINE DEDENT |
Min flips of continuous characters to make all characters same in a string | To find min number of flips in binary string ; If last character is not equal to str [ i ] increase res ; To return min flips ; Driver Code | def findFlips ( str , n ) : NEW_LINE INDENT last = ' β ' NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( last != str [ i ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT last = str [ i ] NEW_LINE DEDENT return res // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "00011110001110" NEW_LINE n = len ( str ) NEW_LINE print ( findFlips ( str , n ) ) NEW_LINE DEDENT |
Maximum length substring having all same characters after k changes | function to find the maximum length of substring having character ch ; traverse the whole string ; if character is not same as ch increase count ; While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same ; length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length ; function which returns maximum length of substring ; Driver Code | def findLen ( A , n , k , ch ) : NEW_LINE INDENT maxlen = 1 NEW_LINE cnt = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while r < n : NEW_LINE INDENT if A [ r ] != ch : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT while cnt > k : NEW_LINE INDENT if A [ l ] != ch : NEW_LINE INDENT cnt -= 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT maxlen = max ( maxlen , r - l + 1 ) NEW_LINE r += 1 NEW_LINE DEDENT return maxlen NEW_LINE DEDENT def answer ( A , n , k ) : NEW_LINE INDENT maxlen = 1 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT maxlen = max ( maxlen , findLen ( A , n , k , chr ( i + ord ( ' A ' ) ) ) ) NEW_LINE maxlen = max ( maxlen , findLen ( A , n , k , chr ( i + ord ( ' a ' ) ) ) ) NEW_LINE DEDENT return maxlen NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE A = " ABABA " NEW_LINE print ( " Maximum β length β = " , answer ( A , n , k ) ) NEW_LINE n = 6 NEW_LINE k = 4 NEW_LINE B = " HHHHHH " NEW_LINE print ( " Maximum β length β = " , answer ( B , n , k ) ) NEW_LINE DEDENT |
Given a sequence of words , print all anagrams together using STL | Python3 program for finding all anagram pairs in the given array ; Utility function for printing anagram list ; Utility function for storing the vector of strings into HashMap ; Check for sorted string if it already exists ; Push new string to already existing key ; Print utility function for printing all the anagrams ; Driver code ; Initialize vector of strings ; Utility function for storing strings into hashmap | from collections import defaultdict NEW_LINE def printAnagram ( store : dict ) -> None : NEW_LINE INDENT for ( k , v ) in store . items ( ) : NEW_LINE INDENT temp_vec = v NEW_LINE size = len ( temp_vec ) NEW_LINE if ( size > 1 ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( temp_vec [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT def storeInMap ( vec : list ) -> None : NEW_LINE INDENT store = defaultdict ( lambda : list ) NEW_LINE for i in range ( len ( vec ) ) : NEW_LINE INDENT tempString = vec [ i ] NEW_LINE tempString = ' ' . join ( sorted ( tempString ) ) NEW_LINE if ( tempString not in store ) : NEW_LINE INDENT temp_vec = [ ] NEW_LINE temp_vec . append ( vec [ i ] ) NEW_LINE store [ tempString ] = temp_vec NEW_LINE DEDENT else : NEW_LINE INDENT temp_vec = store [ tempString ] NEW_LINE temp_vec . append ( vec [ i ] ) NEW_LINE store [ tempString ] = temp_vec NEW_LINE DEDENT DEDENT printAnagram ( store ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ ] NEW_LINE arr . append ( " geeksquiz " ) NEW_LINE arr . append ( " geeksforgeeks " ) NEW_LINE arr . append ( " abcd " ) NEW_LINE arr . append ( " forgeeksgeeks " ) NEW_LINE arr . append ( " zuiqkeegs " ) NEW_LINE arr . append ( " cat " ) NEW_LINE arr . append ( " act " ) NEW_LINE arr . append ( " tca " ) NEW_LINE storeInMap ( arr ) NEW_LINE DEDENT |
Quick way to check if all the characters of a string are same | Function to check is all the characters in string are or not ; Insert characters in the set ; If all characters are same Size of set will always be 1 ; Driver code | def allCharactersSame ( s ) : NEW_LINE INDENT s1 = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT s1 . append ( s [ i ] ) NEW_LINE DEDENT s1 = list ( set ( s1 ) ) NEW_LINE if ( len ( s1 ) == 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT Str = " nnnn " NEW_LINE allCharactersSame ( Str ) NEW_LINE |
Check if both halves of the string have same set of characters | Python3 program to check if it is possible to split string or not ; Function to check if we can split string or not ; Counter array initialized with 0 ; Length of the string ; Traverse till the middle element is reached ; First half ; Second half ; Checking if values are different set flag to 1 ; String to be checked | MAX_CHAR = 26 NEW_LINE def checkCorrectOrNot ( s ) : NEW_LINE INDENT global MAX_CHAR NEW_LINE count1 = [ 0 ] * MAX_CHAR NEW_LINE count2 = [ 0 ] * MAX_CHAR NEW_LINE n = len ( s ) NEW_LINE if n == 1 : NEW_LINE INDENT return true NEW_LINE DEDENT i = 0 ; j = n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT count1 [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE count2 [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE i += 1 ; j -= 1 NEW_LINE DEDENT for i in range ( MAX_CHAR ) : NEW_LINE INDENT if count1 [ i ] != count2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = " ababc " NEW_LINE print ( " Yes " if checkCorrectOrNot ( s ) else " No " ) NEW_LINE |
Extract maximum numeric value from a given string | Set 1 ( General approach ) | Utility function to find maximum string ; If both having equal lengths ; Reach first unmatched character / value ; Return string with maximum value ; If different lengths return string with maximum length ; Function to extract the maximum value ; Start traversing the string ; Ignore leading zeroes ; Store numeric value into a string ; Update maximum string ; To handle the case if there is only 0 numeric value ; Return maximum string ; Driver Code | def maximumNum ( curr_num , res ) : NEW_LINE INDENT len1 = len ( curr_num ) ; NEW_LINE len2 = len ( res ) ; NEW_LINE if ( len1 == len2 ) : NEW_LINE INDENT i = 0 ; NEW_LINE while ( curr_num [ i ] == res [ i ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( curr_num [ i ] < res [ i ] ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT else : NEW_LINE INDENT return curr_num ; NEW_LINE DEDENT DEDENT return res if ( len1 < len2 ) else curr_num ; NEW_LINE DEDENT def extractMaximum ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE curr_num = " " ; NEW_LINE res = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( i < n and str [ i ] == '0' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT while ( i < n and str [ i ] >= '0' and str [ i ] <= '9' ) : NEW_LINE INDENT curr_num += str [ i ] ; NEW_LINE i += 1 ; NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( len ( curr_num ) > 0 ) : NEW_LINE INDENT i -= 1 ; NEW_LINE DEDENT res = maximumNum ( curr_num , res ) ; NEW_LINE curr_num = " " ; NEW_LINE DEDENT if ( len ( curr_num ) == 0 and len ( res ) == 0 ) : NEW_LINE INDENT res += '0' ; NEW_LINE DEDENT return maximumNum ( curr_num , res ) ; NEW_LINE DEDENT str = "100klh564abc365bg " ; NEW_LINE print ( extractMaximum ( str ) ) ; NEW_LINE |
To check divisibility of any large number by 999 | function to check divisibility ; Append required 0 s at the beginning . ; add digits in group of three in gSum ; group saves 3 - digit group ; calculate result till 3 digit sum ; Driver code | def isDivisible999 ( num ) : NEW_LINE INDENT n = len ( num ) ; NEW_LINE if ( n == 0 or num [ 0 ] == '0' ) : NEW_LINE INDENT return true NEW_LINE DEDENT if ( ( n % 3 ) == 1 ) : NEW_LINE INDENT num = "00" + num NEW_LINE DEDENT if ( ( n % 3 ) == 2 ) : NEW_LINE INDENT num = "0" + num NEW_LINE DEDENT gSum = 0 NEW_LINE for i in range ( 0 , n , 3 ) : NEW_LINE INDENT group = 0 NEW_LINE group += ( ord ( num [ i ] ) - 48 ) * 100 NEW_LINE group += ( ord ( num [ i + 1 ] ) - 48 ) * 10 NEW_LINE group += ( ord ( num [ i + 2 ] ) - 48 ) NEW_LINE gSum += group NEW_LINE DEDENT if ( gSum > 1000 ) : NEW_LINE INDENT num = str ( gSum ) NEW_LINE n = len ( num ) NEW_LINE gSum = isDivisible999 ( num ) NEW_LINE DEDENT return ( gSum == 999 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = "1998" NEW_LINE n = len ( num ) NEW_LINE if ( isDivisible999 ( num ) ) : NEW_LINE INDENT print ( " Divisible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β divisible " ) NEW_LINE DEDENT DEDENT |
Rearrange a string in sorted order followed by the integer sum | Python3 program for above implementation ; Function to return string in lexicographic order followed by integers sum ; Traverse the string ; Count occurrence of uppercase alphabets ; Store sum of integers ; Traverse for all characters A to Z ; Append the current character in the string no . of times it occurs in the given string ; Append the sum of integers ; return resultant string ; Driver code | MAX_CHAR = 26 NEW_LINE def arrangeString ( string ) : NEW_LINE INDENT char_count = [ 0 ] * MAX_CHAR NEW_LINE s = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if string [ i ] >= " A " and string [ i ] <= " Z " : NEW_LINE INDENT char_count [ ord ( string [ i ] ) - ord ( " A " ) ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT s += ord ( string [ i ] ) - ord ( "0" ) NEW_LINE DEDENT DEDENT res = " " NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT ch = chr ( ord ( " A " ) + i ) NEW_LINE while char_count [ i ] : NEW_LINE INDENT res += ch NEW_LINE char_count [ i ] -= 1 NEW_LINE DEDENT DEDENT if s > 0 : NEW_LINE INDENT res += str ( s ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ACCBA10D2EW30" NEW_LINE print ( arrangeString ( string ) ) NEW_LINE DEDENT |
URLify a given string ( Replace spaces is % 20 ) | Instantiate the string ; Trim the given string ; Replace All space ( unicode is \\ s ) to % 20 ; Display the result | s = " Mr β John β Smith β " NEW_LINE s = s . strip ( ) NEW_LINE s = s . replace ( ' β ' , " % 20" ) NEW_LINE print ( s ) NEW_LINE |
Program to print all substrings of a given string | Function to print all sub strings ; Pick starting point ; Pick ending point ; Print characters from current starting point to current ending point . ; Driver program to test above function | def subString ( Str , n ) : NEW_LINE INDENT for Len in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - Len + 1 ) : NEW_LINE INDENT j = i + Len - 1 NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT print ( Str [ k ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT Str = " abc " NEW_LINE subString ( Str , len ( Str ) ) NEW_LINE |
Reverse a string preserving space positions | Function to reverse the string and preserve the space position ; Mark spaces in result ; Traverse input string from beginning and put characters in result from end ; Ignore spaces in input string ; Ignore spaces in result . ; Driver code | def reverses ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE result = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == ' β ' ) : NEW_LINE INDENT result [ i ] = ' β ' NEW_LINE DEDENT DEDENT j = n - 1 NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT if ( st [ i ] != ' β ' ) : NEW_LINE INDENT if ( result [ j ] == ' β ' ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT result [ j ] = st [ i ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT return ' ' . join ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " internship β at β geeks β for β geeks " NEW_LINE print ( reverses ( st ) ) NEW_LINE DEDENT |
Find uncommon characters of the two strings | size of the hash table ; function to find the uncommon characters of the two strings ; mark presence of each character as 0 in the hash table 'present[] ; for each character of str1 , mark its presence as 1 in 'present[] ; for each character of str2 ; if a character of str2 is also present in str1 , then mark its presence as - 1 ; else mark its presence as 2 ; print all the uncommon characters ; Driver Code | MAX_CHAR = 26 NEW_LINE def findAndPrintUncommonChars ( str1 , str2 ) : NEW_LINE ' NEW_LINE INDENT present = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT present [ i ] = 0 NEW_LINE DEDENT l1 = len ( str1 ) NEW_LINE l2 = len ( str2 ) NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , l1 ) : NEW_LINE INDENT present [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] = 1 NEW_LINE DEDENT for i in range ( 0 , l2 ) : NEW_LINE INDENT if ( present [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] == 1 or present [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_LINE INDENT present [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT present [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] = 2 NEW_LINE DEDENT DEDENT for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT if ( present [ i ] == 1 or present [ i ] == 2 ) : NEW_LINE INDENT print ( chr ( i + ord ( ' a ' ) ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " characters " NEW_LINE str2 = " alphabets " NEW_LINE findAndPrintUncommonChars ( str1 , str2 ) NEW_LINE DEDENT |
Length Of Last Word in a String | Python3 program for implementation of simple approach to find length of last word ; String a is ' final ' -- can not be modified So , create a copy and trim the spaces from both sides ; Driver code | def lengthOfLastWord ( a ) : NEW_LINE INDENT l = 0 NEW_LINE x = a . strip ( ) NEW_LINE for i in range ( len ( x ) ) : NEW_LINE INDENT if x [ i ] == " β " : NEW_LINE INDENT l = 0 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT return l NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT inp = " Geeks β For β Geeks β " NEW_LINE print ( " The β length β of β last β word β is " , lengthOfLastWord ( inp ) ) NEW_LINE DEDENT |
Length Of Last Word in a String | Python3 program for implementation of efficient approach to find length of last word ; Split by space and converting String to list and ; Driver code | def length ( str ) : NEW_LINE INDENT lis = list ( str . split ( " β " ) ) NEW_LINE return len ( lis [ - 1 ] ) NEW_LINE DEDENT str = " Geeks β for β Geeks " NEW_LINE print ( " The β length β of β last β word β is " , length ( str ) ) NEW_LINE |
Program to count vowels in a string ( Iterative and Recursive ) | Function to check the Vowel ; Returns count of vowels in str ; Check for vowel ; string object ; Total number of Vowels | def isVowel ( ch ) : NEW_LINE INDENT return ch . upper ( ) in [ ' A ' , ' E ' , ' I ' , ' O ' , ' U ' ] NEW_LINE DEDENT def countVowels ( str ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if isVowel ( str [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT str = ' abc β de ' NEW_LINE print ( countVowels ( str ) ) NEW_LINE |
Toggle case of a string using Bitwise Operators | Python3 program to get toggle case of a string ; tOGGLE cASE = swaps CAPS to lower case and lower case to CAPS ; Bitwise EXOR with 32 ; Driver Code | x = 32 ; NEW_LINE def toggleCase ( a ) : NEW_LINE INDENT for i in range ( len ( a ) ) : NEW_LINE INDENT a = a [ : i ] + chr ( ord ( a [ i ] ) ^ 32 ) + a [ i + 1 : ] ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT str = " CheRrY " ; NEW_LINE print ( " Toggle β case : β " , end = " " ) ; NEW_LINE str = toggleCase ( str ) ; NEW_LINE print ( str ) ; NEW_LINE print ( " Original β string : β " , end = " " ) ; NEW_LINE str = toggleCase ( str ) ; NEW_LINE print ( str ) ; NEW_LINE |
Determine if a string has all Unique Characters | Python3 program to illustrate String with unique characters ; Converting string to set ; If length of set is equal to len of string then it will have unique characters ; Driver Code | def uniqueCharacters ( str ) : NEW_LINE INDENT setstring = set ( str ) NEW_LINE if ( len ( setstring ) == len ( str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = " GeeksforGeeks " NEW_LINE if ( uniqueCharacters ( input ) ) : NEW_LINE INDENT print ( " The β String β " + input + " β has β all β unique β characters " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The β String β " + input + " β has β duplicate β characters " ) NEW_LINE DEDENT DEDENT |
Ropes Data Structure ( Fast String Concatenation ) | Function that concatenates strings a [ 0. . n1 - 1 ] and b [ 0. . n2 - 1 ] and stores the result in c [ ] ; Copy characters of A [ ] to C [ ] ; Copy characters of B [ ] ; Driver Code ; Concatenate a [ ] and b [ ] and store result in c [ ] | def concatenate ( a , b , c , n1 , n2 ) : NEW_LINE INDENT i = - 1 NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT c [ i ] = a [ i ] NEW_LINE DEDENT for j in range ( n2 ) : NEW_LINE INDENT c [ i ] = b [ j ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = " Hi β This β is β geeksforgeeks . β " NEW_LINE n1 = len ( a ) NEW_LINE b = " You β are β welcome β here . " NEW_LINE n2 = len ( b ) NEW_LINE a = list ( a ) NEW_LINE b = list ( b ) NEW_LINE c = [ 0 ] * ( n1 + n2 - 1 ) NEW_LINE concatenate ( a , b , c , n1 , n2 ) NEW_LINE for i in c : NEW_LINE INDENT print ( i , end = " " ) NEW_LINE DEDENT DEDENT |
Binary representation of next greater number with same number of 1 ' s β and β 0' s | Function to find the next greater number with same number of 1 ' s β and β 0' s ; locate first ' i ' from end such that bnum [ i ] == '0' and bnum [ i + 1 ] == '1' swap these value and break ; if no swapping performed ; Since we want the smallest next value , shift all 1 ' s β at β the β end β in β the β binary β β substring β starting β from β index β ' i + 2 ; special case while swapping if '0' occurs then break ; required next greater number ; Driver code | def nextGreaterWithSameDigits ( bnum ) : NEW_LINE INDENT l = len ( bnum ) NEW_LINE bnum = list ( bnum ) NEW_LINE for i in range ( l - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( bnum [ i ] == '0' and bnum [ i + 1 ] == '1' ) : NEW_LINE INDENT ch = bnum [ i ] NEW_LINE bnum [ i ] = bnum [ i + 1 ] NEW_LINE bnum [ i + 1 ] = ch NEW_LINE break NEW_LINE DEDENT DEDENT if ( i == 0 ) : NEW_LINE INDENT return " no β greater β number " NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT j = i + 2 NEW_LINE k = l - 1 NEW_LINE while ( j < k ) : NEW_LINE INDENT if ( bnum [ j ] == '1' and bnum [ k ] == '0' ) : NEW_LINE INDENT ch = bnum [ j ] NEW_LINE bnum [ j ] = bnum [ k ] NEW_LINE bnum [ k ] = ch NEW_LINE j += 1 NEW_LINE k -= 1 NEW_LINE DEDENT elif ( bnum [ i ] == '0' ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT return bnum NEW_LINE DEDENT bnum = "10010" NEW_LINE print ( " Binary β representation β of β next β greater β number β = β " , * nextGreaterWithSameDigits ( bnum ) , sep = " " ) NEW_LINE |
Generate all rotations of a given string | Print all the rotated strings . ; Generate all rotations one by one and print ; Current index in str ; Current index in temp ; Copying the second part from the point of rotation . ; Copying the first part from the point of rotation . ; Driver Code | def printRotatedString ( str ) : NEW_LINE INDENT lenn = len ( str ) NEW_LINE temp = [ 0 ] * ( lenn ) NEW_LINE for i in range ( lenn ) : NEW_LINE DEDENT j = i NEW_LINE k = 0 NEW_LINE INDENT while ( j < len ( str ) ) : NEW_LINE INDENT temp [ k ] = str [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT j = 0 NEW_LINE while ( j < i ) : NEW_LINE INDENT temp [ k ] = str [ j ] NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT print ( * temp , sep = " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeks " NEW_LINE printRotatedString ( str ) NEW_LINE DEDENT |
All possible strings of any length that can be formed from a given string | Python3 code to generate all possible strings that can be formed from given string ; Number of subsequences is ( 2 * * n - 1 ) ; Generate all subsequences of a given string . using counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter is set If set then print jth element from arr [ ] ; Print all permutations of current subsequence ; Driver program | from itertools import permutations NEW_LINE def printAll ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE opsize = pow ( 2 , n ) NEW_LINE for counter in range ( 1 , opsize ) : NEW_LINE INDENT subs = " " NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( counter & ( 1 << j ) ) : NEW_LINE INDENT subs += ( st [ j ] ) NEW_LINE DEDENT DEDENT perm = permutations ( subs ) NEW_LINE for i in perm : NEW_LINE INDENT print ( ' ' . join ( i ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " abc " NEW_LINE printAll ( ( st ) ) NEW_LINE DEDENT |
Longest Non | utility function to check whether a string is palindrome or not ; Check for palindrome . ; palindrome string ; function to find maximum length substring which is not palindrome ; to check whether all characters of the string are same or not ; All characters are same , we can 't make a non-palindromic string. ; If string is palindrome , we can make it non - palindrome by removing any corner character ; Complete string is not a palindrome . ; Driver Code | def isPalindrome ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if ( str [ i ] != str [ n - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def maxLengthNonPalinSubstring ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE ch = str [ 0 ] NEW_LINE i = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( str [ i ] != ch ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( isPalindrome ( str ) ) : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT return n NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " abba " NEW_LINE print ( " Maximum β length β = " , maxLengthNonPalinSubstring ( str ) ) NEW_LINE DEDENT |
Move spaces to front of string in single traversal | Function to find spaces and move to beginning ; Traverse from end and swap spaces ; Driver code | def moveSpaceInFront ( s ) : NEW_LINE INDENT i = len ( s ) - 1 ; NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ j ] != ' β ' ) : NEW_LINE INDENT s = swap ( s , i , j ) ; NEW_LINE i -= 1 ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT def swap ( c , i , j ) : NEW_LINE INDENT c = list ( c ) NEW_LINE c [ i ] , c [ j ] = c [ j ] , c [ i ] NEW_LINE return ' ' . join ( c ) NEW_LINE DEDENT s = " Hey β there , β it ' s β GeeksforGeeks " ; NEW_LINE s = moveSpaceInFront ( s ) ; NEW_LINE print ( s ) ; NEW_LINE |
Move spaces to front of string in single traversal | Function to find spaces and move to beginning ; Keep copying non - space characters ; Move spaces to be beginning ; Driver code | def moveSpaceInFront ( s ) : NEW_LINE INDENT i = len ( s ) - 1 ; NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ j ] != ' β ' ) : NEW_LINE INDENT s = s [ : i ] + s [ j ] + s [ i + 1 : ] NEW_LINE i -= 1 ; NEW_LINE DEDENT DEDENT while ( i >= 0 ) : NEW_LINE INDENT s = s [ : i ] + ' β ' + s [ i + 1 : ] NEW_LINE i -= 1 NEW_LINE DEDENT return s ; NEW_LINE DEDENT s = " Hey β there , β it ' s β GeeksforGeeks " ; NEW_LINE s = moveSpaceInFront ( s ) ; NEW_LINE print ( s ) ; NEW_LINE |
Minimum number of Appends needed to make a string palindrome | Checking if the String is palindrome or not ; single character is always palindrome ; pointing to first character ; pointing to last character ; Recursive function to count number of appends ; Removing first character of String by incrementing base address pointer . ; Driver Code | def isPalindrome ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE if ( Len == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT ptr1 = 0 NEW_LINE ptr2 = Len - 1 NEW_LINE while ( ptr2 > ptr1 ) : NEW_LINE INDENT if ( Str [ ptr1 ] != Str [ ptr2 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT ptr1 += 1 NEW_LINE ptr2 -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def noOfAppends ( s ) : NEW_LINE INDENT if ( isPalindrome ( s ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT del s [ 0 ] NEW_LINE return 1 + noOfAppends ( s ) NEW_LINE DEDENT se = " abede " NEW_LINE s = [ i for i in se ] NEW_LINE print ( noOfAppends ( s ) ) NEW_LINE |
Find Excel column number from column title | Returns resul when we pass title . ; This process is similar to binary - to - decimal conversion ; Driver function | def titleToNumber ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE for B in range ( len ( s ) ) : NEW_LINE INDENT result *= 26 ; NEW_LINE result += ord ( s [ B ] ) - ord ( ' A ' ) + 1 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT print ( titleToNumber ( " CDA " ) ) ; NEW_LINE |
Check whether K | PHP program to check if k - th bit of a given number is set or not using right shift operator . ; Driver code | def isKthBitSet ( n , k ) : NEW_LINE INDENT if ( ( n >> ( k - 1 ) ) and 1 ) : NEW_LINE INDENT print ( " SET " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NOT β SET " ) NEW_LINE DEDENT DEDENT n , k = 5 , 1 NEW_LINE isKthBitSet ( n , k ) NEW_LINE |
Reverse string without using any temporary variable | Function to reverse string and return reversed string ; Iterate loop upto start not equal to end ; XOR for swapping the variable ; Driver Code | def reversingString ( str , start , end ) : NEW_LINE INDENT while ( start < end ) : NEW_LINE INDENT str = ( str [ : start ] + chr ( ord ( str [ start ] ) ^ ord ( str [ end ] ) ) + str [ start + 1 : ] ) ; NEW_LINE str = ( str [ : end ] + chr ( ord ( str [ start ] ) ^ ord ( str [ end ] ) ) + str [ end + 1 : ] ) ; NEW_LINE str = ( str [ : start ] + chr ( ord ( str [ start ] ) ^ ord ( str [ end ] ) ) + str [ start + 1 : ] ) ; NEW_LINE start += 1 ; NEW_LINE end -= 1 ; NEW_LINE DEDENT return str ; NEW_LINE DEDENT s = " GeeksforGeeks " ; NEW_LINE print ( reversingString ( s , 0 , 12 ) ) ; NEW_LINE |
Check if a string follows a ^ nb ^ n pattern or not | Python3 code to check a ^ nb ^ n pattern ; if length of str is odd return No ; check first half is ' a ' and other half is full of 'b ; Driver code ; Function call | def isanbn ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if n & 1 : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( int ( n / 2 ) ) : NEW_LINE INDENT if str [ i ] != ' a ' or str [ n - i - 1 ] != ' b ' : NEW_LINE return " No " NEW_LINE DEDENT return " Yes " NEW_LINE DEDENT input_str = " ab " NEW_LINE print ( isanbn ( input_str ) ) NEW_LINE |
Number of substrings divisible by 6 in a string of integers | Return the number of substring divisible by 6 and starting at index i in s [ ] and previous sum of digits modulo 3 is m . ; End of the string . ; If already calculated , return the stored value . ; Converting into integer . ; Increment result by 1 , if current digit is divisible by 2 and sum of digits is divisible by 3. And recur for next index with new modulo . ; Returns substrings divisible by 6. ; For storing the value of all states . ; If string contain 0 , increment count by 1. ; Else calculate using recursive function . Pass previous sum modulo 3 as 0. ; Driver Code | def f ( i , m , s , memoize ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( memoize [ i ] [ m ] != - 1 ) : NEW_LINE INDENT return memoize [ i ] [ m ] NEW_LINE DEDENT x = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE ans = ( ( ( x + m ) % 3 == 0 and x % 2 == 0 ) + f ( i + 1 , ( m + x ) % 3 , s , memoize ) ) NEW_LINE memoize [ i ] [ m ] = ans NEW_LINE return memoize [ i ] [ m ] NEW_LINE DEDENT def countDivBy6 ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE memoize = [ [ - 1 ] * 3 for i in range ( n + 1 ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += f ( i , 0 , s , memoize ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "4806" NEW_LINE print ( countDivBy6 ( s ) ) NEW_LINE DEDENT |
Lexicographically first palindromic string | Python3 program to find first palindromic permutation of given string ; Function to count frequency of each char in the string . freq [ 0 ] for ' a ' , ... . , freq [ 25 ] for 'z ; Cases to check whether a palindr0mic string can be formed or not ; count_odd to count no of chars with odd frequency ; For even length string no odd freq character ; For odd length string one odd freq character ; Function to find odd freq char and reducing its freq by 1 returns " " if odd freq char is not present ; To find lexicographically first palindromic string . ; Assigning odd freq character if present else empty string . ; Traverse characters in increasing order ; Divide all occurrences into two halves . Note that odd character is removed by findOddAndRemoveItsFreq ( ) ; creating front string ; creating rear string ; Final palindromic string which is lexicographically first ; Driver code | MAX_CHAR = 26 ; NEW_LINE ' NEW_LINE def countFreq ( str1 , freq , len1 ) : NEW_LINE INDENT for i in range ( len1 ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT DEDENT def canMakePalindrome ( freq , len1 ) : NEW_LINE INDENT count_odd = 0 ; NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( freq [ i ] % 2 != 0 ) : NEW_LINE INDENT count_odd += 1 ; NEW_LINE DEDENT DEDENT if ( len1 % 2 == 0 ) : NEW_LINE INDENT if ( count_odd > 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT if ( count_odd != 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def findOddAndRemoveItsFreq ( freq ) : NEW_LINE INDENT odd_str = " " ; NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( freq [ i ] % 2 != 0 ) : NEW_LINE INDENT freq [ i ] -= 1 ; NEW_LINE odd_str += chr ( i + ord ( ' a ' ) ) ; NEW_LINE return odd_str ; NEW_LINE DEDENT DEDENT return odd_str ; NEW_LINE DEDENT def findPalindromicString ( str1 ) : NEW_LINE INDENT len1 = len ( str1 ) ; NEW_LINE freq = [ 0 ] * MAX_CHAR ; NEW_LINE countFreq ( str1 , freq , len1 ) ; NEW_LINE if ( canMakePalindrome ( freq , len1 ) == False ) : NEW_LINE INDENT return " No β Palindromic β String " ; NEW_LINE DEDENT odd_str = findOddAndRemoveItsFreq ( freq ) ; NEW_LINE front_str = " " ; NEW_LINE rear_str = " β " ; NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT temp = " " ; NEW_LINE if ( freq [ i ] != 0 ) : NEW_LINE INDENT ch = chr ( i + ord ( ' a ' ) ) ; NEW_LINE for j in range ( 1 , int ( freq [ i ] / 2 ) + 1 ) : NEW_LINE INDENT temp += ch ; NEW_LINE DEDENT front_str += temp ; NEW_LINE rear_str = temp + rear_str ; NEW_LINE DEDENT DEDENT return ( front_str + odd_str + rear_str ) ; NEW_LINE DEDENT str1 = " malayalam " ; NEW_LINE print ( findPalindromicString ( str1 ) ) ; NEW_LINE |
Count substrings with same first and last characters | Returns true if first and last characters of s are same . ; Starting point of substring ; Length of substring ; Check if current substring has same starting and ending characters . ; Driver code | def checkEquality ( s ) : NEW_LINE INDENT return ( ord ( s [ 0 ] ) == ord ( s [ len ( s ) - 1 ] ) ) ; NEW_LINE DEDENT def countSubstringWithEqualEnds ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , n - i + 1 ) : NEW_LINE INDENT if ( checkEquality ( s [ i : i + j ] ) ) : NEW_LINE INDENT result += 1 ; NEW_LINE DEDENT DEDENT DEDENT return result ; NEW_LINE DEDENT s = " abcab " ; NEW_LINE print ( countSubstringWithEqualEnds ( s ) ) ; NEW_LINE |
Count substrings with same first and last characters | Space efficient Python3 program to count all substrings with same first and last characters . ; Iterating through all substrings in way so that we can find first and last character easily ; Driver Code | def countSubstringWithEqualEnds ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT s = " abcab " ; NEW_LINE print ( countSubstringWithEqualEnds ( s ) ) NEW_LINE |
Find the missing number in a string of numbers with no separator | Python3 program to find a missing number in a string of consecutive numbers without any separator . ; gets the integer at position i with length m , returns it or - 1 , if none ; Find value at index i and length m . ; Returns value of missing number ; Try all lengths for first number ; Get value of first number with current length ; To store missing number of current length ; To indicate whether the sequence failed anywhere for current length . ; Find subsequent numbers with previous number as n ; If we haven 't yet found the missing number for current length. Next number is n+2. Note that we use Log10 as (n+2) may have more length than n. ; If next value is ( n + 1 ) ; not found or no missing number ; Driver code | import math NEW_LINE MAX_DIGITS = 6 NEW_LINE def getValue ( Str , i , m ) : NEW_LINE INDENT if ( i + m > len ( Str ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT value = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT c = ( ord ( Str [ i + j ] ) - ord ( '0' ) ) NEW_LINE if ( c < 0 or c > 9 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT value = value * 10 + c NEW_LINE DEDENT return value NEW_LINE DEDENT def findMissingNumber ( Str ) : NEW_LINE INDENT for m in range ( 1 , MAX_DIGITS + 1 ) : NEW_LINE INDENT n = getValue ( Str , 0 , m ) NEW_LINE if ( n == - 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT missingNo = - 1 NEW_LINE fail = False NEW_LINE i = m NEW_LINE while ( i != len ( Str ) ) : NEW_LINE INDENT if ( ( missingNo == - 1 ) and ( getValue ( Str , i , 1 + int ( math . log10 ( n + 2 ) ) ) == n + 2 ) ) : NEW_LINE INDENT missingNo = n + 1 NEW_LINE n += 2 NEW_LINE DEDENT elif ( ( getValue ( Str , i , 1 + int ( math . log10 ( n + 1 ) ) ) == n + 1 ) ) : NEW_LINE INDENT n += 1 NEW_LINE DEDENT else : NEW_LINE INDENT fail = True NEW_LINE break NEW_LINE DEDENT i += 1 + int ( math . log10 ( n ) ) NEW_LINE DEDENT if ( not fail ) : NEW_LINE INDENT return missingNo NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT print ( findMissingNumber ( "99101102" ) ) NEW_LINE |
Maximum consecutive repeating character in string | function to find out the maximum repeating character in given string ; Find the maximum repeating character starting from str [ i ] ; Update result if required ; Driver code | def maxRepeating ( str ) : NEW_LINE INDENT l = len ( str ) NEW_LINE count = 0 NEW_LINE res = str [ 0 ] NEW_LINE for i in range ( l ) : NEW_LINE INDENT cur_count = 1 NEW_LINE for j in range ( i + 1 , l ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT cur_count += 1 NEW_LINE DEDENT if cur_count > count : NEW_LINE INDENT count = cur_count NEW_LINE res = str [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " aaaabbaaccde " NEW_LINE print ( maxRepeating ( str ) ) NEW_LINE DEDENT |
Sum of two large numbers | Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Reverse both of strings ; Do school mathematics , compute sum of current digits and carry ; Calculate carry for next step ; Add remaining digits of larger number ; Add remaining carry ; reverse resultant string ; Driver code | def findSum ( str1 , str2 ) : NEW_LINE INDENT if ( len ( str1 ) > len ( str2 ) ) : NEW_LINE INDENT t = str1 ; NEW_LINE str1 = str2 ; NEW_LINE str2 = t ; NEW_LINE DEDENT str = " " ; NEW_LINE n1 = len ( str1 ) ; NEW_LINE n2 = len ( str2 ) ; NEW_LINE str1 = str1 [ : : - 1 ] ; NEW_LINE str2 = str2 [ : : - 1 ] ; NEW_LINE carry = 0 ; NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT sum = ( ( ord ( str1 [ i ] ) - 48 ) + ( ( ord ( str2 [ i ] ) - 48 ) + carry ) ) ; NEW_LINE str += chr ( sum % 10 + 48 ) ; NEW_LINE carry = int ( sum / 10 ) ; NEW_LINE DEDENT for i in range ( n1 , n2 ) : NEW_LINE INDENT sum = ( ( ord ( str2 [ i ] ) - 48 ) + carry ) ; NEW_LINE str += chr ( sum % 10 + 48 ) ; NEW_LINE carry = ( int ) ( sum / 10 ) ; NEW_LINE DEDENT if ( carry ) : NEW_LINE INDENT str += chr ( carry + 48 ) ; NEW_LINE DEDENT str = str [ : : - 1 ] ; NEW_LINE return str ; NEW_LINE DEDENT str1 = "12" ; NEW_LINE str2 = "198111" ; NEW_LINE print ( findSum ( str1 , str2 ) ) ; NEW_LINE |
Sum of two large numbers | Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute sum of current digits and carry ; Add remaining digits of str2 [ ] ; Add remaining carry ; reverse resultant string ; Driver code | def findSum ( str1 , str2 ) : NEW_LINE INDENT if len ( str1 ) > len ( str2 ) : NEW_LINE INDENT temp = str1 NEW_LINE str1 = str2 NEW_LINE str2 = temp NEW_LINE DEDENT str3 = " " NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE diff = n2 - n1 NEW_LINE carry = 0 NEW_LINE for i in range ( n1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = ( ( ord ( str1 [ i ] ) - ord ( '0' ) ) + int ( ( ord ( str2 [ i + diff ] ) - ord ( '0' ) ) ) + carry ) NEW_LINE str3 = str3 + str ( sum % 10 ) NEW_LINE carry = sum // 10 NEW_LINE DEDENT for i in range ( n2 - n1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = ( ( ord ( str2 [ i ] ) - ord ( '0' ) ) + carry ) NEW_LINE str3 = str3 + str ( sum % 10 ) NEW_LINE carry = sum // 10 NEW_LINE DEDENT if ( carry ) : NEW_LINE INDENT str3 + str ( carry + '0' ) NEW_LINE DEDENT str3 = str3 [ : : - 1 ] NEW_LINE return str3 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "12" NEW_LINE str2 = "198111" NEW_LINE print ( findSum ( str1 , str2 ) ) NEW_LINE DEDENT |
Palindrome pair in an array of words ( or strings ) | Utility function to check if a string is a palindrome ; Compare each character from starting with its corresponding character from last ; Function to check if a palindrome pair exists ; Consider each pair one by one ; Concatenate both strings ; Check if the concatenated string is palindrome ; Check for other combination of the two strings ; Driver code | def isPalindrome ( st ) : NEW_LINE INDENT length = len ( st ) NEW_LINE for i in range ( length // 2 ) : NEW_LINE INDENT if ( st [ i ] != st [ length - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def checkPalindromePair ( vect ) : NEW_LINE INDENT for i in range ( len ( vect ) - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , len ( vect ) ) : NEW_LINE INDENT check_str = vect [ i ] + vect [ j ] NEW_LINE if ( isPalindrome ( check_str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT check_str = vect [ j ] + vect [ i ] NEW_LINE if ( isPalindrome ( check_str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT vect = [ " geekf " , " geeks " , " or " , " keeg " , " abc " , " bc " ] NEW_LINE if checkPalindromePair ( vect ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Print consecutive characters together in a line | Python3 program to print consecutive characters together in a line . ; Driver Code | def _print ( string ) : NEW_LINE INDENT print ( string [ 0 ] , end = " " ) NEW_LINE for i in range ( 1 , len ( string ) ) : NEW_LINE INDENT if ( ord ( string [ i ] ) == ord ( string [ i - 1 ] ) + 1 or ord ( string [ i ] ) == ord ( string [ i - 1 ] ) - 1 ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ) NEW_LINE print ( string [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " ABCXYZACCD " NEW_LINE _print ( string ) NEW_LINE DEDENT |
Efficiently check if a string has all unique characters without using any additional data structure | Returns true if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters using its 32 bits ; If bit corresponding to current character is already set ; set bit in checker ; Driver code | def areCharactersUnique ( s ) : NEW_LINE INDENT checker = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT val = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( checker & ( 1 << val ) ) > 0 : NEW_LINE INDENT return False NEW_LINE DEDENT checker |= ( 1 << val ) NEW_LINE DEDENT return True NEW_LINE DEDENT s = " aaabbccdaa " NEW_LINE if areCharactersUnique ( s ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Count of words whose i | Return the count of words . ; If word contain single letter , return 1. ; Checking for first letter . ; Traversing the string and multiplying for combinations . ; If all three letters are same . ; If two letter are distinct . ; If all three letter are distinct . ; Checking for last letter . ; Driven Program | def countWords ( str , l ) : NEW_LINE INDENT count = 1 ; NEW_LINE if ( l == 1 ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( str [ 0 ] == str [ 1 ] ) : NEW_LINE INDENT count *= 1 NEW_LINE DEDENT else : NEW_LINE INDENT count *= 2 NEW_LINE DEDENT for j in range ( 1 , l - 1 ) : NEW_LINE INDENT if ( str [ j ] == str [ j - 1 ] and str [ j ] == str [ j + 1 ] ) : NEW_LINE INDENT count *= 1 NEW_LINE DEDENT elif ( str [ j ] == str [ j - 1 ] or str [ j ] == str [ j + 1 ] or str [ j - 1 ] == str [ j + 1 ] ) : NEW_LINE INDENT count *= 2 NEW_LINE DEDENT else : NEW_LINE INDENT count *= 3 NEW_LINE DEDENT DEDENT if ( str [ l - 1 ] == str [ l - 2 ] ) : NEW_LINE INDENT count *= 1 NEW_LINE DEDENT else : NEW_LINE INDENT count *= 2 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " abc " NEW_LINE l = len ( str ) NEW_LINE print ( countWords ( str , l ) ) NEW_LINE DEDENT |
Maximum and minimum sums from two numbers with digit replacements | Find new value of x after replacing digit " from " to " to " ; Required digit found , replace it ; Returns maximum and minimum possible sums of x1 and x2 if digit replacements are allowed . ; We always get minimum sum if we replace 6 with 5. ; We always get maximum sum if we replace 5 with 6. ; Driver code | def replaceDig ( x , from1 , to ) : NEW_LINE INDENT result = 0 NEW_LINE multiply = 1 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT reminder = x % 10 NEW_LINE if ( reminder == from1 ) : NEW_LINE INDENT result = result + to * multiply NEW_LINE DEDENT else : NEW_LINE INDENT result = result + reminder * multiply NEW_LINE DEDENT multiply *= 10 NEW_LINE x = int ( x / 10 ) NEW_LINE DEDENT return result NEW_LINE DEDENT def calculateMinMaxSum ( x1 , x2 ) : NEW_LINE INDENT minSum = replaceDig ( x1 , 6 , 5 ) + replaceDig ( x2 , 6 , 5 ) NEW_LINE maxSum = replaceDig ( x1 , 5 , 6 ) + replaceDig ( x2 , 5 , 6 ) NEW_LINE print ( " Minimum β sum β = " , minSum ) NEW_LINE print ( " Maximum β sum β = " , maxSum , end = " β " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x1 = 5466 NEW_LINE x2 = 4555 NEW_LINE calculateMinMaxSum ( x1 , x2 ) NEW_LINE DEDENT |
Queries on substring palindrome formation | Query type 1 : update str1ing position i with character x . ; Pr " Yes " if range [ L . . R ] can form palindrome , else pr " No " . ; Find the frequency of each character in S [ L ... R ] . ; Checking if more than one character have frequency greater than 1. ; Driver Code | def qType1 ( l , x , str1 ) : NEW_LINE INDENT str1 [ l - 1 ] = x NEW_LINE DEDENT def qType2 ( l , r , str1 ) : NEW_LINE INDENT freq = [ 0 for i in range ( 27 ) ] NEW_LINE for i in range ( l - 1 , r ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT if ( freq [ j ] % 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if count <= 1 : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT str1 = " geeksforgeeks " NEW_LINE str2 = [ i for i in str1 ] NEW_LINE n = len ( str2 ) NEW_LINE qType1 ( 4 , ' g ' , str2 ) NEW_LINE qType2 ( 1 , 4 , str2 ) NEW_LINE qType2 ( 2 , 3 , str2 ) NEW_LINE qType1 ( 10 , ' t ' , str2 ) NEW_LINE qType2 ( 10 , 11 , str2 ) NEW_LINE |
Queries on substring palindrome formation | Python3 program to Queries on substr1ing palindrome formation . ; Return the frequency of the character in the i - th prefix . ; Updating the BIT ; Query to update the character in the str1ing . ; Adding - 1 at L position ; Updating the character ; Adding + 1 at R position ; Query to find if rearrangement of character in range L ... R can form palindrome ; Checking on the first character of the str1ing S . ; Checking if frequency of character is even or odd . ; Creating the Binary Index Tree of all aphabet ; Driver code | max = 1000 ; NEW_LINE def getFrequency ( tree , idx , i ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( idx > 0 ) : NEW_LINE INDENT sum += tree [ idx ] [ i ] ; NEW_LINE idx -= ( idx & - idx ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def update ( tree , idx , val , i ) : NEW_LINE INDENT while ( idx <= max ) : NEW_LINE INDENT tree [ idx ] [ i ] += val ; NEW_LINE idx += ( idx & - idx ) ; NEW_LINE DEDENT DEDENT def qType1 ( tree , l , x , str1 ) : NEW_LINE INDENT update ( tree , l , - 1 , ord ( str1 [ l - 1 ] ) - 97 + 1 ) ; NEW_LINE list1 = list ( str1 ) NEW_LINE list1 [ l - 1 ] = x ; NEW_LINE str1 = ' ' . join ( list1 ) ; NEW_LINE update ( tree , l , 1 , ord ( str1 [ l - 1 ] ) - 97 + 1 ) ; NEW_LINE DEDENT def qType2 ( tree , l , r , str1 ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 1 , 27 ) : NEW_LINE INDENT if ( l == 1 ) : NEW_LINE INDENT if ( getFrequency ( tree , r , i ) % 2 == 1 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( ( getFrequency ( tree , r , i ) - getFrequency ( tree , l - 1 , i ) ) % 2 == 1 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( " Yes " ) if ( count <= 1 ) else print ( " No " ) ; NEW_LINE DEDENT def buildBIT ( tree , str1 , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT update ( tree , i + 1 , 1 , ord ( str1 [ i ] ) - 97 + 1 ) ; NEW_LINE DEDENT DEDENT str1 = " geeksforgeeks " ; NEW_LINE n = len ( str1 ) ; NEW_LINE tree = [ [ 0 for x in range ( 27 ) ] for y in range ( max ) ] ; NEW_LINE buildBIT ( tree , str1 , n ) ; NEW_LINE qType1 ( tree , 4 , ' g ' , str1 ) ; NEW_LINE qType2 ( tree , 1 , 4 , str1 ) ; NEW_LINE qType2 ( tree , 2 , 3 , str1 ) ; NEW_LINE qType1 ( tree , 10 , ' t ' , str1 ) ; NEW_LINE qType2 ( tree , 10 , 11 , str1 ) ; NEW_LINE |
Subsets and Splits