text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Maximum possible time that can be formed from four digits | Python3 implementation of the approach ; Function to return the updated frequency map for the array passed as argument ; Function that returns true if the passed digit is present in the map after decrementing it 's frequency by 1 ; If map contains the digit ; Decrement the frequency of the digit by 1 ; True here indicates that the digit was found in the map ; Digit not found ; Function to return the maximum possible time_value in 24 - Hours format ; First digit of hours can be from the range [ 0 , 2 ] ; If no valid digit found ; If first digit of hours was chosen as 2 then the second digit of hours can be from the range [ 0 , 3 ] ; Else it can be from the range [ 0 , 9 ] ; Hours and minutes separator ; First digit of minutes can be from the range [ 0 , 5 ] ; Second digit of minutes can be from the range [ 0 , 9 ] ; Return the maximum possible time_value ; Driver code | from collections import defaultdict NEW_LINE def getFrequencyMap ( arr , n ) : NEW_LINE INDENT hashMap = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hashMap [ arr [ i ] ] += 1 NEW_LINE DEDENT return hashMap NEW_LINE DEDENT def hasDigit ( hashMap , digit ) : NEW_LINE INDENT if hashMap [ digit ] > 0 : NEW_LINE INDENT hashMap [ digit ] -= 1 NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT def getMaxtime_value ( arr , n ) : NEW_LINE INDENT hashMap = getFrequencyMap ( arr , n ) NEW_LINE flag = False NEW_LINE time_value = " " NEW_LINE for i in range ( 2 , - 1 , - 1 ) : NEW_LINE INDENT if hasDigit ( hashMap , i ) == True : NEW_LINE INDENT flag = True NEW_LINE time_value += str ( i ) NEW_LINE break NEW_LINE DEDENT DEDENT if not flag : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT flag = False NEW_LINE if ( time_value [ 0 ] == '2' ) : NEW_LINE INDENT for i in range ( 3 , - 1 , - 1 ) : NEW_LINE INDENT if hasDigit ( hashMap , i ) == True : NEW_LINE INDENT flag = True NEW_LINE time_value += str ( i ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 9 , - 1 , - 1 ) : NEW_LINE INDENT if hasDigit ( hashMap , i ) == True : NEW_LINE INDENT flag = True NEW_LINE time_value += str ( i ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if not flag : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT time_value += " : " NEW_LINE flag = False NEW_LINE for i in range ( 5 , - 1 , - 1 ) : NEW_LINE INDENT if hasDigit ( hashMap , i ) == True : NEW_LINE INDENT flag = True NEW_LINE time_value += str ( i ) NEW_LINE break NEW_LINE DEDENT DEDENT if not flag : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT flag = False NEW_LINE for i in range ( 9 , - 1 , - 1 ) : NEW_LINE INDENT if hasDigit ( hashMap , i ) == True : NEW_LINE INDENT flag = True NEW_LINE time_value += str ( i ) NEW_LINE break NEW_LINE DEDENT DEDENT if not flag : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT return time_value NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 0 , 0 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getMaxtime_value ( arr , n ) ) NEW_LINE DEDENT |
Most frequent word in first String which is not present in second String | Python3 implementation of above approach ; Function to return frequent word from S1 that isn 't present in S2 ; create map of banned words ; find smallest and most frequent word ; check if word is not banned ; return answer ; Driver Code | from collections import defaultdict NEW_LINE def smallestFreq ( S1 , S2 ) : NEW_LINE INDENT banned = defaultdict ( lambda : 0 ) NEW_LINE i = 0 NEW_LINE while i < len ( S2 ) : NEW_LINE INDENT s = " " NEW_LINE while i < len ( S2 ) and S2 [ i ] != ' β ' : NEW_LINE INDENT s += S2 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE banned [ s ] += 1 NEW_LINE DEDENT result = defaultdict ( lambda : 0 ) NEW_LINE ans = " " NEW_LINE freq = 0 NEW_LINE i = 0 NEW_LINE while i < len ( S1 ) : NEW_LINE INDENT s = " " NEW_LINE while i < len ( S1 ) and S1 [ i ] != ' β ' : NEW_LINE INDENT s += S1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE if banned [ s ] == 0 : NEW_LINE INDENT result [ s ] += 1 NEW_LINE if ( result [ s ] > freq or ( result [ s ] == freq and s < ans ) ) : NEW_LINE INDENT ans = s NEW_LINE freq = result [ s ] NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S1 = " geeks β for β geeks β is β best β place β to β learn " NEW_LINE S2 = " bad β place " NEW_LINE print ( smallestFreq ( S1 , S2 ) ) NEW_LINE DEDENT |
Minimum characters to be replaced to remove the given substring | Function to calculate minimum characters to replace ; mismatch occurs ; If all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driver Code | def replace ( A , B ) : NEW_LINE INDENT n , m = len ( A ) , len ( B ) NEW_LINE count , i = 0 , 0 NEW_LINE while i < n : NEW_LINE INDENT j = 0 NEW_LINE while j < m : NEW_LINE INDENT if i + j >= n or A [ i + j ] != B [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == m : NEW_LINE INDENT count += 1 NEW_LINE i += m - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " aaaaaaaa " NEW_LINE str2 = " aaa " NEW_LINE print ( replace ( str1 , str2 ) ) NEW_LINE DEDENT |
Largest connected component on a grid | Python3 program to print the largest connected component in a grid ; stores information about which cell are already visited in a particular BFS ; result stores the final result grid ; stores the count of cells in the largest connected component ; Function checks if a cell is valid i . e it is inside the grid and equal to the key ; BFS to find all cells in connection with key = input [ i ] [ j ] ; terminating case for BFS ; x_move and y_move arrays are the possible movements in x or y direction ; checks all four points connected with input [ i ] [ j ] ; called every time before a BFS so that visited array is reset to zero ; If a larger connected component is found this function is called to store information about that component . ; function to print the result ; prints the largest component ; function to calculate the largest connected component ; checking cell to the right ; updating result ; checking cell downwards ; updating result ; Drivers Code ; function to compute the largest connected component in the grid | n = 6 ; NEW_LINE m = 8 ; NEW_LINE visited = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE result = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE COUNT = 0 NEW_LINE def is_valid ( x , y , key , input ) : NEW_LINE INDENT if ( x < n and y < m and x >= 0 and y >= 0 ) : NEW_LINE INDENT if ( visited [ x ] [ y ] == 0 and input [ x ] [ y ] == key ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def BFS ( x , y , i , j , input ) : NEW_LINE INDENT global COUNT NEW_LINE if ( x != y ) : NEW_LINE INDENT return ; NEW_LINE DEDENT visited [ i ] [ j ] = 1 ; NEW_LINE COUNT += 1 NEW_LINE x_move = [ 0 , 0 , 1 , - 1 ] NEW_LINE y_move = [ 1 , - 1 , 0 , 0 ] NEW_LINE for u in range ( 4 ) : NEW_LINE INDENT if ( is_valid ( i + y_move [ u ] , j + x_move [ u ] , x , input ) ) : NEW_LINE INDENT BFS ( x , y , i + y_move [ u ] , j + x_move [ u ] , input ) ; NEW_LINE DEDENT DEDENT DEDENT def reset_visited ( ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT visited [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT def reset_result ( key , input ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( visited [ i ] [ j ] != 0 and input [ i ] [ j ] == key ) : NEW_LINE INDENT result [ i ] [ j ] = visited [ i ] [ j ] ; NEW_LINE DEDENT else : NEW_LINE INDENT result [ i ] [ j ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def print_result ( res ) : NEW_LINE INDENT print ( " The β largest β connected β " + " component β of β the β grid β is β : " + str ( res ) ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( result [ i ] [ j ] != 0 ) : NEW_LINE INDENT print ( result [ i ] [ j ] , end = ' β ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' . β ' , end = ' ' ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT def computeLargestConnectedGrid ( input ) : NEW_LINE INDENT global COUNT NEW_LINE current_max = - 10000000000 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT reset_visited ( ) ; NEW_LINE COUNT = 0 ; NEW_LINE if ( j + 1 < m ) : NEW_LINE INDENT BFS ( input [ i ] [ j ] , input [ i ] [ j + 1 ] , i , j , input ) ; NEW_LINE DEDENT if ( COUNT >= current_max ) : NEW_LINE INDENT current_max = COUNT ; NEW_LINE reset_result ( input [ i ] [ j ] , input ) ; NEW_LINE DEDENT reset_visited ( ) ; NEW_LINE COUNT = 0 ; NEW_LINE if ( i + 1 < n ) : NEW_LINE INDENT BFS ( input [ i ] [ j ] , input [ i + 1 ] [ j ] , i , j , input ) ; NEW_LINE DEDENT if ( COUNT >= current_max ) : NEW_LINE INDENT current_max = COUNT ; NEW_LINE reset_result ( input [ i ] [ j ] , input ) ; NEW_LINE DEDENT DEDENT DEDENT print_result ( current_max ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = [ [ 1 , 4 , 4 , 4 , 4 , 3 , 3 , 1 ] , [ 2 , 1 , 1 , 4 , 3 , 3 , 1 , 1 ] , [ 3 , 2 , 1 , 1 , 2 , 3 , 2 , 1 ] , [ 3 , 3 , 2 , 1 , 2 , 2 , 2 , 2 ] , [ 3 , 1 , 3 , 1 , 1 , 4 , 4 , 4 ] , [ 1 , 1 , 3 , 1 , 1 , 4 , 4 , 4 ] ] ; NEW_LINE computeLargestConnectedGrid ( input ) ; NEW_LINE DEDENT |
Check if a string is substring of another | Returns true if s1 is substring of s2 ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; Driver Code | def isSubstring ( s1 , s2 ) : NEW_LINE INDENT M = len ( s1 ) NEW_LINE N = len ( s2 ) NEW_LINE for i in range ( N - M + 1 ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( s2 [ i + j ] != s1 [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j + 1 == M : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " for " NEW_LINE s2 = " geeksforgeeks " NEW_LINE res = isSubstring ( s1 , s2 ) NEW_LINE if res == - 1 : NEW_LINE INDENT print ( " Not β present " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Present β at β index β " + str ( res ) ) NEW_LINE DEDENT DEDENT |
Splitting a Numeric String | Function accepts a string and checks if string can be split . ; if there is only 1 number in the string then it is not possible to split it ; storing the substring from 0 to i + 1 to form initial number of the increasing sequence ; convert string to integer and add 1 and again convert back to string s2 ; if s2 is not a substring of number than not possible ; if s2 is the next substring of the numeric string ; Incearse num2 by 1 i . e the next number to be looked for ; check if string is fully traversed then break ; If next string doesnot occurs in a given numeric string then it is not possible ; if the string was fully traversed and conditions were satisfied ; if conditions failed to hold ; Driver code ; Call the split function for splitting the string | def split ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE if ( Len == 1 ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE return NEW_LINE DEDENT s1 , s2 = " " , " " NEW_LINE for i in range ( ( Len // 2 ) + 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE s1 = Str [ 0 : i + 1 ] NEW_LINE num1 = int ( s1 ) NEW_LINE num2 = num1 + 1 NEW_LINE s2 = str ( num2 ) NEW_LINE k = i + 1 NEW_LINE while ( flag == 0 ) : NEW_LINE INDENT l = len ( s2 ) NEW_LINE if ( k + l > Len ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT if ( ( Str [ k : k + l ] == s2 ) ) : NEW_LINE INDENT flag = 0 NEW_LINE num2 += 1 NEW_LINE k = k + l NEW_LINE if ( k == Len ) : NEW_LINE INDENT break NEW_LINE DEDENT s2 = str ( num2 ) NEW_LINE l = len ( s2 ) NEW_LINE if ( k + 1 > len ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " Possible " , s1 ) NEW_LINE break NEW_LINE DEDENT elif ( flag == 1 and i > ( Len // 2 ) - 1 ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT Str = "99100" NEW_LINE split ( Str ) NEW_LINE |
Count of number of given string in 2D character array | utility function to search complete string from any given index of 2d array ; through Backtrack searching in every directions ; Function to search the string in 2d array ; Driver code | def internalSearch ( ii , needle , row , col , hay , row_max , col_max ) : NEW_LINE INDENT found = 0 NEW_LINE if ( row >= 0 and row <= row_max and col >= 0 and col <= col_max and needle [ ii ] == hay [ row ] [ col ] ) : NEW_LINE INDENT match = needle [ ii ] NEW_LINE ii += 1 NEW_LINE hay [ row ] [ col ] = 0 NEW_LINE if ( ii == len ( needle ) ) : NEW_LINE INDENT found = 1 NEW_LINE DEDENT else : NEW_LINE INDENT found += internalSearch ( ii , needle , row , col + 1 , hay , row_max , col_max ) NEW_LINE found += internalSearch ( ii , needle , row , col - 1 , hay , row_max , col_max ) NEW_LINE found += internalSearch ( ii , needle , row + 1 , col , hay , row_max , col_max ) NEW_LINE found += internalSearch ( ii , needle , row - 1 , col , hay , row_max , col_max ) NEW_LINE DEDENT hay [ row ] [ col ] = match NEW_LINE DEDENT return found NEW_LINE DEDENT def searchString ( needle , row , col , strr , row_count , col_count ) : NEW_LINE INDENT found = 0 NEW_LINE for r in range ( row_count ) : NEW_LINE INDENT for c in range ( col_count ) : NEW_LINE INDENT found += internalSearch ( 0 , needle , r , c , strr , row_count - 1 , col_count - 1 ) NEW_LINE DEDENT DEDENT return found NEW_LINE DEDENT needle = " MAGIC " NEW_LINE inputt = [ " BBABBM " , " CBMBBA " , " IBABBG " , " GOZBBI " , " ABBBBC " , " MCIGAM " ] NEW_LINE strr = [ 0 ] * len ( inputt ) NEW_LINE for i in range ( len ( inputt ) ) : NEW_LINE INDENT strr [ i ] = list ( inputt [ i ] ) NEW_LINE DEDENT print ( " count : β " , searchString ( needle , 0 , 0 , strr , len ( strr ) , len ( strr [ 0 ] ) ) ) NEW_LINE |
Find minimum shift for longest common prefix | function for KMP search ; preprocessing of longest proper prefix ; find out the longest prefix and position ; for new position with longer prefix in str2 update pos and Len ; prresult ; Driver Code | def KMP ( m , n , str2 , str1 ) : NEW_LINE INDENT pos = 0 NEW_LINE Len = 0 NEW_LINE p = [ 0 for i in range ( m + 1 ) ] NEW_LINE k = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT while ( k > 0 and str1 [ k ] != str1 [ i - 1 ] ) : NEW_LINE INDENT k = p [ k ] NEW_LINE DEDENT if ( str1 [ k ] == str1 [ i - 1 ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT p [ i ] = k NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT while ( j > 0 and j < n and str1 [ j ] != str2 [ i ] ) : NEW_LINE INDENT j = p [ j ] NEW_LINE DEDENT if ( j < n and str1 [ j ] == str2 [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( j > Len ) : NEW_LINE INDENT Len = j NEW_LINE pos = i - j + 1 NEW_LINE DEDENT DEDENT print ( " Shift β = β " , pos ) NEW_LINE print ( " Prefix β = β " , str1 [ : Len ] ) NEW_LINE DEDENT str1 = " geeksforgeeks " NEW_LINE str2 = " forgeeksgeeks " NEW_LINE n = len ( str1 ) NEW_LINE str2 = str2 + str2 NEW_LINE KMP ( 2 * n , n , str2 , str1 ) NEW_LINE |
Find all the patterns of "1(0 + ) 1" in a given string | SET 1 ( General Approach ) | Function to count patterns ; Variable to store the last character ; We found 0 and last character was '1' , state change ; After the stream of 0 ' s , β we β got β a β ' 1 ', counter incremented ; Last character stored ; Driver Code | def patternCount ( str ) : NEW_LINE INDENT last = str [ 0 ] NEW_LINE i = 1 ; counter = 0 NEW_LINE while ( i < len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == '0' and last == '1' ) : NEW_LINE INDENT while ( str [ i ] == '0' ) : NEW_LINE INDENT i += 1 NEW_LINE if ( str [ i ] == '1' ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT DEDENT DEDENT last = str [ i ] NEW_LINE i += 1 NEW_LINE DEDENT return counter NEW_LINE DEDENT str = "1001ab010abc01001" NEW_LINE ans = patternCount ( str ) NEW_LINE print ( ans ) NEW_LINE |
Boyer Moore Algorithm | Good Suffix heuristic | preprocessing for strong good suffix rule ; m is the length of pattern ; if character at position i - 1 is not equivalent to character at j - 1 , then continue searching to right of the pattern for border ; the character preceding the occurrence of t in pattern P is different than the mismatching character in P , we stop skipping the occurrences and shift the pattern from i to j ; Update the position of next border ; p [ i - 1 ] matched with p [ j - 1 ] , border is found . store the beginning position of border ; Preprocessing for case 2 ; set the border position of the first character of the pattern to all indices in array shift having shift [ i ] = 0 ; suffix becomes shorter than bpos [ 0 ] , use the position of next widest border as value of j ; Search for a pattern in given text using Boyer Moore algorithm with Good suffix rule ; s is shift of the pattern with respect to text ; initialize all occurrence of shift to 0 ; do preprocessing ; Keep reducing index j of pattern while characters of pattern and text are matching at this shift s ; If the pattern is present at the current shift , then index j will become - 1 after the above loop ; pat [ i ] != pat [ s + j ] so shift the pattern shift [ j + 1 ] times ; Driver Code | def preprocess_strong_suffix ( shift , bpos , pat , m ) : NEW_LINE INDENT i = m NEW_LINE j = m + 1 NEW_LINE bpos [ i ] = j NEW_LINE while i > 0 : NEW_LINE INDENT while j <= m and pat [ i - 1 ] != pat [ j - 1 ] : NEW_LINE INDENT if shift [ j ] == 0 : NEW_LINE INDENT shift [ j ] = j - i NEW_LINE DEDENT j = bpos [ j ] NEW_LINE DEDENT i -= 1 NEW_LINE j -= 1 NEW_LINE bpos [ i ] = j NEW_LINE DEDENT DEDENT def preprocess_case2 ( shift , bpos , pat , m ) : NEW_LINE INDENT j = bpos [ 0 ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT if shift [ i ] == 0 : NEW_LINE INDENT shift [ i ] = j NEW_LINE DEDENT if i == j : NEW_LINE INDENT j = bpos [ j ] NEW_LINE DEDENT DEDENT DEDENT def search ( text , pat ) : NEW_LINE INDENT s = 0 NEW_LINE m = len ( pat ) NEW_LINE n = len ( text ) NEW_LINE bpos = [ 0 ] * ( m + 1 ) NEW_LINE shift = [ 0 ] * ( m + 1 ) NEW_LINE preprocess_strong_suffix ( shift , bpos , pat , m ) NEW_LINE preprocess_case2 ( shift , bpos , pat , m ) NEW_LINE while s <= n - m : NEW_LINE INDENT j = m - 1 NEW_LINE while j >= 0 and pat [ j ] == text [ s + j ] : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if j < 0 : NEW_LINE INDENT print ( " pattern β occurs β at β shift β = β % d " % s ) NEW_LINE s += shift [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT s += shift [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT text = " ABAAAABAACD " NEW_LINE pat = " ABA " NEW_LINE search ( text , pat ) NEW_LINE DEDENT |
Maximum length prefix of one string that occurs as subsequence in another | Return the maximum length prefix which is subsequence . ; Iterating string T . ; If end of string S . ; If character match , increment counter . ; Driver Code | def maxPrefix ( s , t ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , len ( t ) ) : NEW_LINE INDENT if ( count == len ( s ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( t [ i ] == s [ count ] ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT S = " digger " NEW_LINE T = " biggerdiagram " NEW_LINE print ( maxPrefix ( S , T ) ) NEW_LINE |
Replace all occurrences of string AB with C without using extra space | Python 3 program to replace all occurrences of " AB " with " C " ; Start traversing from second character ; If previous character is ' A ' and current character is 'B" ; Replace previous character with ' C ' and move all subsequent characters one position back ; Driver code | def translate ( st ) : NEW_LINE INDENT for i in range ( 1 , len ( st ) ) : NEW_LINE INDENT if ( st [ i - 1 ] == ' A ' and st [ i ] == ' B ' ) : NEW_LINE INDENT st [ i - 1 ] = ' C ' NEW_LINE for j in range ( i , len ( st ) - 1 ) : NEW_LINE INDENT st [ j ] = st [ j + 1 ] NEW_LINE DEDENT st [ len ( st ) - 1 ] = ' β ' NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT st = list ( " helloABworldABGfG " ) NEW_LINE translate ( st ) NEW_LINE print ( " The β modified β string β is β : " ) NEW_LINE print ( ' ' . join ( st ) ) NEW_LINE |
Find all occurrences of a given word in a matrix | Python3 Program to find all occurrences of the word in a matrix ; check whether given cell ( row , col ) is a valid cell or not . ; return true if row number and column number is in range ; These arrays are used to get row and column numbers of 8 neighboursof a given cell ; A utility function to do DFS for a 2D boolean matrix . It only considers the 8 neighbours as adjacent vertices ; return if current character doesn 't match with the next character in the word ; append current character position to path ; current character matches with the last character \ in the word ; Recur for all connected neighbours ; The main function to find all occurrences of the word in a matrix ; traverse through the all cells of given matrix ; occurrence of first character in matrix ; check and prif path exists ; Driver code | ROW = 3 NEW_LINE COL = 5 NEW_LINE def isvalid ( row , col , prevRow , prevCol ) : NEW_LINE INDENT return ( row >= 0 ) and ( row < ROW ) and ( col >= 0 ) and ( col < COL ) and not ( row == prevRow and col == prevCol ) NEW_LINE DEDENT rowNum = [ - 1 , - 1 , - 1 , 0 , 0 , 1 , 1 , 1 ] NEW_LINE colNum = [ - 1 , 0 , 1 , - 1 , 1 , - 1 , 0 , 1 ] NEW_LINE def DFS ( mat , row , col , prevRow , prevCol , word , path , index , n ) : NEW_LINE INDENT if ( index > n or mat [ row ] [ col ] != word [ index ] ) : NEW_LINE INDENT return NEW_LINE DEDENT path += word [ index ] + " ( " + str ( row ) + " , β " + str ( col ) + " ) β " NEW_LINE if ( index == n ) : NEW_LINE INDENT print ( path ) NEW_LINE return NEW_LINE DEDENT for k in range ( 8 ) : NEW_LINE INDENT if ( isvalid ( row + rowNum [ k ] , col + colNum [ k ] , prevRow , prevCol ) ) : NEW_LINE INDENT DFS ( mat , row + rowNum [ k ] , col + colNum [ k ] , row , col , word , path , index + 1 , n ) NEW_LINE DEDENT DEDENT DEDENT def findWords ( mat , word , n ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == word [ 0 ] ) : NEW_LINE INDENT DFS ( mat , i , j , - 1 , - 1 , word , " " , 0 , n ) NEW_LINE DEDENT DEDENT DEDENT DEDENT mat = [ [ ' B ' , ' N ' , ' E ' , ' Y ' , ' S ' ] , [ ' H ' , ' E ' , ' D ' , ' E ' , ' S ' ] , [ ' S ' , ' G ' , ' N ' , ' D ' , ' E ' ] ] NEW_LINE word = list ( " DES " ) NEW_LINE findWords ( mat , word , len ( word ) - 1 ) NEW_LINE |
Generate N Random Hexadecimal Numbers | Python3 program for the above approach ; Maximum length of the random integer ; Function to generate N Hexadecimal integers ; Stores all the possible charcters in the Hexadecimal notation ; Loop to print N integers ; Randomly select length of the int in the range [ 1 , maxSize ] ; Print len charcters ; Print a randomly selected character ; Driver Code | import random , math NEW_LINE maxSize = 10 ; NEW_LINE def randomHexInt ( N ) : NEW_LINE INDENT hexChar = [ '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT Len = math . floor ( random . random ( ) * ( maxSize - 1 ) + 1 ) NEW_LINE for j in range ( Len ) : NEW_LINE INDENT print ( hexChar [ math . floor ( random . random ( ) * 16 ) ] , end = " " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 ; NEW_LINE randomHexInt ( N ) ; NEW_LINE DEDENT |
Check if two array of string are equal by performing swapping operations | Function to check whether brr [ ] can be made equal to arr [ ] by doing swapping operations ; siz variable to store size of string ; iterate till N to sort strings ; sort each string in arr [ ] ; sort each string in brr [ ] ; Sort both the vectors so that all the comparable strings will be arranged ; iterate till N to compare string in arr [ ] and brr [ ] ; Compare each string ; Return false becaues if atleast one string is not equal then brr [ ] cannot be converted to arr [ ] ; All the strings are compared so at last return true . ; Driver code ; Store the answer in variable | def checkEqualArrays ( arr , brr , N ) : NEW_LINE INDENT siz = len ( arr [ 0 ] ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp1 = list ( arr [ i ] ) ; NEW_LINE temp1 . sort ( ) ; NEW_LINE arr [ i ] = " " . join ( temp1 ) NEW_LINE temp2 = list ( brr [ i ] ) ; NEW_LINE temp2 . sort ( ) ; NEW_LINE brr [ i ] = " " . join ( temp2 ) ; NEW_LINE DEDENT arr . sort ( ) NEW_LINE brr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != brr [ i ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 ; NEW_LINE arr = [ " bcd " , " aac " ] ; NEW_LINE brr = [ " aca " , " dbc " ] ; NEW_LINE ans = checkEqualArrays ( arr , brr , N ) ; NEW_LINE if ( ans ) : NEW_LINE INDENT print ( " true " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " false " ) ; NEW_LINE DEDENT DEDENT |
Maximum length of string formed by concatenation having even frequency of each character | Python3 implementation of the above approach ; Function to check the string ; Count the frequency of the string ; Check the frequency of the string ; Store the length of the new String ; Function to find the longest concatenated string having every character of even frequency ; Checking the string ; Dont Include the string ; Include the string ; Driver code ; Call the function ; Print the answer | maxi = 0 ; NEW_LINE ans1 = " " ; NEW_LINE def calculate ( ans ) : NEW_LINE INDENT global maxi , ans1 ; NEW_LINE dp = [ 0 ] * 26 ; NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT dp [ ord ( ans [ i ] ) - ord ( ' A ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( dp [ i ] % 2 == 1 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT DEDENT if ( maxi < len ( ans ) ) : NEW_LINE INDENT maxi = len ( ans ) ; NEW_LINE ans1 = ans ; NEW_LINE DEDENT DEDENT def longestString ( arr , index , string ) : NEW_LINE INDENT if ( index == len ( arr ) ) : NEW_LINE INDENT return ; NEW_LINE DEDENT longestString ( arr , index + 1 , string ) ; NEW_LINE string += arr [ index ] ; NEW_LINE calculate ( string ) ; NEW_LINE longestString ( arr , index + 1 , string ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ " ABAB " , " ABF " , " CDA " , " AD " , " CCC " ] ; NEW_LINE longestString ( A , 0 , " " ) ; NEW_LINE print ( ans1 , len ( ans1 ) ) ; NEW_LINE DEDENT |
Find the next number by adding natural numbers in order on alternating indices from last | Function to generate the resultant number using the given criteria ; Storing end result ; Find the length of numeric string ; Traverse the string ; Storing digit at ith position ; Checking that the number would be added or not ; Logic for summing the digits if the digit is greater than 10 ; Storing the result ; Returning the result ; Driver Code | def generateNumber ( number ) : NEW_LINE INDENT temp = 0 ; adding_number = 0 ; NEW_LINE result = " " ; NEW_LINE l = len ( number ) ; NEW_LINE for i in range ( l - 1 , - 1 , - 1 ) : NEW_LINE INDENT digit = ord ( number [ i ] ) - ord ( '0' ) ; NEW_LINE if ( temp % 2 == 0 ) : NEW_LINE INDENT adding_number += 1 ; NEW_LINE digit += adding_number ; NEW_LINE if ( digit >= 10 ) : NEW_LINE INDENT digit %= 9 ; NEW_LINE if ( digit == 0 ) : NEW_LINE INDENT digit = 9 ; NEW_LINE DEDENT DEDENT DEDENT result = str ( digit ) + result ; NEW_LINE temp += 1 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "1345" ; NEW_LINE print ( generateNumber ( S ) ) ; NEW_LINE DEDENT |
Find the single digit sum of alphabetical values of a string | Python program for the above approach ; Traverse the given string ; If character is an alphabet ; Stores the sum of order of values ; Find the score ; Find the single digit sum ; Return the resultant sum ; Driver Code | def findTheSum ( str ) : NEW_LINE INDENT alpha = " " NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if ( ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) or ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) ) : NEW_LINE INDENT alpha += str [ i ] NEW_LINE DEDENT DEDENT score = 0 NEW_LINE n = 0 NEW_LINE for i in range ( 0 , len ( alpha ) ) : NEW_LINE INDENT if ( alpha [ i ] >= ' A ' and alpha [ i ] <= ' Z ' ) : NEW_LINE INDENT score += ord ( alpha [ i ] ) - ord ( ' A ' ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT score += ord ( alpha [ i ] ) - ord ( ' a ' ) + 1 NEW_LINE DEDENT DEDENT while ( score > 0 or n > 9 ) : NEW_LINE INDENT if ( score == 0 ) : NEW_LINE INDENT score = n NEW_LINE n = 0 NEW_LINE DEDENT n += score % 10 NEW_LINE score = score // 10 NEW_LINE DEDENT return n NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " GeeksforGeeks " NEW_LINE print ( findTheSum ( S ) ) NEW_LINE DEDENT |
Minimum value of K such that each substring of size K has the given character | Function to find the minimum value of K such that char c occurs in all K sized substrings of string S ; Store the string length ; Store difference of lengths of segments of every two consecutive occurrences of c ; Stores the maximum difference ; Store the previous occurence of char c ; Check if the current character is c or not ; Stores the difference of consecutive occurrences of c ; Update previous occurrence of c with current occurence ; Comparing diff with max ; If string doesn 't contain c ; Return max ; Driver Code | def findK ( s , c ) : NEW_LINE INDENT n = len ( s ) NEW_LINE diff = 0 NEW_LINE max = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == c ) : NEW_LINE INDENT diff = i - prev NEW_LINE prev = i NEW_LINE if ( diff > max ) : NEW_LINE INDENT max = diff NEW_LINE DEDENT DEDENT DEDENT if ( max == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " abdegb " NEW_LINE ch = ' b ' NEW_LINE print ( findK ( S , ch ) ) NEW_LINE DEDENT |
Count subsequences 01 in string generated by concatenation of given numeric string K times | Function to calculate the number of subsequences of "01" ; Store count of 0 ' s β and β 1' s ; Count of subsequences without concatenation ; Case 1 ; Case 2 ; Return the total count ; Driver Code | def countSubsequence ( S , N , K ) : NEW_LINE INDENT C = 0 NEW_LINE C1 = 0 NEW_LINE C0 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT C1 += 1 NEW_LINE DEDENT elif ( S [ i ] == '0' ) : NEW_LINE INDENT C0 += 1 NEW_LINE DEDENT DEDENT B1 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT B1 += 1 NEW_LINE DEDENT elif ( S [ i ] == '0' ) : NEW_LINE INDENT C = C + ( C1 - B1 ) NEW_LINE DEDENT DEDENT ans = C * K NEW_LINE ans += ( C1 * C0 * ( ( ( K ) * ( K - 1 ) ) // 2 ) ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "230013110087" NEW_LINE K = 2 NEW_LINE N = len ( S ) NEW_LINE print ( countSubsequence ( S , N , K ) ) NEW_LINE DEDENT |
Count of distinct groups of strings formed after performing equivalent operation | Function to perform the find operation to find the parent of a disjoint set ; Function to perform union operation of disjoint set union ; Find the parent of node a and b ; Update the rank ; Function to find the number of distinct strings after performing the given operations ; Stores the parent elements of the sets ; Stores the rank of the sets ; Update parent [ i ] to i ; Stores the total characters traversed through the strings ; Stores the current characters traversed through a string ; Update current [ i ] to false ; Update current [ ch - ' a ' ] to true ; Check if current [ j ] is true ; Update total [ j ] to true ; Add arr [ i ] [ 0 ] - ' a ' and j elements to same set ; Stores the count of distinct strings ; Check total [ i ] is true and parent of i is i only ; Increment the value of distCount by 1 ; Print the value of distCount ; Driver Code | def Find ( parent , a ) : NEW_LINE INDENT if parent [ a ] == a : NEW_LINE INDENT parent [ a ] = a NEW_LINE return parent [ a ] NEW_LINE DEDENT else : NEW_LINE INDENT parent [ a ] = Find ( parent , parent [ a ] ) NEW_LINE return parent [ a ] NEW_LINE DEDENT DEDENT def Union ( parent , rank , a , b ) : NEW_LINE INDENT a = Find ( parent , a ) NEW_LINE b = Find ( parent , b ) NEW_LINE if ( rank [ a ] == rank [ b ] ) : NEW_LINE INDENT rank [ a ] += 1 NEW_LINE DEDENT if ( rank [ a ] > rank [ b ] ) : NEW_LINE INDENT parent [ b ] = a NEW_LINE DEDENT else : NEW_LINE INDENT parent [ a ] = b NEW_LINE DEDENT DEDENT def numOfDistinctStrings ( arr , N ) : NEW_LINE INDENT parent = [ 0 for _ in range ( 27 ) ] NEW_LINE rank = [ 0 for _ in range ( 27 ) ] NEW_LINE for j in range ( 0 , 27 ) : NEW_LINE INDENT parent [ j ] = j NEW_LINE DEDENT total = [ False for _ in range ( 26 ) ] NEW_LINE current = [ False for _ in range ( 26 ) ] NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , 26 ) : NEW_LINE INDENT current [ j ] = False NEW_LINE DEDENT for ch in arr [ i ] : NEW_LINE INDENT current [ ord ( ch ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for j in range ( 0 , 26 ) : NEW_LINE INDENT if ( current [ j ] ) : NEW_LINE INDENT total [ j ] = True NEW_LINE Union ( parent , rank , ord ( arr [ i ] [ 0 ] ) - ord ( ' a ' ) , j ) NEW_LINE DEDENT DEDENT DEDENT distCount = 0 NEW_LINE for i in range ( 0 , 26 ) : NEW_LINE INDENT if ( total [ i ] and Find ( parent , i ) == i ) : NEW_LINE INDENT distCount += 1 NEW_LINE DEDENT DEDENT print ( distCount ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " a " , " ab " , " b " , " d " ] NEW_LINE N = len ( arr ) NEW_LINE numOfDistinctStrings ( arr , N ) NEW_LINE DEDENT |
Minimum adjacent swaps required to make a binary string alternating | Function to find the minimum number of adjacent swaps to make the string alternating ; Count the no of zeros and ones ; Base Case ; Store no of min swaps when string starts with "1" ; Keep track of the odd positions ; Checking for when the string starts with "1" ; Adding the no of swaps to fix "1" at odd positions ; Store no of min swaps when string starts with "0" ; Keep track of the odd positions ; Checking for when the string starts with "0" ; Adding the no of swaps to fix "1" at odd positions ; Returning the answer based on the conditions when string length is even ; When string length is odd ; When no of ones is greater than no of zeros ; When no of ones is greater than no of zeros ; Driver Code | def minSwaps ( s ) : NEW_LINE INDENT ones = 0 NEW_LINE zeros = 0 NEW_LINE N = len ( s ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if s [ i ] == '1' : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zeros += 1 NEW_LINE DEDENT DEDENT if ( ( N % 2 == 0 and ones != zeros ) or ( N % 2 == 1 and abs ( ones - zeros ) != 1 ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans_1 = 0 NEW_LINE j = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT ans_1 += abs ( j - i ) NEW_LINE j += 2 NEW_LINE DEDENT DEDENT ans_0 = 0 NEW_LINE k = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT ans_0 += abs ( k - i ) NEW_LINE k += 2 NEW_LINE DEDENT DEDENT if ( N % 2 == 0 ) : NEW_LINE INDENT return min ( ans_1 , ans_0 ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( ones > zeros ) : NEW_LINE INDENT return ans_1 NEW_LINE DEDENT else : NEW_LINE INDENT return ans_0 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "110100" NEW_LINE print ( minSwaps ( S ) ) NEW_LINE DEDENT |
Print all ways to reach the Nth stair with the jump of 1 or 2 units at a time | Function to find all the ways to reach Nth stair using one or two jumps ; Base Cases ; Recur for jump1 and jump2 ; Stores the total possible jumps ; Add "1" with every element present in jump1 ; Add "2" with every element present in jump2 ; Driver Code | def TotalPossibleJumps ( N ) : NEW_LINE INDENT if ( ( N - 1 ) == 0 ) : NEW_LINE INDENT newvec = [ ] NEW_LINE newvec . append ( " " ) NEW_LINE return newvec NEW_LINE DEDENT else : NEW_LINE INDENT if ( N < 0 ) : NEW_LINE INDENT newvec = [ ] NEW_LINE return newvec NEW_LINE DEDENT DEDENT jump1 = TotalPossibleJumps ( N - 1 ) NEW_LINE jump2 = TotalPossibleJumps ( N - 2 ) NEW_LINE totaljumps = [ ] NEW_LINE for s in jump1 : NEW_LINE INDENT totaljumps . append ( "1" + s ) NEW_LINE DEDENT for s in jump2 : NEW_LINE INDENT totaljumps . append ( "2" + s ) NEW_LINE DEDENT return totaljumps NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE Ans = TotalPossibleJumps ( N ) NEW_LINE for it in Ans : NEW_LINE INDENT print ( it ) NEW_LINE DEDENT DEDENT |
Find any permutation of Binary String of given size not present in Array | Function to find a binary string of N bits that does not occur in the givrn array arr [ ] ; Stores the resultant string ; Loop to iterate over all the given strings in a diagonal order ; Append the complement of element at current index into ans ; Return Answer ; Driver code | def findString ( arr , N ) : NEW_LINE INDENT ans = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans += '1' if arr [ i ] [ i ] == '0' else '0' NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ "111" , "011" , "001" ] NEW_LINE N = len ( arr ) NEW_LINE print ( findString ( arr , N ) ) NEW_LINE DEDENT |
Check if the string has a reversible equal substring at the ends | Function to print longest substring that appears at beginning of string and also at end in reverse order ; Stores the resultant string ; If the characters are same ; Otherwise , break ; If the string can 't be formed ; Otherwise print resultant string ; Driver Code | def commonSubstring ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE ans = " " NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE i = i + 1 NEW_LINE j = j - 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( len ( ans ) == 0 ) : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " True " ) NEW_LINE print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " abca " NEW_LINE commonSubstring ( S ) NEW_LINE DEDENT |
Length of Smallest Non Prime Subsequence in given numeric String | Function to find the smallest length of resultant subsequence ; Check for a subsequence of size 1 ; Check for a subsequence of size 2 ; If none of the above check is successful then subsequence must be of size 3 ; Never executed ; Driver Code | def findMinimumSubsequence ( S ) : NEW_LINE INDENT flag = False NEW_LINE dummy = ' ' NEW_LINE for j in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ j ] != '2' and S [ j ] != '3' and S [ j ] != '5' and S [ j ] != '7' ) : NEW_LINE INDENT print ( 1 ) NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT for j in range ( len ( S ) ) : NEW_LINE INDENT for j1 in range ( j + 1 , len ( S ) , 1 ) : NEW_LINE INDENT dummy = S [ j ] + S [ j1 ] NEW_LINE if ( dummy != "23" and dummy != "37" and dummy != "53" and dummy != "73" ) : NEW_LINE INDENT print ( 2 ) NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE DEDENT DEDENT if ( flag == True ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT if ( len ( S ) >= 3 ) : NEW_LINE INDENT print ( 3 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "237" NEW_LINE findMinimumSubsequence ( S ) NEW_LINE DEDENT |
Minimize changes to make all characters equal by changing vowel to consonant and vice versa | Python 3 program for the above approach ; Function to find the minimum number of steps to make all characters equal ; Initializing the variables ; Store the frequency ; Iterate over the string ; Calculate the total number of vowels ; Storing frequency of each vowel ; Count the consonants ; Storing the frequency of each consonant ; Iterate over the 2 maps ; Maximum frequency of consonant ; Maximum frequency of vowel ; Find the result ; Driver Code | import sys NEW_LINE from collections import defaultdict NEW_LINE def operations ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE vowels = 0 NEW_LINE consonants = 0 NEW_LINE max_vowels = - sys . maxsize - 1 NEW_LINE max_consonants = - sys . maxsize - 1 NEW_LINE freq_consonants = defaultdict ( int ) NEW_LINE freq_vowels = defaultdict ( int ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) : NEW_LINE INDENT vowels += 1 NEW_LINE freq_vowels [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT consonants += 1 NEW_LINE freq_consonants [ s [ i ] ] += 1 NEW_LINE DEDENT DEDENT for it in freq_consonants : NEW_LINE INDENT max_consonants = max ( max_consonants , freq_consonants [ it ] ) NEW_LINE DEDENT for it in freq_vowels : NEW_LINE INDENT max_vowels = max ( max_vowels , freq_vowels [ it ] ) NEW_LINE DEDENT ans = min ( ( 2 * ( vowels - max_vowels ) + consonants ) , ( 2 * ( consonants - max_vowels ) + consonants ) ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE print ( operations ( S ) ) NEW_LINE DEDENT |
Count of ways to empty given String by recursively removing all adjacent duplicates | Python3 implementation for the above approach ; Define the dp table globally ; Recursive function to calculate the dp values for range [ L , R ] ; The range is odd length ; The state is already calculated ; If the length is 2 ; Total answer for this state ; Variable to store the current answer . ; Remove characters s [ l ] and s [ i ] . ; Initialize all the states of dp to - 1 memset ( dp , - 1 , sizeof ( dp ) ) ; ; Calculate all Combinations ; Driver Code | import numpy as np NEW_LINE dp = np . zeros ( ( 505 , 505 ) ) ; NEW_LINE choose = np . zeros ( ( 502 , 502 ) ) ; NEW_LINE def calc ( l , r , s ) : NEW_LINE INDENT if ( abs ( r - l ) % 2 == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( l > r ) : NEW_LINE INDENT dp [ l ] [ r ] = 1 ; NEW_LINE return dp [ l ] [ r ] NEW_LINE DEDENT if ( dp [ l ] [ r ] != - 1 ) : NEW_LINE INDENT return dp [ l ] [ r ] ; NEW_LINE DEDENT if ( ( r - l ) == 1 ) : NEW_LINE INDENT if ( s [ l ] == s [ r ] ) : NEW_LINE INDENT dp [ l ] [ r ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ l ] [ r ] = 0 ; NEW_LINE DEDENT return dp [ l ] [ r ] ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for k in range ( l + 1 , r + 1 , 2 ) : NEW_LINE INDENT temp = 1 ; NEW_LINE if ( s [ l ] == s [ k ] ) : NEW_LINE INDENT temp = calc ( l + 1 , k - 1 , s ) * calc ( k + 1 , r , s ) * choose [ ( r - l + 1 ) // 2 ] [ ( r - k ) // 2 ] ; NEW_LINE ans += temp ; NEW_LINE DEDENT DEDENT dp [ l ] [ r ] = ans ; NEW_LINE return dp [ l ] [ r ] NEW_LINE DEDENT def waysToClearString ( S ) : NEW_LINE INDENT for i in range ( 505 ) : NEW_LINE INDENT for j in range ( 505 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT n = len ( S ) ; NEW_LINE choose [ 0 ] [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , ( n // 2 ) + 1 ) : NEW_LINE INDENT choose [ i ] [ 0 ] = 1 ; NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT choose [ i ] [ j ] = choose [ i - 1 ] [ j ] + choose [ i - 1 ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT return calc ( 0 , n - 1 , S ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aabccb " ; NEW_LINE print ( waysToClearString ( S ) ) ; NEW_LINE DEDENT |
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation | Function to check for valid subsequences ; Stores which element belongs to which subsequence ; Check for each pos if a possible subsequence exist or not ; Last member of 1 subsequence ; Last Member of 2 nd subsequence ; Check if current element can go to 2 nd subsequence ; Check if the current elements belongs to first subsequence ; If the current element does not belong to any subsequence ; Check if last digit of first subsequence is greater than pos ; If a subsequence is found , find the subsequences ; Stores the resulting subsequences ; Print the subsequence ; If no subsequence found , print - 1 ; Driver Code | def findSubsequence ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = [ '0' for i in range ( n ) ] NEW_LINE for pos in range ( 10 ) : NEW_LINE INDENT lst1 = '0' NEW_LINE flag = 1 NEW_LINE lst2 = chr ( pos + 48 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( lst2 <= str [ i ] ) : NEW_LINE INDENT res [ i ] = '2' NEW_LINE lst2 = str [ i ] NEW_LINE DEDENT elif ( lst1 <= str [ i ] ) : NEW_LINE INDENT res [ i ] = '1' NEW_LINE lst1 = str [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( lst1 > chr ( pos + 48 ) ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT S1 = " " NEW_LINE S2 = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( res [ i ] == '1' ) : NEW_LINE INDENT S1 += str [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT S2 += str [ i ] NEW_LINE DEDENT DEDENT print ( S1 , S2 ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " - 1" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "040425524644" NEW_LINE findSubsequence ( S ) NEW_LINE S = "123456789" NEW_LINE findSubsequence ( S ) NEW_LINE DEDENT |
Find Kth lexicographical ordered numeric string of length N with distinct products of each substring | Java program for the above approach ; Function to find the required String ; If the current length is equal to n exit from here only ; Iterate for all the characters ; Check if the product is present before ; If the current String is good then recurse for the next character ; Decrease all the products back to their original state ; Erase the last character ; Function to calculate kth ordered valid String ; Check for the base cases ; There are atmost 10 valid Strings for n = 1 ; Vector to keep a check on number of occurences of products ; Recursively construct the Strings ; Driver Code | s = ' ' NEW_LINE K = 0 NEW_LINE def getString ( curlen , N , prod ) : NEW_LINE INDENT global s , K NEW_LINE if ( curlen == N ) : NEW_LINE INDENT K -= 1 NEW_LINE if ( K == 0 ) : NEW_LINE INDENT ans = s NEW_LINE DEDENT return NEW_LINE DEDENT ch = '2' NEW_LINE while ( ch <= '9' ) : NEW_LINE INDENT s = chr ( ord ( s ) + ord ( ch ) ) NEW_LINE ok = 1 NEW_LINE t = 1 NEW_LINE i = curlen NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE while ( i >= 0 and len ( s ) ) : NEW_LINE INDENT t *= ord ( s [ i ] ) - 48 NEW_LINE if ( prod [ t ] != 0 ) : NEW_LINE INDENT ok = 0 NEW_LINE DEDENT prod [ t ] += 1 NEW_LINE i -= 1 NEW_LINE DEDENT if ( ok != 0 ) : NEW_LINE INDENT getString ( curlen + 1 , N , prod ) NEW_LINE DEDENT t = 1 NEW_LINE i = curlen NEW_LINE while ( i >= 0 and len ( s ) > i ) : NEW_LINE INDENT i -= 1 NEW_LINE t *= ord ( s [ i ] ) - 48 NEW_LINE prod [ t ] -= 1 NEW_LINE DEDENT if ( len ( s ) > 0 ) : NEW_LINE INDENT s = s [ 0 : len ( s ) - 1 ] NEW_LINE DEDENT DEDENT DEDENT def kthValidString ( N ) : NEW_LINE INDENT if ( N > 10 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT if ( K > 10 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT s = " " NEW_LINE K -= 1 NEW_LINE s += ( K + '0' ) NEW_LINE return s NEW_LINE DEDENT ans = " - 1" NEW_LINE s = " " NEW_LINE prod = [ 0 ] * 10005 NEW_LINE getString ( 0 , N , prod ) NEW_LINE return ans NEW_LINE DEDENT N = 3 NEW_LINE K = 4 NEW_LINE print ( kthValidString ( N ) ) NEW_LINE |
Minimum swaps to balance the given brackets at any index | Function to balance the given bracket by swap ; To count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; Driver code | def BalancedStringBySwapping ( s ) : NEW_LINE INDENT unbalancedPair = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( unbalancedPair > 0 and s [ i ] == ' ] ' ) : NEW_LINE INDENT unbalancedPair -= 1 ; NEW_LINE DEDENT elif ( s [ i ] == ' [ ' ) : NEW_LINE INDENT unbalancedPair += 1 ; NEW_LINE DEDENT DEDENT return ( unbalancedPair + 1 ) // 2 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : s = " ] ] ] [ [ [ " ; NEW_LINE INDENT print ( BalancedStringBySwapping ( s ) ) ; NEW_LINE DEDENT |
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice | Function of return the number of palindromic strings of length N with first K alphabets possible ; If N is odd , half + 1 position can be filled to cope with the extra middle element ; K is reduced by one , because count of choices for the next position is reduced by 1 as a element can only once ; Return the possible count ; Function to find the count of palindromic string of first K characters according to the given criteria ; If N = 1 , then only K palindromic strings possible . ; If N = 2 , the 2 * K palindromic strings possible , K for N = 1 and K for N = 2 ; Initialize ans with the count of strings possible till N = 2 ; Return the possible count ; Driver Code | def lengthNPalindrome ( N , K ) : NEW_LINE INDENT half = N // 2 ; NEW_LINE if ( N & 1 ) : NEW_LINE INDENT half += 1 ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( 1 , half + 1 ) : NEW_LINE INDENT ans *= K ; NEW_LINE K -= 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def palindromicStrings ( N , K ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return K ; NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return 2 * K ; NEW_LINE DEDENT ans = 0 ; NEW_LINE ans += ( 2 * K ) ; NEW_LINE for i in range ( 3 , N + 1 ) : NEW_LINE INDENT ans += lengthNPalindrome ( i , K ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 ; K = 3 ; NEW_LINE print ( palindromicStrings ( N , K ) ) ; NEW_LINE DEDENT |
Minimum number of characters required to be added to a String such that all lowercase alphabets occurs as a subsequence in increasing order | Python3 program for the above approach ; Function to find the LCS of strings S and string T ; Base Case ; Already Calculated State ; If the characters are the same ; Otherwise ; Function to find the minimum number of characters that needs to be appended in the string to get all lowercase alphabets as a subsequences ; String containing all the characters ; Stores the result of overlapping subproblems ; Return the minimum characters required ; Driver Code | import numpy as np NEW_LINE def LCS ( S , N , T , M , dp ) : NEW_LINE INDENT if ( N == 0 or M == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ N ] [ M ] != 0 ) : NEW_LINE INDENT return dp [ N ] [ M ] ; NEW_LINE DEDENT if ( S [ N - 1 ] == T [ M - 1 ] ) : NEW_LINE INDENT dp [ N ] [ M ] = 1 + LCS ( S , N - 1 , T , M - 1 , dp ) ; NEW_LINE return dp [ N ] [ M ] NEW_LINE DEDENT dp [ N ] [ M ] = max ( LCS ( S , N - 1 , T , M , dp ) , LCS ( S , N , T , M - 1 , dp ) ) ; NEW_LINE return dp [ N ] [ M ] NEW_LINE DEDENT def minimumCharacter ( S ) : NEW_LINE INDENT T = " abcdefghijklmnopqrstuvwxyz " ; NEW_LINE N = len ( S ) ; M = len ( T ) ; NEW_LINE dp = np . zeros ( ( N + 1 , M + 1 ) ) ; NEW_LINE return ( 26 - LCS ( S , N , T , M , dp ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " abcdadc " ; NEW_LINE print ( minimumCharacter ( S ) ) ; NEW_LINE DEDENT |
Count ways to make the number formed by K concatenations of a numeric string divisible by 5 | Python program for the above approach ; Function to find the value of a ^ b modulo 1000000007 ; Stores the resultant value a ^ b ; Find the value of a ^ b ; Function to count the number of ways such that the formed number is divisible by 5 by removing digits ; Stores the count of ways ; Find the count for string S ; If the digit is 5 or 0 ; Find the count of string for K concatenation of string S ; Find the total count ; Driver Code | MOD = 1000000007 NEW_LINE def exp_mod ( a , b ) : NEW_LINE INDENT ret = 1 NEW_LINE while ( b ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT ret = ret * a % MOD NEW_LINE DEDENT b >>= 1 NEW_LINE a = a * a % MOD NEW_LINE DEDENT return ret NEW_LINE DEDENT def countOfWays ( s , k ) : NEW_LINE INDENT N = len ( s ) NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '5' or s [ i ] == '0' ) : NEW_LINE INDENT ans = ( ans + exp_mod ( 2 , i ) ) % MOD NEW_LINE DEDENT DEDENT q = exp_mod ( 2 , N ) NEW_LINE qk = exp_mod ( q , k ) NEW_LINE inv = exp_mod ( q - 1 , MOD - 2 ) NEW_LINE ans = ans * ( qk - 1 ) % MOD NEW_LINE ans = ans * inv % MOD NEW_LINE return ans NEW_LINE DEDENT S = "1256" NEW_LINE K = 1 NEW_LINE print ( countOfWays ( S , K ) ) NEW_LINE |
Find the string present at the middle of a lexicographically increasing sequence of strings from S to T | Function to print the string at the middle of lexicographically increasing sequence of strings from S to T ; Stores the base 26 digits after addition ; Iterete from right to left and add carry to next position ; Reduce the number to find the middle string by dividing each position by 2 ; If current value is odd , carry 26 to the next index value ; Driver Code | def printMiddleString ( S , T , N ) : NEW_LINE INDENT a1 = [ 0 ] * ( N + 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT a1 [ i + 1 ] = ord ( S [ i ] ) - ord ( " a " ) + ord ( T [ i ] ) - ord ( " a " ) ; NEW_LINE DEDENT for i in range ( N , 1 , - 1 ) : NEW_LINE INDENT a1 [ i - 1 ] += a1 [ i ] // 26 ; NEW_LINE a1 [ i ] %= 26 ; NEW_LINE DEDENT for i in range ( N + 1 ) : NEW_LINE INDENT if ( a1 [ i ] & 1 ) : NEW_LINE if ( i + 1 <= N ) : NEW_LINE INDENT a1 [ i + 1 ] += 26 ; NEW_LINE DEDENT a1 [ i ] = a1 [ i ] // 2 ; NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( chr ( a1 [ i ] + ord ( " a " ) ) , end = " " ) ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT N = 5 ; NEW_LINE S = " afogk " ; NEW_LINE T = " asdji " ; NEW_LINE printMiddleString ( S , T , N ) ; NEW_LINE |
Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Python program to solve the above approach ; initializing first and second variable as to store how many string ' s ' and string ' t ' will be appended ; storing tmp length ; if length of string tmp is greater than k , then we have reached our destination string now we can return character at index k ; appending s to tmp , f times ; appending t to tmp , s times ; extracting output character ; Driver code | def KthCharacter ( s , t , k ) : NEW_LINE INDENT f = 1 NEW_LINE ss = 2 NEW_LINE tmp = " " NEW_LINE lenn = len ( tmp ) NEW_LINE while ( lenn < k ) : NEW_LINE INDENT tf = f NEW_LINE ts = ss NEW_LINE while ( tf != 0 ) : NEW_LINE INDENT tf -= 1 NEW_LINE tmp += s NEW_LINE DEDENT while ( ts != 0 ) : NEW_LINE INDENT ts -= 1 NEW_LINE tmp += t NEW_LINE DEDENT f += 2 NEW_LINE ss += 2 NEW_LINE lenn = len ( tmp ) NEW_LINE DEDENT output = tmp [ k - 1 ] NEW_LINE return output NEW_LINE DEDENT S1 = " a " NEW_LINE S2 = " bc " NEW_LINE k = 4 NEW_LINE ans = KthCharacter ( S1 , S2 , k ) NEW_LINE print ( ans ) NEW_LINE |
Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Python program to solve the above approach ; storing length ; variables for temporary strings of s and t ; final output variable ; if k is greater than even after adding string ' s ' ' first ' times ( let ' s β call β it β x ) β we ' ll subtract x from k ; incrementing first by 2 , as said in problem statement ; if k is greater than even after adding string ' t ' ' second ' times ( let ' s β call β it β y ) β we ' ll subtract y from k ; incrementing second by two as said in problem statement ; if k is smaller than y , then the character will be at position k % m . ; returning character at k index ; if k is smaller than x , then the character is at position k % n ; returning character at k index ; Driver code | def KthCharacter ( s , t , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = len ( t ) NEW_LINE first = 1 NEW_LINE second = 2 NEW_LINE output = ' ? ' NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( k > first * n ) : NEW_LINE INDENT x = first * n NEW_LINE k = k - x NEW_LINE first = first + 2 NEW_LINE if ( k > second * m ) : NEW_LINE INDENT y = second * m NEW_LINE k = k - y NEW_LINE second = second + 2 NEW_LINE DEDENT else : NEW_LINE INDENT ind = k % m NEW_LINE ind -= 1 NEW_LINE if ( ind < 0 ) : NEW_LINE INDENT ind = m - 1 NEW_LINE DEDENT output = t [ ind ] NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ind = k % n NEW_LINE ind -= 1 NEW_LINE if ( ind < 0 ) : NEW_LINE INDENT ind = n - 1 NEW_LINE DEDENT output = s [ ind ] NEW_LINE break NEW_LINE DEDENT DEDENT return output NEW_LINE DEDENT S1 = " a " NEW_LINE S2 = " bc " NEW_LINE k = 4 NEW_LINE ans = KthCharacter ( S1 , S2 , k ) NEW_LINE print ( ans ) NEW_LINE |
Count of ways to rearrange N digits and M alphabets keeping all alphabets together | Python program of the above approach ; Function to find the factorial of the given number ; Function to count ways to rearrange characters of the string such that all alphabets are adjacent . ; Stores factorial of ( N + 1 ) ; Stores factorial of ; Driver Code ; Given a and b ; Function call | import math NEW_LINE def fact ( a ) : NEW_LINE INDENT return math . factorial ( a ) NEW_LINE DEDENT def findComb ( N , M ) : NEW_LINE INDENT x = fact ( N + 1 ) NEW_LINE y = fact ( M ) NEW_LINE return ( x * y ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE M = 2 NEW_LINE print ( findComb ( N , M ) ) NEW_LINE DEDENT |
Count of camel case characters present in a given string | Function to count all the camelcase characters in the string S ; Stores the total count of camelcase characters ; Traverse the string S ; If ASCII value of character lies over the range [ 65 , 91 ] then increment the count ; Print the total count obtained ; Driver Code | def countCamelCase ( S ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( ord ( S [ i ] ) >= 65 and ord ( S [ i ] ) <= 91 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ckjkUUYII " NEW_LINE countCamelCase ( S ) NEW_LINE DEDENT |
Decode a given string by removing duplicate occurrences | Function to count the appearances of each character ; If the character is lower case ; If the character is uppercase ; If the character is a punctuation mark ; Function to decode the given encoded string ; Iterate the given string str ; Find the index of the next character to be printed ; Driver code | def findRepetition ( a ) : NEW_LINE INDENT if a <= ' z ' and a >= ' a ' : NEW_LINE INDENT return ord ( a ) - 97 NEW_LINE DEDENT elif a <= ' Z ' and a >= ' A ' : NEW_LINE INDENT return ord ( a ) - 65 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def decodeString ( str_ ) : NEW_LINE INDENT output = " " NEW_LINE i = 0 NEW_LINE while ( i < len ( str_ ) ) : NEW_LINE INDENT output += str_ [ i ] NEW_LINE i += findRepetition ( str_ [ i ] ) + 1 NEW_LINE DEDENT print ( " Decrypted β code β is β { " + output + " } " ) NEW_LINE DEDENT str_ = " abbbb β acccdddd " NEW_LINE decodeString ( str_ ) NEW_LINE |
Program to perform a letter frequency attack on a monoalphabetic substitution cipher | Function to decrypt a monoalphabetic substitution cipher using the letter frequency attack ; Stores final 5 possible deciphered plaintext ; Store the frequency of each letter in cipher text ; Stores the frequency of each letter in cipher text in descending order ; Store which alphabet is used already ; Traverse the string S ; Copy the frequency array ; Stores the string formed from concatanating the english letters in the decreasing frequency in the english language ; Sort the array in descending order ; Itearate over the range [ 0 , 5 ] ; Iterate over the range [ 0 , 26 ] ; Store the numerical equivalent of letter at ith index of array letter_frequency ; Calculate the probable shift used in monoalphabetic cipher ; Temporary string to generate one plaintext at a time ; Generate the probable ith plaintext string using the shift calculated above ; Insert whitespaces as it is ; Shift the kth letter of the cipher by x ; Add the kth calculated / shifted letter to temporary string ; Print the generated 5 possible plaintexts ; Given string ; Function Call | def printString ( S , N ) : NEW_LINE INDENT plaintext = [ None ] * 5 NEW_LINE freq = [ 0 ] * 26 NEW_LINE freqSorted = [ None ] * 26 NEW_LINE used = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] != ' β ' : NEW_LINE INDENT freq [ ord ( S [ i ] ) - 65 ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT freqSorted [ i ] = freq [ i ] NEW_LINE DEDENT T = " ETAOINSHRDLCUMWFGYPBVKJXQZ " NEW_LINE freqSorted . sort ( reverse = True ) NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT ch = - 1 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT if freqSorted [ i ] == freq [ j ] and used [ j ] == 0 : NEW_LINE INDENT used [ j ] = 1 NEW_LINE ch = j NEW_LINE break NEW_LINE DEDENT DEDENT if ch == - 1 : NEW_LINE INDENT break NEW_LINE DEDENT x = ord ( T [ i ] ) - 65 NEW_LINE x = x - ch NEW_LINE curr = " " NEW_LINE for k in range ( N ) : NEW_LINE INDENT if S [ k ] == ' β ' : NEW_LINE INDENT curr += " β " NEW_LINE continue NEW_LINE DEDENT y = ord ( S [ k ] ) - 65 NEW_LINE y += x NEW_LINE if y < 0 : NEW_LINE INDENT y += 26 NEW_LINE DEDENT if y > 25 : NEW_LINE INDENT y -= 26 NEW_LINE DEDENT curr += chr ( y + 65 ) NEW_LINE DEDENT plaintext [ i ] = curr NEW_LINE DEDENT for i in range ( 5 ) : NEW_LINE INDENT print ( plaintext [ i ] ) NEW_LINE DEDENT DEDENT S = " B β TJNQMF β NFTTBHF " NEW_LINE N = len ( S ) NEW_LINE printString ( S , N ) NEW_LINE |
Count of substrings in a Binary String that contains more 1 s than 0 s | Function to merge two partitions such that the merged array is sorted ; Counting inversions ; Function to implement merge sort ; Function to calculate number of inversions in a given array ; Calculate the number of inversions ; Return the number of inversions ; Function to count the number of substrings that contains more 1 s than 0 s ; Stores the prefix sum array ; Stores the count of valid substrings ; Driver Code ; Given Input ; Function Call | def merge ( v , left , mid , right , inversions ) : NEW_LINE INDENT temp = [ 0 for i in range ( right - left + 1 ) ] NEW_LINE i = left NEW_LINE j = mid + 1 NEW_LINE k = 0 NEW_LINE cnt = 0 NEW_LINE while ( i <= mid and j <= right ) : NEW_LINE INDENT if ( v [ i ] <= v [ j ] ) : NEW_LINE INDENT temp [ k ] = v [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT inversions += ( mid - i + 1 ) NEW_LINE temp [ k ] = v [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while ( i <= mid ) : NEW_LINE INDENT temp [ k ] = v [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( j <= right ) : NEW_LINE INDENT temp [ k ] = v [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT k = 0 NEW_LINE for a in range ( left , right + 1 , 1 ) : NEW_LINE INDENT v [ a ] = temp [ k ] NEW_LINE k += 1 NEW_LINE DEDENT DEDENT def mergeSort ( v , left , right , inversions ) : NEW_LINE INDENT if ( left < right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE mergeSort ( v , left , mid , inversions ) NEW_LINE mergeSort ( v , mid + 1 , right , inversions ) NEW_LINE merge ( v , left , mid , right , inversions ) NEW_LINE DEDENT DEDENT def CountInversions ( v ) : NEW_LINE INDENT n = len ( v ) NEW_LINE inversions = 0 NEW_LINE mergeSort ( v , 0 , n - 1 , inversions ) NEW_LINE return inversions NEW_LINE DEDENT def getSubsCount ( input ) : NEW_LINE INDENT n = len ( input ) NEW_LINE nums = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT nums [ i ] = ord ( input [ i ] ) - 48 NEW_LINE if ( nums [ i ] == 0 ) : NEW_LINE INDENT nums [ i ] = - 1 NEW_LINE DEDENT DEDENT pref = [ 0 for i in range ( n ) ] NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += nums [ i ] NEW_LINE pref [ i ] = sum NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( pref [ i ] > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT pref = pref [ : - 1 ] NEW_LINE inversions = CountInversions ( pref ) NEW_LINE ans = cnt + inversions + 1 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = "101" NEW_LINE ans = getSubsCount ( input ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Check if a string consisting only of a , b , c can be made empty by removing substring " abc " recursively | Function to check if the given string S can be made empty ; Stores the characters of the string S ; Traverse the given string ; If the character is c ; If stack size is greater than 2 ; Pop from the stack ; Top two characters in the stack should be ' b ' and ' a ' respectively ; Otherwise , print No ; If character is ' a ' or ' b ' push to stack ; If stack is empty , then print Yes . Otherwise print No ; Driver code | def canMadeEmpty ( s , n ) : NEW_LINE INDENT st = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] == ' c ' : NEW_LINE INDENT if len ( st ) >= 2 : NEW_LINE INDENT b = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE a = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE if a != ' a ' or b != ' b ' : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT st . append ( s [ i ] ) NEW_LINE DEDENT DEDENT if len ( st ) == 0 : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT s = " aabcbc " NEW_LINE n = len ( s ) NEW_LINE print ( canMadeEmpty ( s , n ) ) NEW_LINE |
Check if summation of two words is equal to target word | Function to check weather summation of two words equal to target word ; Store the length of each string ; Reverse the strings A , B and C ; Stores the remainder ; Iterate in the range [ 0 , max ( L , max ( M , N ) ) ] ; Stores the integer at ith position from the right in the sum of A and B ; If i is less than L ; If i is less than M ; Update rem and curr ; If i is less than N and curr is not equal to C [ i ] - ' a ' , return " No " ; If rem is greater than 0 , return " No " ; Otherwise , return " Yes " ; Driver Code ; Given Input ; Function Call | def isSumEqual ( A , B , C ) : NEW_LINE INDENT L = len ( A ) NEW_LINE M = len ( B ) NEW_LINE N = len ( A ) NEW_LINE A = A [ : : - 1 ] NEW_LINE B = B [ : : - 1 ] NEW_LINE C = C [ : : - 1 ] NEW_LINE rem = 0 NEW_LINE for i in range ( max ( L , max ( M , N ) ) ) : NEW_LINE INDENT curr = rem NEW_LINE if ( i < L ) : NEW_LINE INDENT curr += ord ( A [ i ] ) - ord ( ' a ' ) NEW_LINE DEDENT if ( i < M ) : NEW_LINE INDENT curr += ord ( B [ i ] ) - ord ( ' a ' ) NEW_LINE DEDENT rem = curr // 10 NEW_LINE curr %= 10 NEW_LINE if ( i < N and curr != ord ( C [ i ] ) - ord ( ' a ' ) ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT if ( rem ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT else : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " acb " NEW_LINE B = " cba " NEW_LINE C = " cdb " NEW_LINE print ( isSumEqual ( A , B , C ) ) NEW_LINE DEDENT |
Minimum K such that every substring of length at least K contains a character c | Set | Function to find minimum value of K such that there exist atleast one K amazing character ; Stores the answer ; Update the S ; Iterate over the characters in range [ a , z ] ; Stores the last index where c appears ; Stores the maximum possible length ; Update S ; Iterate over characters of string S ; If S [ i ] is equal to c ; Stores the distance between positions of two same c ; Update max_len ; Update the value of prev ; Update the value of ans ; Return the answer ; Driver Code ; Given Input ; Function Call | def MinimumLengthSubstring ( S , N ) : NEW_LINE INDENT ans = N NEW_LINE S = "0" + S + "0" NEW_LINE S = [ i for i in S ] NEW_LINE for c in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT prev = 0 NEW_LINE max_len = 0 NEW_LINE S [ 0 ] = chr ( c ) NEW_LINE S [ N + 1 ] = chr ( c ) NEW_LINE for i in range ( 1 , N + 2 ) : NEW_LINE INDENT if ( S [ i ] == chr ( c ) ) : NEW_LINE INDENT len = i - prev NEW_LINE max_len = max ( max_len , len ) NEW_LINE prev = i NEW_LINE DEDENT DEDENT ans = min ( ans , max_len ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcde " NEW_LINE N = len ( S ) NEW_LINE print ( MinimumLengthSubstring ( S , N ) ) NEW_LINE DEDENT |
Minimize hamming distance in Binary String by setting only one K size substring bits | Function to find minimum Hamming Distance after atmost one operation ; Store the size of the string ; Store the prefix sum of 1 s ; Create Prefix Sum array ; Initialize cnt as number of ones in string S ; Store the required result ; Traverse the string , S ; Store the number of 1 s in the substring S [ i , i + K - 1 ] ; Update the answer ; Return the result ; Driver Code ; Given Input ; Function Call | def minimumHammingDistance ( S , K ) : NEW_LINE INDENT n = len ( S ) NEW_LINE pref = [ 0 ] * n NEW_LINE pref [ 0 ] = ord ( S [ 0 ] ) - ord ( '0' ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + ( ord ( S [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT cnt = pref [ n - 1 ] NEW_LINE ans = cnt NEW_LINE for i in range ( n - K ) : NEW_LINE INDENT value = pref [ i + K - 1 ] - ( pref [ i - 1 ] if ( i - 1 ) >= 0 else 0 ) NEW_LINE ans = min ( ans , cnt - value + ( K - value ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "101" NEW_LINE K = 2 NEW_LINE print ( minimumHammingDistance ( s , K ) ) NEW_LINE DEDENT |
Check if a permutation of S2 can be obtained by adding or removing characters from S1 | Python 3 program for the above approach ; Function to check if the given number is prime or not ; If the number is less than 2 ; If the number is 2 ; If N is a multiple of 2 ; Otherwise , check for the odds values ; Function to check if S1 can be a permutation of S2 by adding or removing characters from S1 ; Initialize a frequency array ; Decrement the frequency for occurrence in s1 ; Increment the frequency for occurence in s2 ; If frequency of current char is same in s1 and s2 ; Check the frequency for the current char is not prime ; Print the result ; Driver Code | from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def checkPermutation ( s1 , s2 ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for ch in s1 : NEW_LINE INDENT if ord ( ch ) - 97 in freq : NEW_LINE INDENT freq [ ord ( ch ) - 97 ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ ord ( ch ) - 97 ] = 1 NEW_LINE DEDENT DEDENT for ch in s2 : NEW_LINE INDENT if ord ( ch ) - 97 in freq : NEW_LINE INDENT freq [ ord ( ch ) - 97 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ ord ( ch ) - 97 ] = 1 NEW_LINE DEDENT DEDENT isAllChangesPrime = True NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( isPrime ( abs ( freq [ i ] ) ) == False ) : NEW_LINE INDENT isAllChangesPrime = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( isAllChangesPrime == False ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = " gekforgk " NEW_LINE S2 = " geeksforgeeks " NEW_LINE checkPermutation ( S1 , S2 ) NEW_LINE DEDENT |
Count ways to split a string into two subsets that are reverse of each other | Function to find the total number of ways to partitiaon the string into two subset satisfying the conditions ; Stores the resultant number of ways of splitting ; Iterate over the range [ 0 , 2 ^ N ] ; Traverse the string S ; If ith bit is set , then append the character S [ i ] to X ; Otherwise , append the character S [ i ] to Y ; Reverse the second string ; If X is equal to Y ; Return the total number of ways ; Driver Code | def countWays ( S , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for mask in range ( ( 1 << N ) ) : NEW_LINE INDENT X , Y = " " , " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( mask >> i & 1 ) : NEW_LINE INDENT X += S [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT Y += S [ i ] NEW_LINE DEDENT DEDENT Y = Y [ : : - 1 ] NEW_LINE if ( X == Y ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " mippiisssisssiipsspiim " NEW_LINE N = len ( S ) NEW_LINE print ( countWays ( S , N ) ) NEW_LINE DEDENT |
Check if String formed by first and last X characters of a String is a Palindrome | Function to check whether the first x characters of both string str and reversed string str are same or not ; Length of the string str ; Traverse over the string while first and last x characters are not equal ; If the current and n - k - 1 from last character are not equal ; Finally , print true ; Driver Code ; Given input ; Function Call | def isEqualSubstring ( string , x ) : NEW_LINE INDENT n = len ( string ) NEW_LINE i = 0 NEW_LINE while i < n and i < x : NEW_LINE INDENT if ( string [ i ] != string [ n - i - 1 ] ) : NEW_LINE INDENT print ( " false " ) NEW_LINE return NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( " true " ) NEW_LINE return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT string = " GeeksforGeeks " NEW_LINE x = 3 NEW_LINE isEqualSubstring ( string , x ) NEW_LINE DEDENT |
Flip the String by either swapping given characters or rotating it horizontally for Q queries | Function to find final string after applying all Queries on it ; Traverse the Queries array ; Convert A , B to zero indexing ; Query of 1 st type ; Swap ath and bth characters ; Query of 2 nd type ; Swap first N characters with last N characters ; Print answer ; Driver code ; Input ; Function call | def solve ( S , N , Queries , Q ) : NEW_LINE INDENT S = list ( S ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT T = Queries [ i ] [ 0 ] NEW_LINE A = Queries [ i ] [ 1 ] NEW_LINE B = Queries [ i ] [ 2 ] NEW_LINE A -= 1 NEW_LINE B -= 1 NEW_LINE if ( T == 1 ) : NEW_LINE INDENT temp = S [ A ] NEW_LINE S [ A ] = S [ B ] NEW_LINE S [ B ] = temp NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT temp = S [ j ] NEW_LINE S [ j ] = S [ j + N ] NEW_LINE S [ j + N ] = temp NEW_LINE DEDENT DEDENT DEDENT S = ' ' . join ( S ) NEW_LINE print ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ABCD " NEW_LINE N = len ( S ) // 2 NEW_LINE Queries = [ [ 2 , 0 , 0 ] , [ 1 , 1 , 3 ] , [ 2 , 0 , 0 ] ] NEW_LINE Q = len ( Queries ) NEW_LINE solve ( S , N , Queries , Q ) NEW_LINE DEDENT |
Minimum number of replacement done of substring "01" with "110" to remove it completely | Function to find the minimum number of replacement of "01" with "110" s . t . S doesn 't contain substring "10" ; Stores the number of operations performed ; Stores the resultant count of substrings ; Traverse the string S from end ; If the current character is 0 ; If the current character is 1 ; Print the result ; Driver Code | def minimumOperations ( S , N ) : NEW_LINE INDENT ans = 0 NEW_LINE cntOne = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT ans += cntOne NEW_LINE cntOne *= 2 NEW_LINE DEDENT else : NEW_LINE INDENT cntOne += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "001" NEW_LINE N = len ( S ) NEW_LINE minimumOperations ( S , N ) NEW_LINE DEDENT |
Count different Bitwise OR values of equal length strings S1 and S2 by swapping exactly one pair of characters from the first string | Function to find the number of ways to obtain different Bitwise OR ; Stores the count of pairs t00 , t10 , t01 , t11 ; Traverse the characters of the string S1 and S2 ; Count the pair ( 0 , 0 ) ; Count the pair ( 1 , 0 ) ; Count the pair ( 1 , 1 ) ; Count the pair ( 0 , 1 ) ; Number of ways to calculate the different bitwise OR ; Print the result ; Driver Code | def differentBitwiseOR ( s1 , s2 ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE t00 = 0 NEW_LINE t10 = 0 NEW_LINE t01 = 0 NEW_LINE t11 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s1 [ i ] == '0' and s2 [ i ] == '0' ) : NEW_LINE INDENT t00 += 1 NEW_LINE DEDENT if ( s1 [ i ] == '1' and s2 [ i ] == '0' ) : NEW_LINE INDENT t10 += 1 NEW_LINE DEDENT if ( s1 [ i ] == '1' and s2 [ i ] == '1' ) : NEW_LINE INDENT t11 += 1 NEW_LINE DEDENT if ( s1 [ i ] == '0' and s2 [ i ] == '1' ) : NEW_LINE INDENT t01 += 1 NEW_LINE DEDENT DEDENT ans = t00 * t10 + t01 * t10 + t00 * t11 NEW_LINE print ( ans ) NEW_LINE DEDENT S1 = "01001" NEW_LINE S2 = "11011" NEW_LINE differentBitwiseOR ( S1 , S2 ) NEW_LINE |
Flip all 0 s in given Binary Strings K times with different neighbours | Function to modify the given string K number of times by flipping 0 s having different adjacent characters ; Size of the string ; Stores modified string after each iteration ; Iterate over the range [ 0 k ] ; Traverse the string S ; If '0' is present at 0 th index then replace it with 1 st index ; If '0' is present at the last index then replace it with last index - 1 character ; Otherwise , convert 0 s to 1 if the adjacent characters are different ; If during this iteration there is no change in the string then break this loop ; Update the string S ; Print the updated string ; Driver Code | def convertString ( S , k ) : NEW_LINE INDENT n = len ( S ) NEW_LINE temp = S NEW_LINE temp = list ( temp ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT if ( j == 0 and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = S [ j + 1 ] NEW_LINE DEDENT elif ( j == n - 1 and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = S [ j - 1 ] NEW_LINE DEDENT elif ( S [ j - 1 ] != S [ j + 1 ] and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = '1' NEW_LINE DEDENT DEDENT if ( S == temp ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = ' ' . join ( temp ) NEW_LINE S = temp NEW_LINE DEDENT print ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "10010001" NEW_LINE K = 1 NEW_LINE convertString ( S , K ) NEW_LINE DEDENT |
Minimum number of removals required such that no subsequence of length 2 occurs more than once | Function to remove the minimum count of characters from the string such that no subsequence of length 2 repeats ; Initialize the final string ; Stores if any character occurs in the final string or not ; Store the index of the last character added in the string ; Traverse the string ; Add all the unique characters ; Check if S [ 0 ] appears in the range [ pos + 1 , N - 1 ] ; If the characters are the same ; Print the resultant string ; Driver Code | def RemoveCharacters ( s ) : NEW_LINE INDENT ans = " " NEW_LINE c = [ 0 for i in range ( 26 ) ] NEW_LINE pos = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( c [ ord ( s [ i ] ) - 97 ] == 0 ) : NEW_LINE INDENT c [ ord ( s [ i ] ) - 97 ] = 1 NEW_LINE pos = i NEW_LINE ans += s [ i ] NEW_LINE DEDENT DEDENT for i in range ( pos + 1 , len ( s ) , 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ 0 ] ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcaadbcd " NEW_LINE RemoveCharacters ( S ) NEW_LINE DEDENT |
Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K | Function to check if a numeric string can be split into substrings such that the difference between the consecutive substrings is K ; Stores the size of the string ; Iterate over the range [ 1 , N ] and try each possible starting number ; Convert the number to string ; Build up a sequence starting with the number ; Compare it with the original string s ; Print the result ; Driver Code | def isPossible ( s , K ) : NEW_LINE INDENT valid = False NEW_LINE firstx = - 1 NEW_LINE n = len ( s ) NEW_LINE for i in range ( 1 , n // 2 + 1 , 1 ) : NEW_LINE INDENT x = int ( s [ 0 : i ] ) NEW_LINE firstx = x NEW_LINE test = str ( x ) NEW_LINE while ( len ( test ) < len ( s ) ) : NEW_LINE INDENT x -= K NEW_LINE test += str ( x ) NEW_LINE DEDENT if ( test == s ) : NEW_LINE INDENT valid = True NEW_LINE break NEW_LINE DEDENT DEDENT print ( " Yes " ) if valid == True else print ( " No " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "8642" NEW_LINE K = 2 NEW_LINE isPossible ( S , K ) NEW_LINE DEDENT |
Convert given Binary string S to all 1 s by changing all 0 s to 1 s in range [ i + 1 , i + K ] if S [ i ] is 1 | Function to check whether all 0 s in the string can be changed into 1 s ; Store the count of 0 s converted for the last occurrence of 1 ; Declere a stack ; Traverse the string , S ; If stack is empty ; There is no 1 that can change this 0 to 1 ; Push 1 into the stack ; The last 1 has reached its limit ; New 1 has been found which can now change at most K 0 s ; If flag is 1 , pr " YES " else pr " NO " ; Driver code ; Given Input ; Function call | def changeCharacters ( S , N , K ) : NEW_LINE INDENT flag = 1 NEW_LINE count = 0 NEW_LINE st = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if len ( st ) == 0 : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT count = 0 NEW_LINE st . append ( S [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == K ) : NEW_LINE INDENT del st [ - 1 ] NEW_LINE count = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE DEDENT DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "100100" NEW_LINE N = len ( S ) NEW_LINE K = 2 NEW_LINE changeCharacters ( S , N , K ) NEW_LINE DEDENT |
Check if all prefixes of a number is divisible by remaining count of digits | Function to check if all prefixes of a number is divisible by remaining count of digits or not ; Traverse and check divisibility for each updated number ; Update the original number ; Given Input ; Function Call | def prefixDivisble ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while n > 0 : NEW_LINE INDENT if n % i != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT n = n // 10 NEW_LINE i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT n = 52248 NEW_LINE if ( prefixDivisble ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Length of the longest substring that contains even number of vowels | Function to find the length of the longest substring having even number of vowels ; Create two hashmaps ; Keep the track of frequencies of the vowels ; Stores the maximum length ; Traverse the given string S ; If it is a vowel , then update the frequency ; Find the index of occurence of the string evenOdd in map ; Update the maximum length ; Print the maximum length ; Driver Code | def longestSubstring ( s ) : NEW_LINE INDENT indexes = { } NEW_LINE chars = { } NEW_LINE chars [ ' a ' ] = 0 NEW_LINE chars [ ' e ' ] = 1 NEW_LINE chars [ ' i ' ] = 2 NEW_LINE chars [ ' o ' ] = 3 NEW_LINE chars [ ' u ' ] = 4 NEW_LINE evenOdd = "00000" NEW_LINE evenOdd = [ i for i in evenOdd ] NEW_LINE indexes [ " " . join ( evenOdd ) ] = - 1 NEW_LINE length = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT c = s [ i ] NEW_LINE if ( c in chars ) : NEW_LINE INDENT evenOdd [ chars [ it ] ] = '1' if evenOdd [ chars [ it ] ] else '0' NEW_LINE DEDENT if ( " " . join ( evenOdd ) not in indexes ) : NEW_LINE INDENT indexes [ " " . join ( evenOdd ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT length = max ( length , i - indexes [ " " . join ( evenOdd ) ] ) NEW_LINE DEDENT DEDENT print ( length ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " bcbcbc " NEW_LINE longestSubstring ( S ) NEW_LINE DEDENT |
Minimum number whose binary form is not a subsequence of given binary string | Function to check if string str1 is a subsequence of string str2 ; Store index of str1 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 ; If matched , move ahead in str1 ; If all characters of str1 were found in str2 ; Function to find the minimum number which is not a subsequence of the given binary string in its binary form ; Store the decimal number of string , S ; Initialize the required result ; Iterate in the range [ 0 , R ] ; Convert integer i to binary string ; Check if the string is not a subsequence ; Update ans and break ; Print the required result ; Driver Code ; Function Call ; Function Call | def isSubsequence ( str1 , str2 , m , n ) : NEW_LINE INDENT j = 0 NEW_LINE i = 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( str1 [ j ] == str2 [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( j == m ) NEW_LINE DEDENT def findMinimumNumber ( s ) : NEW_LINE INDENT r = int ( s , 2 ) NEW_LINE ans = r + 1 NEW_LINE for i in range ( r + 1 ) : NEW_LINE INDENT p = " " NEW_LINE j = i NEW_LINE while ( j > 0 ) : NEW_LINE INDENT p += str ( j % 2 ) NEW_LINE j = j // 2 NEW_LINE DEDENT m = len ( p ) NEW_LINE n = len ( s ) NEW_LINE p = p [ : : - 1 ] NEW_LINE if ( isSubsequence ( p , s , m , n ) == False ) : NEW_LINE INDENT ans = i NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "10101" NEW_LINE findMinimumNumber ( s ) NEW_LINE DEDENT |
Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings | Function to calculate minimum cost to convert all the characters of S to '1 ; Stores the result ; Stores the number of groups that have 0 as characters ; Traverse the S ; If current character is '0 ; If count is greater than 0 ; Set the count to 0 ; If the last few consecutive characters are '0 ; If contains all characters as '1 ; Minimum Cost ; Driver Code ; Given Input ; Function Call | ' NEW_LINE def MinimumCost ( S , A , B ) : NEW_LINE INDENT count = 0 NEW_LINE group = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count > 0 ) : NEW_LINE INDENT group += 1 NEW_LINE DEDENT count = 0 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( count > 0 ) : NEW_LINE INDENT group += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( group == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( min ( A , B ) * ( group - 1 ) + B ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 1 NEW_LINE B = 5 NEW_LINE S = "01100" NEW_LINE MinimumCost ( S , A , B ) NEW_LINE DEDENT |
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number | Function to check if a number is prime number ; Define a flag variable ; Check for factors of num ; If factor is found , set flag to True and break out of loop ; Check if flag is True ; Function to calculate order of the number x ; Function to check whether the given number is Armstrong number or not ; If the condition satisfies ; Function to count Armstrong valued strings ; Stores the count of Armstrong valued strings ; Iterate over the list ; Store the value of the string ; Find value of the string ; Check if it an Armstrong number ; Function to count prime valued strings ; Store the count of prime valued strings ; Iterate over the list ; Store the value of the string ; Find value of the string ; Check if it is a Prime Number ; Driver code ; Function Call | def isPrime ( num ) : NEW_LINE INDENT flag = False NEW_LINE if num > 1 : NEW_LINE INDENT for i in range ( 2 , num ) : NEW_LINE INDENT if ( num % i ) == 0 : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if flag : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def order ( x ) : NEW_LINE INDENT n = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT n = n + 1 NEW_LINE x = x // 10 NEW_LINE DEDENT return n NEW_LINE DEDENT def isArmstrong ( x ) : NEW_LINE INDENT n = order ( x ) NEW_LINE temp = x NEW_LINE sum1 = 0 NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT r = temp % 10 NEW_LINE sum1 = sum1 + r ** n NEW_LINE temp = temp // 10 NEW_LINE DEDENT return ( sum1 == x ) NEW_LINE DEDENT def count_armstrong ( li ) : NEW_LINE INDENT c = 0 NEW_LINE for ele in li : NEW_LINE INDENT val = 0 NEW_LINE for che in ele : NEW_LINE INDENT val += ord ( che ) NEW_LINE DEDENT if isArmstrong ( val ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT def count_prime ( li ) : NEW_LINE INDENT c = 0 NEW_LINE for ele in li : NEW_LINE INDENT val = 0 NEW_LINE for che in ele : NEW_LINE INDENT val += ord ( che ) NEW_LINE DEDENT if isPrime ( val ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT arr = [ " geeksforgeeks " , " a " , " computer " , " science " , " portal " , " for " , " geeks " ] NEW_LINE print ( " Number β of β Armstrong β Strings β are : " , count_armstrong ( arr ) ) NEW_LINE print ( " Number β of β Prime β Strings β are : " , count_prime ( arr ) ) NEW_LINE |
Minimize cost of flipping or swaps to make a Binary String balanced | Function to find the minimum cost to convert the given into balanced string ; Stores count of 1 ' s β and β 0' s in the string ; Traverse the string ; Increment count1 ; Increment count 0 ; Stores absolute difference of counts of 0 ' s β and β 1' s ; If consists of only 0 ' s β and β 1' s ; Print the minimum cost ; Driver Code | def findMinimumCost ( s , N ) : NEW_LINE INDENT count_1 , count_0 = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT DEDENT k = abs ( count_0 - count_1 ) NEW_LINE if ( count_1 == N or count_0 == N ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( k // 2 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "110110" NEW_LINE N = len ( S ) NEW_LINE findMinimumCost ( S , N ) NEW_LINE DEDENT |
Minimum time required to complete all tasks with alteration of their order allowed | Python3 program for the above approach ; Function to find the minimum time required to complete the tasks if the order of tasks can be changed ; If there is no task , print 0 ; Store the maximum occurring character and its frequency ; Stores the frequency of each character ; Traverse the string S ; Increment the frequency of the current character ; Update maxfreq and maxchar ; Store the number of empty slots ; Traverse the hashmap , um ; Fill the empty slots ; Store the required result ; Print the result ; Driver Code | import sys NEW_LINE from collections import defaultdict NEW_LINE def findMinimumTime ( S , N , K ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT maxfreq = - sys . maxsize NEW_LINE um = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT um [ S [ i ] ] += 1 NEW_LINE if ( um [ S [ i ] ] > maxfreq ) : NEW_LINE INDENT maxfreq = um [ S [ i ] ] NEW_LINE maxchar = S [ i ] NEW_LINE DEDENT DEDENT emptySlots = ( maxfreq - 1 ) * K NEW_LINE for it in um : NEW_LINE INDENT if ( it == maxchar ) : NEW_LINE INDENT continue NEW_LINE DEDENT emptySlots -= min ( um [ it ] , maxfreq - 1 ) NEW_LINE DEDENT ans = N + max ( 0 , emptySlots ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " AAABBB " NEW_LINE K = 2 NEW_LINE N = len ( S ) NEW_LINE findMinimumTime ( S , N , K ) NEW_LINE DEDENT |
Check if all characters of a string can be made equal by increments or decrements | Function to check if it is possible to make all characters of string S same or not ; Length of string ; Stores the sum of ASCII value ; Traverse the string S ; Update the weightOfString ; If the sum is divisible by N then pr " Yes " ; Otherwise pr " No " ; Driver Code | def canMakeEqual ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE weightOfString = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT weightOfString += ord ( S [ i ] ) - ord ( ' a ' ) + 1 NEW_LINE DEDENT if ( weightOfString % N == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT S = " beb " NEW_LINE canMakeEqual ( S ) NEW_LINE |
Modify a string by circularly shifting each character to the right by respective frequencies | Function to replace the characters by its frequency of character in it ; Stores frequencies of characters in the string S ; Traverse the string S ; Increment the frequency of each character by 1 ; Traverse the string S ; Find the frequency of the current character ; Update the character ; Print the resultant string ; Driver Code | def addFrequencyToCharacter ( S ) : NEW_LINE INDENT frequency = [ 0 for i in range ( 26 ) ] NEW_LINE N = len ( S ) NEW_LINE S = list ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT frequency [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT add = frequency [ ord ( S [ i ] ) - ord ( ' a ' ) ] % 26 NEW_LINE if ord ( S [ i ] ) + add <= ord ( ' z ' ) : NEW_LINE INDENT S [ i ] = chr ( ord ( S [ i ] ) + add ) NEW_LINE DEDENT else : NEW_LINE INDENT add = ord ( S [ i ] ) + add - ord ( ' z ' ) NEW_LINE S [ i ] = chr ( ord ( ' a ' ) + add - 1 ) NEW_LINE DEDENT DEDENT s = " " NEW_LINE print ( s . join ( S ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE addFrequencyToCharacter ( S ) NEW_LINE DEDENT |
Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | Function to find the minimum length of the string possible after removing pairs of consecutive digits ; Initialize the stack st ; Traverse the string S ; If the stack is empty ; Otherwise ; Get the top character of the stack ; If cha and top are consecutive digits ; Otherwise , push the character ch ; Print the size of the stack ; Driver Code | def minLength ( S ) : NEW_LINE INDENT st = [ ] NEW_LINE for ch in S : NEW_LINE INDENT if ( len ( st ) == 0 ) : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT else : NEW_LINE INDENT top = st [ - 1 ] NEW_LINE if ( abs ( ord ( ch ) - ord ( top ) ) == 1 ) : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT DEDENT DEDENT return len ( st ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "12213" NEW_LINE print ( minLength ( S ) ) NEW_LINE DEDENT |
Minimum time required to complete all tasks without altering their order | Function to find the minimum time required to complete tasks without changing their order ; Keeps track of the last time instant of each task ; Stores the required result ; Traverse the given string ; Check last time instant of task , if it exists before ; Increment the time if task is within the K units of time ; Update the time of the current task in the map ; Increment the time by 1 ; Print the result ; Driver Code | def findMinimumTime ( tasks , K ) : NEW_LINE INDENT map = { } NEW_LINE curr_time = 0 NEW_LINE for c in tasks : NEW_LINE INDENT if ( c in map ) : NEW_LINE INDENT if ( curr_time - map <= K ) : NEW_LINE INDENT curr_time += K - ( curr_time - map ) + 1 NEW_LINE DEDENT DEDENT map = curr_time NEW_LINE curr_time += 1 NEW_LINE DEDENT print ( curr_time ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ABACCA " NEW_LINE K = 2 NEW_LINE findMinimumTime ( S , K ) NEW_LINE DEDENT |
Check if a string is a subsequence of another string ( using Stacks ) | Function to check if target is a subsequence of string S ; Declare a stack ; Push the characters of target into the stack ; Traverse the string S in reverse ; If the stack is empty ; If S [ i ] is same as the top of the stack ; Pop the top of stack ; Stack s is empty ; Driver Code | def checkforSubsequence ( S , target ) : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( len ( target ) ) : NEW_LINE INDENT s . append ( target [ i ] ) NEW_LINE DEDENT for i in range ( len ( S ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT if ( S [ i ] == s [ - 1 ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT DEDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " KOTTAYAM " NEW_LINE target = " KOTA " NEW_LINE checkforSubsequence ( S , target ) NEW_LINE DEDENT |
Program to construct a DFA to check if a given integer is unsigned or not | Python3 program for the above approach ; Function to construct DFA as per the given conditions ; If at state 0 and a digit has occurred then set it to state 1 ; Similarly for all other states ; Function to build and connect the DFA states ; Connect all the states to the dead state ; Function call to make DFA as per the given conditions ; Function call to check whether an integer in the form of is unsigned integer or not ; Build the DFA ; Stores the current state ; Traverse the string ; If at a certain state a digit occurs then change the current state according to the DFA ; Or + / - sign ; Or decimal occurred ; Or any other character ; Or e / E or exponent sign ; State 1 , 4 , 8 will give the final answer ; Driver Code | digits , sign = "0123456789" , " + - " NEW_LINE dot , ex = " . " , " eE " NEW_LINE dfa = [ [ 0 for i in range ( 5 ) ] for i in range ( 11 ) ] NEW_LINE def makeDFA ( ) : NEW_LINE INDENT global dfa NEW_LINE dfa [ 0 ] [ 0 ] = 1 NEW_LINE dfa [ 1 ] [ 0 ] = 1 NEW_LINE dfa [ 1 ] [ 2 ] = 3 NEW_LINE dfa [ 1 ] [ 3 ] = 2 NEW_LINE dfa [ 1 ] [ 4 ] = 6 NEW_LINE dfa [ 3 ] [ 0 ] = 4 NEW_LINE dfa [ 4 ] [ 0 ] = 4 NEW_LINE dfa [ 4 ] [ 3 ] = 5 NEW_LINE dfa [ 4 ] [ 4 ] = 6 NEW_LINE dfa [ 6 ] [ 0 ] = 8 NEW_LINE dfa [ 6 ] [ 1 ] = 7 NEW_LINE dfa [ 7 ] [ 0 ] = 8 NEW_LINE dfa [ 8 ] [ 0 ] = 8 NEW_LINE dfa [ 8 ] [ 3 ] = 9 NEW_LINE DEDENT def buildDFA ( ) : NEW_LINE INDENT global dfa NEW_LINE for i in range ( 11 ) : NEW_LINE INDENT for j in range ( 5 ) : NEW_LINE INDENT dfa [ i ] [ j ] = 10 NEW_LINE DEDENT DEDENT makeDFA ( ) NEW_LINE DEDENT def checkDFA ( s ) : NEW_LINE INDENT buildDFA ( ) NEW_LINE currentstate = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] in digits ) : NEW_LINE INDENT currentstate = dfa [ currentstate ] [ 0 ] NEW_LINE DEDENT elif ( s [ i ] in sign ) : NEW_LINE INDENT currentstate = dfa [ currentstate ] [ 1 ] NEW_LINE DEDENT elif ( s [ i ] in dot ) : NEW_LINE INDENT currentstate = dfa [ currentstate ] [ 2 ] NEW_LINE DEDENT elif ( s [ i ] in ex ) : NEW_LINE INDENT currentstate = dfa [ currentstate ] [ 4 ] NEW_LINE DEDENT else : NEW_LINE INDENT currentstate = dfa [ currentstate ] [ 3 ] NEW_LINE DEDENT DEDENT if ( currentstate == 1 or currentstate == 4 or currentstate == 8 ) : NEW_LINE INDENT print ( " Unsigned β integer " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β an β unsigned β integer " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1729" NEW_LINE checkDFA ( S ) NEW_LINE DEDENT |
Convert a Mobile Numeric Keypad sequence to equivalent sentence | Function to convert mobile numeric keypad sequence into its equivalent string ; Store the mobile keypad mappings ; Traverse the str1ing str1 ; If the current character is ' . ' , then continue to the next iteration ; Stores the number of continuous clicks ; Iterate a loop to find the count of same characters ; 2 , 3 , 4 , 5 , 6 and 8 keys will have maximum of 3 letters ; 7 and 9 keys will have maximum of 4 keys ; Handle the end condition ; Check if the current pressed key is 7 or 9 ; Else , the key pressed is either 2 , 3 , 4 , 5 , 6 or 8 ; Driver Code | def printSentence ( str1 ) : NEW_LINE INDENT nums = [ " " , " " , " ABC " , " DEF " , " GHI " , " JKL " , " MNO " , " PQRS " , " TUV " , " WXYZ " ] NEW_LINE i = 0 NEW_LINE while ( i < len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] == ' . ' ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT count = 0 NEW_LINE while ( i + 1 < len ( str1 ) and str1 [ i + 1 ] and str1 [ i ] == str1 [ i + 1 ] ) : NEW_LINE INDENT if ( count == 2 and ( ( str1 [ i ] >= '2' and str1 [ i ] <= '6' ) or ( str1 [ i ] == '8' ) ) ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( count == 3 and ( str1 [ i ] == '7' or str1 [ i ] == '9' ) ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE i += 1 NEW_LINE if ( i < len ( str ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( str1 [ i ] == '7' or str1 [ i ] == '9' ) : NEW_LINE INDENT print ( nums [ ord ( str1 [ i ] ) - 48 ] [ count % 4 ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( nums [ ord ( str1 [ i ] ) - 48 ] [ count % 3 ] , end = " " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = "234" NEW_LINE printSentence ( str1 ) NEW_LINE DEDENT |
Lexicographically largest string with sum of characters equal to N | Function to construct the lexicographically largest string having sum of characters as N ; Stores the resulting string ; Iterate until N is at least 26 ; Append ' z ' to the string ans ; Decrement N by 26 ; Append character at index ( N + ' a ' ) ; Return the resultant string ; Driver Code | def getString ( N ) : NEW_LINE INDENT ans = " " NEW_LINE while ( N >= 26 ) : NEW_LINE INDENT ans += ' z ' NEW_LINE N -= 26 NEW_LINE DEDENT ans += chr ( N + ord ( ' a ' ) - 1 ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 30 NEW_LINE print ( getString ( N ) ) NEW_LINE DEDENT |
Length of all prefixes that are also the suffixes of given string | Function to find the length of all prefixes of the given that are also suffixes of the same string ; Stores the prefix string ; Traverse the S ; Add the current character to the prefix string ; Store the suffix string ; Check if both the strings are equal or not ; Driver Code | def countSamePrefixSuffix ( s , n ) : NEW_LINE INDENT prefix = " " NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT prefix += s [ i ] NEW_LINE suffix = s [ n - 1 - i : 2 * n - 2 - i ] NEW_LINE if ( prefix == suffix ) : NEW_LINE INDENT print ( len ( prefix ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ababababab " NEW_LINE N = len ( S ) NEW_LINE countSamePrefixSuffix ( S , N ) NEW_LINE DEDENT |
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | Function to count newly created pairs by swapping the first characters of any pairs of strings ; Stores the count all possible pair of strings ; Push all the strings into the Unordered Map ; Generate all possible pairs of strings from the array arr [ ] ; Store the current pair of strings ; Swap the first character ; Check if both string are not present in map ; Print the result ; Driver Code | def countStringPairs ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE s = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT s [ a [ i ] ] = s . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT p = [ i for i in a [ i ] ] NEW_LINE q = [ j for j in a [ j ] ] NEW_LINE if ( p [ 0 ] != q [ 0 ] ) : NEW_LINE INDENT p [ 0 ] , q [ 0 ] = q [ 0 ] , p [ 0 ] NEW_LINE if ( ( " " . join ( p ) not in s ) and ( " " . join ( q ) not in s ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " good " , " bad " , " food " ] NEW_LINE N = len ( arr ) NEW_LINE countStringPairs ( arr , N ) NEW_LINE DEDENT |
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times | Function to check if a valid parenthesis can be obtained by moving characters to either end at most K number of times ; Base Case 1 ; Count of ' ( ' and ') ; Base Case 2 ; Store the count of moves required to make a valid parenthesis ; Traverse the string ; Increment cnt if opening bracket has occurred ; Otherwise , decrement cnt by 1 ; Decrement cnt by 1 ; If cnt is negative ; Update the cnt ; Increment the ans ; If ans is at most K , then print Yes . Otherwise print No ; Driver Code | def minimumMoves ( s , n , k ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT countOpen = s . count ( ' ( ' ) NEW_LINE countClose = s . count ( ' ) ' ) NEW_LINE if ( countOpen != countClose ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt -= 1 NEW_LINE if ( cnt < 0 ) : NEW_LINE INDENT cnt = 0 NEW_LINE ans += 1 NEW_LINE DEDENT DEDENT DEDENT if ( ans <= k ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : S = " ) ( " NEW_LINE INDENT K = 1 NEW_LINE minimumMoves ( S , len ( S ) , K ) NEW_LINE DEDENT |
Generate a random Binary String of length N | Python3 program for the above approach ; Function to find a random number between 0 or 1 ; Generate the random number ; Return the generated number ; Function to generate a random binary string of length N ; Stores the empty string ; Iterate over the range [ 0 , N - 1 ] ; Store the random number ; Append it to the string ; Print the resulting string ; Driver Code | import random NEW_LINE def findRandom ( ) : NEW_LINE INDENT num = random . randint ( 0 , 1 ) NEW_LINE return num NEW_LINE DEDENT def generateBinaryString ( N ) : NEW_LINE INDENT S = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = findRandom ( ) NEW_LINE S += str ( x ) NEW_LINE DEDENT print ( S ) NEW_LINE DEDENT N = 7 NEW_LINE generateBinaryString ( N ) NEW_LINE |
Partition a string into palindromic strings of at least length 2 with every character present in a single string | Function to check if a string can be split into palindromic strings of at least length 2 by including every character exactly once ; Stores the frequency of each character ; Store the frequency of characters with frequencies 1 and even respectively ; Traverse the string s ; Iterate over all the characters ; If the frequency is 1 ; If frequency is even ; Print the result ; Stores the number of characters with frequency equal to 1 that are not part of a palindromic string ; Iterate over all the characters ; If o becomes less than 0 , then break out of the loop ; If frequency of the current character is > 2 and is odd ; Update the value of o ; If a single character is still remaining ; Increment o by 1 ; Set a [ i ] to 1 ; Print the result ; Driver Code | def checkPalindrome ( s ) : NEW_LINE INDENT a = [ 0 ] * 26 NEW_LINE o , e = 0 , 0 NEW_LINE for i in s : NEW_LINE INDENT a [ ord ( i ) - 97 ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT o += 1 NEW_LINE DEDENT elif ( a [ i ] % 2 == 0 and a [ i ] != 0 ) : NEW_LINE INDENT e += ( a [ i ] // 2 ) NEW_LINE DEDENT DEDENT if ( e >= o ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT o = o - e NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( o <= 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( o > 0 and a [ i ] % 2 == 1 and a [ i ] > 2 ) : NEW_LINE INDENT k = o NEW_LINE o = o - a [ i ] // 2 NEW_LINE if ( o > 0 or 2 * k + 1 == a [ i ] ) : NEW_LINE INDENT o += 1 NEW_LINE a [ i ] = 1 NEW_LINE DEDENT DEDENT DEDENT if ( o <= 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abbbaddzcz " NEW_LINE checkPalindrome ( S ) NEW_LINE DEDENT |
Maximize time by replacing ' _ ' in a given 24 Hour format time | Function to find the maximum time possible by replacing each ' _ ' with any digit ; If the first character is '_ ; If s [ 1 ] is ' _ ' or s [ 1 ] is less than 4 ; Update s [ 0 ] as 2 ; Otherwise , update s [ 0 ] = 1 ; If s [ 1 ] is equal to '_ ; If s [ 0 ] is equal to '2 ; Otherwise ; If S [ 3 ] is equal to '_ ; If s [ 4 ] is equal to '_ ; Return the modified string ; Driver Code | def maximumTime ( s ) : NEW_LINE INDENT s = list ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( s [ 0 ] == ' _ ' ) : NEW_LINE INDENT if ( ( s [ 1 ] == ' _ ' ) or ( s [ 1 ] >= '0' and s [ 1 ] < '4' ) ) : NEW_LINE INDENT s [ 0 ] = '2' NEW_LINE DEDENT else : NEW_LINE INDENT s [ 0 ] = '1' NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 1 ] == ' _ ' ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( s [ 0 ] == '2' ) : NEW_LINE INDENT s [ 1 ] = '3' NEW_LINE DEDENT else : NEW_LINE INDENT s [ 1 ] = '9' NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 3 ] == ' _ ' ) : NEW_LINE INDENT s [ 3 ] = '5' NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 4 ] == ' _ ' ) : NEW_LINE INDENT s [ 4 ] = '9' NEW_LINE DEDENT s = ' ' . join ( s ) NEW_LINE return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "0 _ : 4 _ " NEW_LINE print ( maximumTime ( S ) ) NEW_LINE DEDENT |
How to create half of the string in uppercase and the other half in lowercase ? | | import math NEW_LINE string1 = ' geeks β for β geeks ' NEW_LINE string1_len = len ( string1 ) NEW_LINE half_string = math . ceil ( string1_len / 2 ) NEW_LINE part_a = ' ' NEW_LINE part_b = ' ' NEW_LINE part_a = string1 [ : half_string ] NEW_LINE new_part_a = part_a . upper ( ) NEW_LINE part_b = string1 [ half_string : string1_len ] NEW_LINE changed_string = new_part_a + part_b NEW_LINE print ( changed_string ) NEW_LINE |
Nearest power of 2 of frequencies of each digit of a given number | Python3 program for the above approach ; Function to find the nearest power of 2 for all frequencies in the Map freq ; Traverse the Map ; Calculate log of the current array element ; Find the nearest power of 2 for the current frequency ; Function to find nearest power of 2 for frequency of each digit of num ; Length of string ; Stores the frequency of each character in the string ; Traverse the string S ; Function call to generate nearest power of 2 for each frequency ; Driver Code | from math import log2 , pow NEW_LINE def nearestPowerOfTwoUtil ( freq ) : NEW_LINE INDENT temp = { } NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT lg = int ( log2 ( value ) ) NEW_LINE a = int ( pow ( 2 , lg ) ) NEW_LINE b = int ( pow ( 2 , lg + 1 ) ) NEW_LINE if ( ( value - a ) < ( b - value ) ) : NEW_LINE INDENT temp [ ( int ( a ) ) ] = key NEW_LINE DEDENT else : NEW_LINE INDENT temp [ ( int ( b ) ) ] = key NEW_LINE DEDENT DEDENT for key , value in temp . items ( ) : NEW_LINE INDENT print ( value , " - > " , key ) NEW_LINE DEDENT DEDENT def nearestPowerOfTwo ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] in freq ) : NEW_LINE INDENT freq [ S [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ S [ i ] ] = 1 NEW_LINE DEDENT DEDENT nearestPowerOfTwoUtil ( freq ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = "16333331163" NEW_LINE nearestPowerOfTwo ( N ) NEW_LINE DEDENT |
Smallest string divisible by two given strings | Function to calculate GCD of two numbers ; Function to calculate LCM of two numbers ; Function to find the smallest string which is divisible by strings S and T ; Store the length of both strings ; Store LCM of n and m ; Temporary strings to store concatenated strings ; Concatenate s1 ( l / n ) times ; Concatenate t1 ( l / m ) times ; If s1 and t1 are equal ; Otherwise , pr - 1 ; Driver Code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def lcm ( a , b ) : NEW_LINE INDENT return ( a // gcd ( a , b ) ) * b NEW_LINE DEDENT def findSmallestString ( s , t ) : NEW_LINE INDENT n , m = len ( s ) , len ( t ) NEW_LINE l = lcm ( n , m ) NEW_LINE s1 , t1 = " " , " " NEW_LINE for i in range ( l // n ) : NEW_LINE INDENT s1 += s NEW_LINE DEDENT for i in range ( l // m ) : NEW_LINE INDENT t1 += t NEW_LINE DEDENT if ( s1 == t1 ) : NEW_LINE INDENT print ( s1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , T = " baba " , " ba " NEW_LINE findSmallestString ( S , T ) NEW_LINE DEDENT |
Minimum substring flips required to convert a Binary String to another | Function to count the minimum number of reversals required to make the given binary strings s1 and s2 same ; Stores the minimum count of reversal of substrings required ; If the length of the strings are not the same then return - 1 ; Iterate over each character ; If s1 [ i ] is not equal to s2 [ i ] ; Iterate until s1 [ i ] != s2 [ i ] ; Increment answer by 1 ; Return the resultant count of reversal of subrequired ; Driver Code ; Function Call | def canMakeSame ( s1 , s2 ) : NEW_LINE INDENT ans = - 1 NEW_LINE if ( len ( s1 ) != len ( s2 ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT N = len ( s1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT while ( i < len ( s1 ) and s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT S1 = "100001" NEW_LINE S2 = "110111" NEW_LINE print ( canMakeSame ( S1 , S2 ) ) NEW_LINE |
Count points which are revisited while following the path specified by a given string | Function to find the number of times already visited position is revisited after starting traversal from { X , Y } ; Stores the x and y temporarily ; Stores the number of times an already visited position is revisited ; Initialize hashset ; Insert the starting coordinates ; Traverse over the string ; Update the coordinates according to the current directions ; If the new { X , Y } has been visited before , then increment the count by 1 ; Otherwise ; Insert new { x , y } ; Driver Code | def count ( S , X , Y ) : NEW_LINE INDENT N = len ( S ) NEW_LINE temp_x , temp_y = 0 , 0 NEW_LINE count = 0 NEW_LINE s = { } NEW_LINE s [ ( X , Y ) ] = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp_x = X NEW_LINE temp_y = Y NEW_LINE if ( S [ i ] == ' U ' ) : NEW_LINE INDENT X += 1 NEW_LINE DEDENT elif ( S [ i ] == ' D ' ) : NEW_LINE INDENT X -= 1 NEW_LINE DEDENT elif ( S [ i ] == ' R ' ) : NEW_LINE INDENT Y += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Y -= 1 NEW_LINE DEDENT if ( ( temp_x + X , temp_y + Y ) in s ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ ( temp_x + X , temp_y + Y ) ] = 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " RDDUDL " NEW_LINE X , Y = 0 , 0 NEW_LINE print ( count ( S , X , Y ) ) NEW_LINE DEDENT |
Sum of frequencies of characters of a string present in another string | Function to find sum of frequencies of characters of S1 present in S2 ; Insert all characters of string S1 in the set ; Traverse the string S2 ; Check if X is present in bset or not ; Increment count by 1 ; Finally , print the count ; Given strings | def countTotalFrequencies ( S1 , S2 ) : NEW_LINE INDENT bset = set ( S1 ) NEW_LINE count = 0 NEW_LINE for x in S2 : NEW_LINE INDENT if x in bset : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT S1 = " geEksFOR " NEW_LINE S2 = " GeEksforgeEKS " NEW_LINE countTotalFrequencies ( S1 , S2 ) NEW_LINE |
Make a given Binary String non | Function to return the length of smallest subsequence required to be removed to make the given string non - decreasing ; Length of the string ; Count of zeros and ones ; Traverse the string ; Count minimum removals to obtain strings of the form "00000 . . . . " or "11111 . . . " ; Increment count ; Remove 1 s and remaining 0 s ; Driver Code | def min_length ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE total_zeros = 0 NEW_LINE total_ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT total_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT total_ones += 1 NEW_LINE DEDENT DEDENT ans = min ( total_zeros , total_ones ) NEW_LINE cur_zeros = 0 NEW_LINE cur_ones = 0 NEW_LINE for x in str : NEW_LINE INDENT if ( x == '0' ) : NEW_LINE INDENT cur_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cur_ones += 1 NEW_LINE DEDENT ans = min ( ans , cur_ones + ( total_zeros - cur_zeros ) ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "10011" NEW_LINE min_length ( str ) NEW_LINE DEDENT |
Print all words occurring in a sentence exactly K times | Function to print all the words occurring k times in a string ; Stores the words ; Traverse the list ; Check for count ; Print the word ; Remove from list ; Driver Code ; Given string ; Given value of K ; Function call to find all words occuring K times | def kFreqWords ( S , K ) : NEW_LINE INDENT l = list ( S . split ( " β " ) ) NEW_LINE for i in l : NEW_LINE INDENT if l . count ( i ) == K : NEW_LINE INDENT print ( i ) NEW_LINE l . remove ( i ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " banana β is β in β yellow β and β sun β flower β is β also β in β yellow " NEW_LINE K = 2 NEW_LINE kFreqWords ( S , K ) NEW_LINE DEDENT |
Check if substrings from three given strings can be concatenated to form a palindrome | Function to check if substrings from three given strings can be concatenated to form a palindrome ; Mask for S1 and S2 ; Set ( i - ' a ' ) th bit in maskA ; Set ( i - ' a ' ) th bit in maskC ; If the bitwise AND is > 0 ; Driver Code | def make_palindrome ( S1 , S2 , S3 ) : NEW_LINE INDENT maskA , maskC = 0 , 0 NEW_LINE for i in S1 : NEW_LINE INDENT maskA |= ( 1 << ( ord ( i ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT for i in S3 : NEW_LINE INDENT maskC |= ( 1 << ( ord ( i ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT if ( ( maskA & maskC ) > 0 ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT return " NO " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 , S2 , S3 = " adcb " , " bcdb " , " abe " NEW_LINE print ( make_palindrome ( S1 , S2 , S3 ) ) NEW_LINE DEDENT |
Length of longest prefix anagram which are common in given two strings | Python3 program for the above approach ; Function to check if two arrays are identical or not ; Iterate over the range [ 0 , SIZE ] ; If frequency any character is not same in both the strings ; Otherwise ; Function to find the maximum length of the required string ; Store the count of characters in str1 ; Store the count of characters in str2 ; Stores the maximum length ; Minimum length of str1 and str2 ; Increment the count of characters of str1 [ i ] in freq1 [ ] by one ; Increment the count of characters of stord ( r2 [ i ] ) in freq2 [ ] by one ; Checks if prefixes are anagram or not ; Finally prthe ans ; Driver Code ; Function Call | SIZE = 26 NEW_LINE def longHelper ( freq1 , freq2 ) : NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq1 [ i ] != freq2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def longCommomPrefixAnagram ( s1 , s2 , n1 , n2 ) : NEW_LINE INDENT freq1 = [ 0 ] * 26 NEW_LINE freq2 = [ 0 ] * 26 NEW_LINE ans = 0 NEW_LINE mini_len = min ( n1 , n2 ) NEW_LINE for i in range ( mini_len ) : NEW_LINE INDENT freq1 [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE freq2 [ ord ( s2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( longHelper ( freq1 , freq2 ) ) : NEW_LINE INDENT ans = i + 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abaabcdezzwer " NEW_LINE str2 = " caaabbttyh " NEW_LINE N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE longCommomPrefixAnagram ( str1 , str2 , N , M ) NEW_LINE DEDENT |
Lexicographic rank of a Binary String | Function to find the rank of a string ; Store the length of the string ; Stores its equivalent decimal value ; Traverse the string ; Store the number of strings of length less than N occurring before the given string ; Store the decimal equivalent number of string bin ; Store the rank in answer ; Prthe answer ; Driver Code | def findRank ( s ) : NEW_LINE INDENT N = len ( s ) ; NEW_LINE sb = " " ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT sb += str ( '0' ) ; NEW_LINE DEDENT else : NEW_LINE INDENT sb += str ( '1' ) ; NEW_LINE DEDENT DEDENT bin = str ( sb ) ; NEW_LINE X = pow ( 2 , N ) ; NEW_LINE Y = int ( bin ) ; NEW_LINE ans = X + Y - 1 ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "001" ; NEW_LINE findRank ( S ) ; NEW_LINE DEDENT |
Find the GCD of an array made up of numeric strings | Recursive function to return gcd of A and B ; Base case ; Length of A is greater ; Calculate GCD ; Store the GCD of the length of the strings ; Driver Code ; Function call | def GCD ( lena , lenb ) : NEW_LINE INDENT if ( lena == 0 ) : NEW_LINE INDENT return lenb NEW_LINE DEDENT if ( lenb == 0 ) : NEW_LINE INDENT return lena NEW_LINE DEDENT if ( lena == lenb ) : NEW_LINE INDENT return lena NEW_LINE DEDENT if ( lena > lenb ) : NEW_LINE INDENT return GCD ( lena - lenb , lenb ) NEW_LINE DEDENT return GCD ( lena , lenb - lena ) NEW_LINE DEDENT def StringGCD ( a , b ) : NEW_LINE INDENT gcd = GCD ( len ( a ) , len ( b ) ) NEW_LINE if a [ : gcd ] == b [ : gcd ] : NEW_LINE INDENT if a * ( len ( b ) // gcd ) == b * ( len ( a ) // gcd ) : NEW_LINE return a [ : gcd ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT a = ' geeksgeeks ' NEW_LINE b = ' geeks ' NEW_LINE print ( StringGCD ( a , b ) ) NEW_LINE |
Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence | Function to count minimum number of operations to convert the string to a balanced bracket sequence ; Initialize the integer array ; Traverse the string ; Decrement a [ i ] ; Increment a [ i ] ; Update the sum as current value of arr [ i ] ; If answer exists ; Traverse from i ; Find all substrings with 0 sum ; Print the sum of sizes ; No answer exists ; Driver Code | def countMinMoves ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE a = [ 0 for i in range ( n ) ] NEW_LINE j , ans , sum = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ' ) ' ) : NEW_LINE INDENT a [ i ] += sum - 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] += sum + 1 NEW_LINE DEDENT sum = a [ i ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i - 1 NEW_LINE while ( i < n and a [ i ] != 0 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( i < n and a [ i - 1 ] < 0 ) : NEW_LINE INDENT ans += i - j NEW_LINE if ( j == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : str = " ) ( ( ) " NEW_LINE INDENT countMinMoves ( str ) NEW_LINE DEDENT |
Check if a given string can be converted to a Balanced Bracket Sequence | Function to check if the can be balanced by replacing the ' $ ' with opening or closing brackets ; If string can never be balanced ; Declare 2 stacks to check if all ) can be balanced with ( or $ and vice - versa ; Store the count the occurence of ( , ) and $ ; Traverse the string ; Increment closed bracket count by 1 ; If there are no opening bracket to match it then return False ; Otherwise , pop the character from the stack ; If current character is an opening bracket or $ , push it to the stack ; Increment symbol count by 1 ; Increment open bracket count by 1 ; Traverse the string from end and repeat the same process ; If there are no closing brackets to match it ; Otherwise , pop character from stack ; Store the extra ( or ) which are not balanced yet ; Check if $ is available to balance the extra brackets ; Count ramaining $ after balancing extra ( and ) ; Check if each pair of $ is convertable in ( ) ; Driver Code ; Function Call | def canBeBalanced ( sequence ) : NEW_LINE INDENT if ( len ( sequence ) % 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT stack_ , stack2_ = [ ] , [ ] NEW_LINE countOpen , countClosed = 0 , 0 NEW_LINE countSymbol = 0 NEW_LINE for i in range ( len ( sequence ) ) : NEW_LINE INDENT if ( sequence [ i ] == ' ) ' ) : NEW_LINE INDENT countClosed += 1 NEW_LINE if ( len ( stack_ ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT del stack_ [ - 1 ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( sequence [ i ] == ' $ ' ) : NEW_LINE INDENT countSymbol += 1 NEW_LINE DEDENT else : NEW_LINE INDENT countOpen += 1 NEW_LINE DEDENT stack_ . append ( sequence [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( sequence ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( sequence [ i ] == ' ( ' ) : NEW_LINE INDENT if ( len ( stack2_ ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT del stack2_ [ - 1 ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT stack2_ . append ( sequence [ i ] ) NEW_LINE DEDENT DEDENT extra = abs ( countClosed - countOpen ) NEW_LINE if ( countSymbol < extra ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT countSymbol -= extra NEW_LINE if ( countSymbol % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ( ) ( $ " NEW_LINE if ( canBeBalanced ( S ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | Function to find difference between maximum and minimum frequency of a character in given range ; Stores length of string ; Stores count of queries ; Iterate over the characters of the string ; Stores l - value of a query ; Stores r - value of a query ; Store count of every character laying in range [ l , r ] ; Update frequency of current character ; Stores maximum frequency of characters in given range ; Stores minimum frequency of characters in given range ; Iterate over all possible characters of the given string ; Update mx ; If ( j + ' a ' ) is present ; Difference between max and min ; Driver Code ; Given string ; Given queries ; Function Call | def maxDiffFreq ( queries , S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE Q = len ( queries ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT l = queries [ i ] [ 0 ] - 1 NEW_LINE r = queries [ i ] [ 1 ] - 1 NEW_LINE freq = [ 0 ] * 26 NEW_LINE for j in range ( l , r + 1 ) : NEW_LINE INDENT freq [ ord ( S [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT mx = 0 NEW_LINE mn = 99999999 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT mx = max ( mx , freq [ j ] ) NEW_LINE if ( freq [ j ] ) : NEW_LINE INDENT mn = min ( mn , freq [ j ] ) NEW_LINE DEDENT DEDENT print ( mx - mn ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " abaabac " NEW_LINE queries = [ [ 2 , 6 ] , [ 1 , 7 ] ] NEW_LINE maxDiffFreq ( queries , S ) NEW_LINE DEDENT |
Count strings from given array having all characters appearing in a given string | Function to count the number of strings from an array having all characters appearing in the string S ; Initialize a set to store all distinct characters of S ; Traverse over S ; Insert characters into the Set ; Stores the required count ; Traverse the array ; Traverse over arr [ i ] ; Check if character in arr [ i ] [ j ] is present in the S or not ; Increment the count if all the characters of arr [ i ] are present in the S ; Finally , prthe count ; Driver code | def countStrings ( S , list ) : NEW_LINE INDENT valid = { } NEW_LINE for x in S : NEW_LINE INDENT valid [ x ] = 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( len ( list ) ) : NEW_LINE INDENT j = 0 NEW_LINE while j < len ( list [ i ] ) : NEW_LINE INDENT if ( list [ i ] [ j ] in valid ) : NEW_LINE INDENT j += 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == len ( list [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " ab " , " aab " , " abaaaa " , " bbd " ] NEW_LINE S , l = " ab " , [ ] NEW_LINE print ( countStrings ( S , arr ) ) NEW_LINE DEDENT |
Minimize a string by removing all occurrences of another string | Function to find the minimum length to which string str can be reduced to by removing all occurrences of string K ; Initialize stack of characters ; Push character into the stack ; If stack size >= K . size ( ) ; Create empty string to store characters of stack ; Traverse the string K in reverse ; If any of the characters differ , it means that K is not present in the stack ; Push the elements back into the stack ; Store the string ; Remove top element ; Size of stack gives the minimized length of str ; Driver code ; Function Call | def minLength ( Str , N , K , M ) : NEW_LINE INDENT stackOfChar = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT stackOfChar . append ( Str [ i ] ) NEW_LINE if ( len ( stackOfChar ) >= M ) : NEW_LINE INDENT l = " " NEW_LINE for j in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( K [ j ] != stackOfChar [ - 1 ] ) : NEW_LINE INDENT f = 0 NEW_LINE while ( f != len ( l ) ) : NEW_LINE INDENT stackOfChar . append ( l [ f ] ) NEW_LINE f += 1 NEW_LINE DEDENT break NEW_LINE DEDENT else : NEW_LINE INDENT l = stackOfChar [ - 1 ] + l NEW_LINE stackOfChar . pop ( ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return len ( stackOfChar ) NEW_LINE DEDENT S1 = " fffoxoxoxfxo " NEW_LINE S2 = " fox " NEW_LINE N = len ( S1 ) NEW_LINE M = len ( S2 ) NEW_LINE print ( minLength ( S1 , N , S2 , M ) ) NEW_LINE |
Largest palindrome not exceeding N which can be expressed as product of two 3 | Function to find the largest palindrome not exceeding N which can be expressed as the product of two 3 - digit numbers ; Stores all palindromes ; Stores the product ; Check if X is palindrome ; Check n is less than N ; If true , append it in the list ; Print the largest palindrome ; Driver Code ; Function Call | def palindrome_prod ( N ) : NEW_LINE INDENT palindrome_list = [ ] NEW_LINE for i in range ( 101 , 1000 ) : NEW_LINE INDENT for j in range ( 121 , 1000 , ( 1 if i % 11 == 0 else 11 ) ) : NEW_LINE INDENT n = i * j NEW_LINE x = str ( n ) NEW_LINE if x == x [ : : - 1 ] : NEW_LINE INDENT if n < N : NEW_LINE INDENT palindrome_list . append ( i * j ) NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( max ( palindrome_list ) ) NEW_LINE DEDENT N = 101110 NEW_LINE palindrome_prod ( N ) NEW_LINE |
Check if given strings can be made same by swapping two characters of same or different strings | Function to check if all strings can be made equal by swapping any pair of characters from the same or different strings ; Stores length of string ; Store frequency of each distinct character of the strings ; Traverse the array ; Iterate over the characters ; Update frequency of arr [ i ] [ j ] ; Traverse the array cntFreq [ ] ; If cntFreq [ i ] is divisible by N or not ; Driver Code ; Function Call | def isEqualStrings ( arr , N ) : NEW_LINE INDENT M = len ( arr [ 0 ] ) NEW_LINE cntFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT cntFreq [ ord ( arr [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 256 ) : NEW_LINE INDENT if ( cntFreq [ i ] % N != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " aab " , " bbc " , " cca " ] NEW_LINE N = len ( arr ) NEW_LINE if isEqualStrings ( arr , N ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Minimize a binary string by repeatedly removing even length substrings of same characters | Recursive function to print stack elements from bottom to top without changing their order ; If stack is empty ; Pop top element of the stack ; Recursively call the function PrintStack ; Print the stack element from the bottom ; Push the same element onto the stack to preserve the order ; Function to minimize binary string by removing substrings consisting of same character ; Declare a stack of characters ; Push the first character of the string into the stack ; Traverse the string s ; If Stack is empty ; Push current character into the stack ; Check if the current character is same as the top of the stack ; If true , pop the top of the stack ; Otherwise , push the current element ; Print stack from bottom to top ; Driver Code | def PrintStack ( s ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT x = s [ - 1 ] ; NEW_LINE s . pop ( ) ; NEW_LINE PrintStack ( s ) ; NEW_LINE print ( x , end = " " ) ; NEW_LINE s . append ( x ) ; NEW_LINE DEDENT def minString ( s ) : NEW_LINE INDENT Stack = [ ] ; NEW_LINE Stack . append ( s [ 0 ] ) ; NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( len ( Stack ) == 0 ) : NEW_LINE INDENT Stack . append ( s [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( Stack [ - 1 ] == s [ i ] ) : NEW_LINE INDENT Stack . pop ( ) ; NEW_LINE DEDENT else : NEW_LINE INDENT Stack . append ( s [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT PrintStack ( Stack ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "101001" ; NEW_LINE minString ( string ) ; NEW_LINE DEDENT |
Probability of collision between two trucks | Function to calculate total number of accidents ; Function to calculate count of all possible collision ; Size of string ; Stores the count of collisions ; Total number of truck in lane b ; Count total number of collisions while traversing the string a ; Function to calculate the probability of collisions ; Evaluate total outcome that is all the possible accident ; Evaluate favourable outcome i . e . , count of collision of trucks ; Print desired probability ; Driver Code ; Function Call | def count_of_accident ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if ( n > m ) : NEW_LINE INDENT return ( m * ( m + 1 ) ) / 2 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ) NEW_LINE DEDENT DEDENT def count_of_collision ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE answer = 0 NEW_LINE count_of_truck_in_lane_b = 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if ( b [ i ] == ' T ' ) : NEW_LINE INDENT count_of_truck_in_lane_b += 1 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while ( i < m and i < n ) : NEW_LINE INDENT if ( a [ i ] == ' T ' ) : NEW_LINE INDENT answer += count_of_truck_in_lane_b NEW_LINE DEDENT if ( b [ i ] == ' T ' ) : NEW_LINE INDENT count_of_truck_in_lane_b -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return answer NEW_LINE DEDENT def findProbability ( a , b ) : NEW_LINE INDENT total_outcome = count_of_accident ( a , b ) ; NEW_LINE favourable_outcome = count_of_collision ( a , b ) ; NEW_LINE print ( favourable_outcome / total_outcome ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " TCCBCTTB " NEW_LINE T = " BTCCBBTT " NEW_LINE findProbability ( S , T ) NEW_LINE DEDENT |
Count alphanumeric palindromes of length N | Function to calculate ( x ^ y ) mod p ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Return the final result ; Given N ; Base Case ; Check whether n is even or odd ; Function Call ; Function Call | def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT N = 3 NEW_LINE if ( ( N == 1 ) or ( N == 2 ) ) : NEW_LINE INDENT print ( 62 ) NEW_LINE DEDENT else : NEW_LINE INDENT m = ( 10 ** 9 ) + 7 NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT k = N // 2 NEW_LINE flag = True NEW_LINE DEDENT else : NEW_LINE INDENT k = ( N - 1 ) // 2 NEW_LINE flag = False NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT a = power ( 62 , k , m ) NEW_LINE print ( a ) NEW_LINE DEDENT else : NEW_LINE INDENT a = power ( 62 , ( k + 1 ) , m ) NEW_LINE print ( a ) NEW_LINE DEDENT DEDENT |
Length of the longest substring with every character appearing even number of times | Function to find length of the longest substring with each element occurring even number of times ; Initialize unordered_map ; Stores the length of the longest required substring ; Traverse the string ; Stores the value of the digit present at current index ; Bitwise XOR of the mask with 1 left - shifted by val ; Check if the value of mask is already present in ind or not ; Update the final answer ; Otherwise ; Return the answer ; Driver Code ; Given string ; : Length of the given string ; Function Call | def lenOfLongestReqSubstr ( s , N ) : NEW_LINE INDENT ind = { } NEW_LINE mask = 0 NEW_LINE ind [ 0 ] = - 1 NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE mask ^= ( 1 << val ) NEW_LINE if ( mask in ind ) : NEW_LINE INDENT ans = max ( ans , i - ind [ mask ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ind [ mask ] = i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "223015150" NEW_LINE N = len ( s ) NEW_LINE print ( lenOfLongestReqSubstr ( s , N ) ) NEW_LINE DEDENT |
Subsets and Splits