text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Find whether X exists in Y after jumbling X | Python3 implementation of the approach ; Function that returns true if both the arrays have equal values ; Test the equality ; Function that returns true if any permutation of X exists as a sub in Y ; Base case ; To store cumulative frequency ; Finding the frequency of char... | MAX = 26 NEW_LINE def areEqual ( a , b ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def xExistsInY ( x , y ) : NEW_LINE INDENT if ( len ( x ) > len ( y ) ) : NEW_LINE INDENT return False NEW_LINE ... |
Reverse substrings between each pair of parenthesis | Function to return the modified string ; Push the index of the current opening bracket ; Reverse the substarting after the last encountered opening bracket till the current character ; To store the modified string ; Driver code | def reverseParentheses ( strr , lenn ) : NEW_LINE INDENT st = [ ] NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] == ' ( ' ) : NEW_LINE INDENT st . append ( i ) NEW_LINE DEDENT elif ( strr [ i ] == ' ) ' ) : NEW_LINE INDENT temp = strr [ st [ - 1 ] : i + 1 ] NEW_LINE strr = strr [ : st [ - 1 ] ] + te... |
Count of times second string can be formed from the characters of first string | Python3 implementation of the approach ; Function to update the freq [ ] array to store the frequencies of all the characters of strr ; Update the frequency of the characters ; Function to return the maximum count of times patt can be form... | MAX = 26 NEW_LINE def updateFreq ( strr , freq ) : NEW_LINE INDENT lenn = len ( strr ) NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT freq [ ord ( strr [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT def maxCount ( strr , patt ) : NEW_LINE INDENT strrFreq = [ 0 for i in range ( MAX ) ] NEW_LINE updateFreq ( s... |
Reduce the number to minimum multiple of 4 after removing the digits | Python3 implementation of the approach ; Function to return the minimum number that can be formed after removing the digits which is a multiple of 4 ; For every digit of the number ; Check if the current digit is divisible by 4 ; If any subsequence ... | import sys NEW_LINE TEN = 10 NEW_LINE def minNum ( str , len1 ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT if ( str [ i ] == '4' or str [ i ] == '8' ) : NEW_LINE INDENT res = min ( res , ord ( str [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT DEDENT for i in range ( len1 - 1 ) : ... |
Check if two strings can be made equal by swapping one character among each other | Function that returns true if the string can be made equal after one swap ; A and B are new a and b after we omit the same elements ; Take only the characters which are different in both the strings for every pair of indices ; If the cu... | def canBeEqual ( a , b , n ) : NEW_LINE INDENT A = [ ] NEW_LINE B = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] != b [ i ] : NEW_LINE INDENT A . append ( a [ i ] ) NEW_LINE B . append ( b [ i ] ) NEW_LINE DEDENT DEDENT if len ( A ) == len ( B ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if le... |
Find the Mid | Function to find the mid alphabets ; For every character pair ; Get the average of the characters ; Driver code | def findMidAlphabet ( s1 , s2 , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT mid = ( ord ( s1 [ i ] ) + ord ( s2 [ i ] ) ) // 2 NEW_LINE print ( chr ( mid ) , end = " " ) NEW_LINE DEDENT DEDENT s1 = " akzbqzgw " NEW_LINE s2 = " efhctcsz " NEW_LINE n = len ( s1 ) NEW_LINE findMidAlphabet ( s1 , s2 , n ) ... |
Queries to find the count of vowels in the substrings of the given string | Python 3 implementation of the approach ; Function that returns true if ch is a vowel ; pre [ i ] will store the count of vowels in the substring str [ 0. . . i ] ; Fill the pre [ ] array ; If current character is a vowel ; If its a consonant ;... | N = 2 NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) NEW_LINE DEDENT def performQueries ( str1 , len1 , queries , q ) : NEW_LINE INDENT pre = [ 0 for i in range ( len1 ) ] NEW_LINE if ( isVowel ( str1 [ 0 ] ) ) : NEW_LINE INDENT pre [ 0 ]... |
Check whether the given decoded string is divisible by 6 | Function to return the sum of the digits of n ; Function that return true if the decoded string is divisible by 6 ; To store the sum of the digits ; For each character , get the sum of the digits ; If the sum of digits is not divisible by 3 ; Get the last digit... | def sumDigits ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 ; NEW_LINE sum += digit ; NEW_LINE n //= 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def isDivBySix ( string , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ( ord ( st... |
Check the divisibility of Hexadecimal numbers | Python3 implementation of the approach ; Function that returns true if s is divisible by m ; Map to map characters to real value ; To store the remainder at any stage ; Find the remainder ; Check the value of remainder ; Driver code | CHARS = "0123456789ABCDEF " ; NEW_LINE DIGITS = 16 ; NEW_LINE def isDivisible ( s , m ) : NEW_LINE INDENT mp = dict . fromkeys ( CHARS , 0 ) ; NEW_LINE for i in range ( DIGITS ) : NEW_LINE INDENT mp [ CHARS [ i ] ] = i ; NEW_LINE DEDENT r = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT r = ( r * 16 + mp [... |
Maximum number of splits of a binary number | Function to return the required count ; If the splitting is not possible ; To store the count of zeroes ; Counting the number of zeroes ; Return the final answer ; Driver code | def cntSplits ( s ) : NEW_LINE INDENT if ( s [ len ( s ) - 1 ] == '1' ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans += ( s [ i ] == '0' ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "10010" ... |
Modify the string such that every character gets replaced with the next character in the keyboard | Python3 implementation of the approach ; Function to return the modified string ; Map to store the next character on the keyboard for every possible lowercase character ; Update the string ; Driver code | CHARS = " qwertyuiopasdfghjklzxcvbnm " ; NEW_LINE MAX = 26 ; NEW_LINE def getString ( string , n ) : NEW_LINE INDENT string = list ( string ) ; NEW_LINE uMap = { } ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT uMap [ CHARS [ i ] ] = CHARS [ ( i + 1 ) % MAX ] ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDEN... |
Queries to find the count of characters preceding the given location | Python 3 implementation of the approach ; returns character at index pos - 1 ; Driver Code | def Count ( s , pos ) : NEW_LINE INDENT c = s [ pos - 1 ] NEW_LINE counter = 0 NEW_LINE for i in range ( pos - 1 ) : NEW_LINE INDENT if s [ i ] == c : NEW_LINE INDENT counter = counter + 1 NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abacsddaa " NEW_LINE ... |
Queries to find the count of characters preceding the given location | Python 3 implementation of the approach ; Driver Code | def Count ( temp ) : NEW_LINE INDENT query = [ 9 , 3 , 2 ] NEW_LINE Q = len ( query ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT pos = query [ i ] NEW_LINE print ( temp [ pos - 1 ] ) NEW_LINE DEDENT DEDENT def processing ( s ) : NEW_LINE INDENT temp = [ 0 ] * len ( s ) NEW_LINE d = dict ( ) NEW_LINE for i in range... |
Count of matchsticks required to represent the given number | stick [ i ] stores the count of sticks required to represent the digit i ; Function to return the count of matchsticks required to represent the given number ; For every digit of the given number ; Add the count of sticks required to represent the current di... | sticks = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] ; NEW_LINE def countSticks ( string , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt += ( sticks [ ord ( string [ i ] ) - ord ( '0' ) ] ) ; NEW_LINE DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDE... |
Modulo of a large Binary String | Function to return the value of ( str % k ) ; pwrTwo [ i ] will store ( ( 2 ^ i ) % k ) ; To store the result ; If current bit is 1 ; Add the current power of 2 ; Driver code | def getMod ( _str , n , k ) : NEW_LINE INDENT pwrTwo = [ 0 ] * n NEW_LINE pwrTwo [ 0 ] = 1 % k NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pwrTwo [ i ] = pwrTwo [ i - 1 ] * ( 2 % k ) NEW_LINE pwrTwo [ i ] %= k NEW_LINE DEDENT res = 0 NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT i... |
Count number of binary strings such that there is no substring of length greater than or equal to 3 with all 1 's | Python3 implementation of the approach ; Function to return the count of all possible valid strings ; Initialise and fill 0 's in the dp array ; Base cases ; dp [ i ] [ j ] = number of possible strings su... | MOD = 1000000007 NEW_LINE def countStrings ( N ) : NEW_LINE INDENT dp = [ [ 0 ] * 3 for i in range ( N + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = 1 ; NEW_LINE dp [ 1 ] [ 1 ] = 1 ; NEW_LINE dp [ 1 ] [ 2 ] = 0 ; NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] + dp... |
Find the maximum possible Binary Number from given string | Function to return maximum number that can be formed from the string ; To store the frequency of ' z ' and ' n ' in the given string ; Number of zeroes ; Number of ones ; To store the required number ; Add all the ones ; Add all the zeroes ; Driver code | def maxNumber ( string , n ) : NEW_LINE INDENT freq = [ 0 , 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( string [ i ] == ' z ' ) : NEW_LINE INDENT freq [ 0 ] += 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' n ' ) : NEW_LINE INDENT freq [ 1 ] += 1 ; NEW_LINE DEDENT DEDENT num = " " ; NEW_LINE for i in range (... |
Contiguous unique substrings with the given length L | Function to print the unique sub - string of length n ; set to store the strings ; if the size of the string is equal to 1 then insert ; inserting unique sub - string of length L ; Printing the set of strings ; Driver Code ; Function calling | def result ( s , n ) : NEW_LINE INDENT st = set ( ) ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans = " " ; NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT ans += s [ j ] ; NEW_LINE if ( len ( ans ) == n ) : NEW_LINE INDENT st . add ( ans ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT for ... |
Find the occurrence of the given binary pattern in the binary representation of the array elements | Function to return the binary representation of n ; Array to store binary representation ; Counter for binary array ; Storing remainder in binary array ; To store the binary representation as a string ; Function to retu... | def decToBinary ( n ) : NEW_LINE INDENT binaryNum = [ 0 for i in range ( 32 ) ] NEW_LINE i = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT binaryNum [ i ] = n % 2 NEW_LINE n = n // 2 NEW_LINE i += 1 NEW_LINE DEDENT binary = " " NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT binary += str ( binaryNum [ j... |
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Function that returns true if the sequence can be balanced by changing the position of at most one bracket ; Odd length string can never be balanced ; Add ' ( ' in the beginning and ' ) ' in the end of the string ; If i... | def canBeBalanced ( s , n ) : NEW_LINE INDENT if n % 2 == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT k = " ( " k = k + s + " ) " NEW_LINE d = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( len ( k ) ) : NEW_LINE INDENT if k [ i ] == " ( " : NEW_LINE INDENT d . append ( " ( " ) NEW_LINE DEDENT else : NEW_LINE IN... |
Find the winner of the game | Function to find the winner of the game ; To store the strings for both the players ; If the index is even ; Append the current character to player A 's string ; If the index is odd ; Append the current character to player B 's string ; Sort both the strings to get the lexicographically sm... | def find_winner ( string , n ) : NEW_LINE INDENT string1 = " " ; string2 = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT string1 += string [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT string2 += string [ i ] ; NEW_LINE DEDENT DEDENT string1 = " " . join ( sorted ( string1 )... |
Count of characters in str1 such that after deleting anyone of them str1 becomes str2 | Function to return the count of required indices ; Solution doesn 't exist ; Find the length of the longest common prefix of strings ; Find the length of the longest common suffix of strings ; If solution does not exist ; Return the... | def Find_Index ( str1 , str2 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE if ( n != m + 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if str1 [ i ] == str2 [ i ] : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE IN... |
Expand the string according to the given conditions | Function to expand and print the given string ; Subtract '0' to convert char to int ; Characters within brackets ; Expanding ; Reset the variables ; Driver code | def expandString ( strin ) : NEW_LINE INDENT temp = " " NEW_LINE j = 0 NEW_LINE i = 0 NEW_LINE while ( i < len ( strin ) ) : NEW_LINE INDENT if ( strin [ i ] >= "0" ) : NEW_LINE INDENT num = ord ( strin [ i ] ) - ord ( "0" ) NEW_LINE if ( strin [ i + 1 ] == ' ( ' ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( strin [ j... |
Largest substring of str2 which is a prefix of str1 | Python3 implementation of the approach ; Function to return the largest substring in str2 which is a prefix of str1 ; To store the index in str2 which matches the prefix in str1 ; While there are characters left in str1 ; If the prefix is not found in str2 ; Remove ... | import operator NEW_LINE def findPrefix ( str1 , str2 ) : NEW_LINE INDENT pos = False ; NEW_LINE while ( len ( str1 ) != 0 ) : NEW_LINE INDENT if operator . contains ( str2 , str1 ) != True : NEW_LINE INDENT str1 = str1 [ 0 : len ( str1 ) - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT pos = operator . contains ( str2 ,... |
Round the given number to nearest multiple of 10 | Set | Function to round the given number to the nearest multiple of 10 ; If string is empty ; If the last digit is less then or equal to 5 then it can be rounded to the nearest ( previous ) multiple of 10 by just replacing the last digit with 0 ; Set the last digit to ... | def roundToNearest ( str , n ) : NEW_LINE INDENT if ( str == " " ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ord ( str [ n - 1 ] ) - ord ( '0' ) <= 5 ) : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ n - 1 ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE print ( str [ 0 : n ] ) NEW_LINE DEDENT else : NEW_LINE... |
Repeat substrings of the given String required number of times | Function that returns true if the passed character is a digit ; Function to return the next index of a non - digit character in the string starting at the index i ( returns - 1 ifno such index is found ) ; If the character at index i is a digit then skip ... | def isDigit ( ch ) : NEW_LINE INDENT if ch >= '0' and ch <= '9' : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def nextNonDigit ( string , i ) : NEW_LINE INDENT while i < len ( string ) and isDigit ( string [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if i >= len ( string ) : NEW_LINE IN... |
Check if the given string is vowel prime | Function that returns true if c is a vowel ; Function that returns true if all the vowels in the given string are only at prime indices ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries in it as true . A value in prime [ i ] will finally be false if i i... | def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isVowelPrime ( Str , n ) : NEW_LINE INDENT prime = [ True for i in range ( n ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] ... |
Swap all occurrences of two characters to get lexicographically smallest string | python3 implementation of the approach ; Function to return the lexicographically smallest after swapping all the occurrences of any two characters ; To store the first index of every character of str ; Store the first occurring index eve... | MAX = 256 NEW_LINE def smallestStr ( str , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE chk = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT chk [ i ] = - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( chk [ ord ( str [ i ] ) ] == - 1 ) : NEW_LINE INDENT chk [ ord ( str [ ... |
Longest sub string of 0 's in a binary string which is repeated K times | Function to find the longest subof 0 's ; To store size of the string ; To store the required answer ; Find the longest subof 0 's ; Run a loop upto s [ i ] is zero ; Check the conditions ; Driver code ; Function call | def longest_substring ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if ( k > 1 ) : NEW_LINE INDENT s += s NEW_LINE n *= 2 NEW_LINE DEDENT ans = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT x = 0 NEW_LINE while ( i < n and s [ i ] == '0' ) : NEW_LINE INDENT x , i = x + 1 , i + 1 NEW_LINE DEDENT ans =... |
Find the number of occurrences of a character upto preceding position | Function to find the number of occurrences of a character at position P upto p - 1 ; Return the required count ; Driver code ; Function call | def Occurrence ( s , position ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( position - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ position - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT s = " ababababab " ; NEW_LINE p = 9 NEW_LINE print ( Occurrence ( s , p ) ) NEW_LIN... |
Find the number of occurrences of a character upto preceding position | Function to find the number of occurrences of a character at position P upto p - 1 ; Iterate over the string ; Store the Occurrence of same character ; Increase its frequency ; Return the required count ; Driver code ; Function call | def countOccurrence ( s , position ) : NEW_LINE INDENT alpha = [ 0 ] * 26 NEW_LINE b = [ 0 ] * len ( s ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT b [ i ] = alpha [ ord ( s [ i ] ) - 97 ] NEW_LINE alpha [ ord ( s [ i ] ) - 97 ] = alpha [ ord ( s [ i ] ) - 97 ] + 1 NEW_LINE DEDENT return b [ position -... |
Map every character of one string to another such that all occurrences are mapped to the same character | Python 3 implementation of the approach ; Function that returns true if the mapping is possible ; Both the strings are of un - equal lengths ; To store the frequencies of the characters in both the string ; Update ... | MAX = 26 NEW_LINE def canBeMapped ( s1 , l1 , s2 , l2 ) : NEW_LINE INDENT if ( l1 != l2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT freq1 = [ 0 for i in range ( MAX ) ] NEW_LINE freq2 = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT freq1 [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW... |
Distinct strings such that they contains given strings as sub | Set to store strings and aduplicates ; Recursive function to generate the required strings ; If currentis part of the result ; Insert it into the set ; If character from str1 can be chosen ; If character from str2 can be chosen ; Function to print the gene... | stringSet = dict ( ) NEW_LINE def find_permutation ( str1 , str2 , len1 , len2 , i , j , res ) : NEW_LINE INDENT if ( len ( res ) == len1 + len2 ) : NEW_LINE INDENT stringSet [ res ] = 1 NEW_LINE return NEW_LINE DEDENT if ( i < len1 ) : NEW_LINE INDENT find_permutation ( str1 , str2 , len1 , len2 , i + 1 , j , res + st... |
Generate all possible strings such that char at index i is either str1 [ i ] or str2 [ i ] | Recursive function to generate the required strings ; If length of the current string is equal to the length of the given strings then the current string is part of the result ; Choosing the current character from the string a ... | def generateStr ( a , b , s , count , len ) : NEW_LINE INDENT if ( count == len ) : NEW_LINE INDENT print ( s ) ; NEW_LINE return ; NEW_LINE DEDENT generateStr ( a [ 1 : ] , b [ 1 : ] , s + a [ 0 ] , count + 1 , len ) ; NEW_LINE generateStr ( a [ 1 : ] , b [ 1 : ] , s + b [ 0 ] , count + 1 , len ) ; NEW_LINE DEDENT a =... |
Program to generate all possible valid IP addresses from given string | Set 2 | Function to get all the valid ip - addresses ; If index greater than givenString size and we have four block ; Remove the last dot ; Add ip - address to the results ; To add one index to ip - address ; Select one digit and call the same fun... | def GetAllValidIpAddress ( result , givenString , index , count , ipAddress ) : NEW_LINE INDENT if ( len ( givenString ) == index and count == 4 ) : NEW_LINE INDENT ipAddress . pop ( ) ; NEW_LINE result . append ( ipAddress ) ; NEW_LINE return ; NEW_LINE DEDENT if ( len ( givenString ) < index + 1 ) : NEW_LINE INDENT r... |
Count of non | Function to return the count of required non - overlapping sub - strings ; To store the required count ; If "010" matches the sub - string starting at current index i ; If "101" matches the sub - string starting at current index i ; Driver code | def countSubStr ( s , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE i = 0 NEW_LINE while i < ( n - 2 ) : NEW_LINE INDENT if ( s [ i ] == '0' and s [ i + 1 ] == '1' and s [ i + 2 ] == '0' ) : NEW_LINE INDENT count += 1 ; NEW_LINE i += 3 ; NEW_LINE DEDENT elif ( s [ i ] == '1' and s [ i + 1 ] == '0' and s [ i + 2 ] == '1' )... |
Find distinct characters in distinct substrings of a string | Function to return the count of distinct characters in all the distinct sub - strings of the given string ; To store all the sub - strings ; To store the current sub - string ; To store the characters of the current sub - string ; If current sub - string has... | def countTotalDistinct ( string ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE items = set ( ) ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT temp = " " ; NEW_LINE ans = set ( ) ; NEW_LINE for j in range ( i , len ( string ) ) : NEW_LINE INDENT temp = temp + string [ j ] ; NEW_LINE ans . add ( string [ j ] ) ; ... |
Partition the string in two parts such that both parts have at least k different characters | Function to find the partition of the string such that both parts have at least k different characters ; Length of the string ; To check if the current character is already found ; Count number of different characters in the l... | def division_of_string ( string , k ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE has = { } ; NEW_LINE cnt = 0 ; i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if string [ i ] not in has : NEW_LINE INDENT cnt += 1 ; NEW_LINE has [ string [ i ] ] = True ; NEW_LINE DEDENT if ( cnt == k ) : NEW_LINE INDENT ans = i... |
Count substrings that contain all vowels | SET 2 | Function that returns true if c is a vowel ; Function to return the count of sub - strings that contain every vowel at least once and no consonant ; Map is used to store count of each vowel ; Start index is set to 0 initially ; If substring till now have all vowels atl... | def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) ; NEW_LINE DEDENT def countSubstringsUtil ( s ) : NEW_LINE INDENT count = 0 ; NEW_LINE mp = dict . fromkeys ( s , 0 ) ; NEW_LINE n = len ( s ) ; NEW_LINE start = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE... |
Remove first adjacent pairs of similar characters until possible | Function to remove adjacent duplicates ; Iterate for every character in the string ; If ans string is empty or its last character does not match with the current character then append this character to the string ; Matches with the previous one ; Return... | def removeDuplicates ( S ) : NEW_LINE INDENT ans = " " ; NEW_LINE for it in S : NEW_LINE INDENT if ( ans == " " or ans [ - 1 ] != it ) : NEW_LINE INDENT ans += it ; NEW_LINE DEDENT elif ( ans [ - 1 ] == it ) : NEW_LINE INDENT ans = ans [ : - 1 ] ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _... |
Reverse individual words with O ( 1 ) extra space | Function to resturn the after reversing the individual words ; Pointer to the first character of the first word ; If the current word has ended ; Pointer to the last character of the current word ; Reverse the current word ; Pointer to the first character of the next ... | def reverseWords ( Str ) : NEW_LINE INDENT start = 0 NEW_LINE for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( Str [ i ] == ' β ' or i == len ( Str ) - 1 ) : NEW_LINE INDENT end = i - 1 NEW_LINE if ( i == len ( Str ) - 1 ) : NEW_LINE INDENT end = i NEW_LINE DEDENT while ( start < end ) : NEW_LINE INDENT Str [ star... |
Reverse the Words of a String using Stack | Function to reverse the words of the given sentence ; Create an empty character array stack ; Push words into the stack ; Get the words in reverse order ; Driver code | def reverse ( k ) : NEW_LINE INDENT s = [ ] NEW_LINE token = k . split ( ) NEW_LINE for word in token : NEW_LINE INDENT s . append ( word ) ; NEW_LINE DEDENT while ( len ( s ) ) : NEW_LINE INDENT print ( s . pop ( ) , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = " geeks β... |
Count of substrings which contains a given character K times | Function to count the number of substrings which contains the character C exactly K times ; left and right counters for characters on both sides of subwindow ; left and right pointer on both sides of subwindow ; Initialize the frequency ; result and Length ... | def countSubString ( s , c , k ) : NEW_LINE INDENT leftCount = 0 NEW_LINE rightCount = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE freq = 0 NEW_LINE result = 0 NEW_LINE Len = len ( s ) NEW_LINE while ( s [ left ] != c and left < Len ) : NEW_LINE INDENT left += 1 NEW_LINE leftCount += 1 NEW_LINE DEDENT right = left ... |
Count of sub | Python3 implementation of the approach ; Function to return the total required sub - sequences ; Find ways for all values of x ; x + 1 ; Removing all unnecessary digits ; Prefix Sum Array for X + 1 digit ; Sum of squares ; Previous sum of all possible pairs ; To find sum of multiplication of all possible... | MOD = 1000000007 NEW_LINE def solve ( test ) : NEW_LINE INDENT size = len ( test ) NEW_LINE total = 0 NEW_LINE for i in range ( 9 ) : NEW_LINE INDENT x = i NEW_LINE y = i + 1 NEW_LINE newtest = " " NEW_LINE for j in range ( size ) : NEW_LINE INDENT if ( ord ( test [ j ] ) == x + 48 or ord ( test [ j ] ) == y + 48 ) : N... |
Find if it is possible to make a binary string which contanins given number of "0" , "1" , "01" and "10" as sub sequences | Function that returns true if it is possible to make a binary string consisting of l 0 ' s , β m β 1' s , x "01" sub - sequences and y "10" sub - sequences ; Driver code | def isPossible ( l , m , x , y ) : NEW_LINE INDENT if ( l * m == x + y ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 3 ; m = 2 ; x = 4 ; y = 2 ; NEW_LINE if ( isPossible ( l , m , x , y ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW... |
Count pairs of characters in a string whose ASCII value difference is K | Python3 implementation of the approach ; Function to return the count of required pairs of characters ; Length of the string ; To store the frequency of each character ; Update the frequency of each character ; To store the required count of pair... | MAX = 26 NEW_LINE def countPairs ( string , k ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE if ( k == 0 ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE I... |
Count of three non | Function that returns true if s [ i ... j ] + s [ k ... l ] + s [ p ... q ] is a palindrome ; Function to return the count of valid sub - strings ; To store the count of required sub - strings ; For choosing the first sub - string ; For choosing the second sub - string ; For choosing the third sub ... | def isPalin ( i , j , k , l , p , q , s ) : NEW_LINE INDENT start = i ; end = q ; NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( s [ start ] != s [ end ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT start += 1 ; NEW_LINE if ( start == j + 1 ) : NEW_LINE INDENT start = k ; NEW_LINE DEDENT end -= 1 ; NEW_LIN... |
Find the sum of the ascii values of characters which are present at prime positions | Python3 implementation of the approach ; Function that returns true if n is prime ; Function to return the sum of the ascii values of the characters which are present at prime positions ; To store the sum ; For every character ; If cu... | from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def sumAscii... |
Count the nodes of the tree which make a pangram when concatenated with the sub | Python3 implementation of the approach ; Function that returns if the string x is a pangram ; Function to return the count of nodes which make pangram with the sub - tree nodes ; Function to perform dfs and update the nodes such that weig... | graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE def Pangram ( x ) : NEW_LINE INDENT mp = { } NEW_LINE n = len ( x ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if x [ i ] not in mp : NEW_LINE INDENT mp [ x [ i ] ] = 0 NEW_LINE DEDENT mp [ x [ i ] ] += 1 NEW_LINE DEDENT if ( len ( mp ) ... |
Count the nodes of a tree whose weighted string does not contain any duplicate characters | Python3 implementation of the approach ; Function that returns true if the string contains unique characters ; Function to perform dfs ; If weight of the current node node contains unique characters ; Driver code ; Weights of th... | cnt = 0 NEW_LINE graph = [ [ ] for i in range ( 100 ) ] NEW_LINE weight = [ 0 ] * 100 NEW_LINE def uniqueChars ( x ) : NEW_LINE INDENT mp = { } NEW_LINE n = len ( x ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if x [ i ] not in mp : NEW_LINE INDENT mp [ x [ i ] ] = 0 NEW_LINE DEDENT mp [ x [ i ] ] += 1 NEW_LINE DE... |
Check if a string contains two non overlapping sub | Function that returns true if s contains two non overlapping sub strings " geek " and " keeg " ; If " geek " and " keeg " are both present in s without over - lapping and " keeg " starts after " geek " ends ; Driver code | def isValid ( s ) : NEW_LINE INDENT p = " " NEW_LINE p = s . find ( " geek " ) NEW_LINE if ( s . find ( " keeg " , p + 4 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geekeekeeg " NEW_LINE if ( isValid ( s ) ) : NEW_LINE INDENT pri... |
Find the last non repeating character in string | Maximum distinct characters possible ; Function to return the last non - repeating character ; To store the frequency of each of the character of the given string ; Update the frequencies ; Starting from the last character ; Current character ; If frequency of the curre... | MAX = 256 ; NEW_LINE def lastNonRepeating ( string , n ) : NEW_LINE INDENT freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) ] += 1 ; NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT ch = string [ i ] ; NEW_LINE if ( freq [ ord ( ch ) ] == 1 ) : NEW_L... |
Minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B | Function to return the minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B ; Initialize result ; Loop through last b digits ; Driver code | def findCount ( s , n , a , b ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( b ) : NEW_LINE INDENT if ( i == a ) : NEW_LINE INDENT res += ( s [ n - i - 1 ] != '1' ) NEW_LINE DEDENT else : NEW_LINE INDENT res += ( s [ n - i - 1 ] != '0' ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main... |
Find letter 's position in Alphabet using Bit operation | Python3 implementation of the approach ; Function to calculate the position of characters ; Performing AND operation with number 31 ; Driver code | NUM = 31 NEW_LINE def positions ( str ) : NEW_LINE INDENT for i in str : NEW_LINE INDENT print ( ( ord ( i ) & NUM ) , end = " β " ) NEW_LINE DEDENT DEDENT str = " Geeks " NEW_LINE positions ( str ) NEW_LINE |
Generate all permutations of a string that follow given constraints | Simple Python program to print all permutations of a string that follow given constraint ; Check if current permutation is valid ; Recursively generate all permutation ; Driver Code | def permute ( str , l , r ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT if " AB " not in ' ' . join ( str ) : NEW_LINE INDENT print ( ' ' . join ( str ) , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT str [ l ] , str [ i ] = str [ i ] , str [ l ] NEW_LINE perm... |
Length of the longest substring that do not contain any palindrome | Function to find the length of the longest substring ; initializing the variables ; checking palindrome of size 2 example : aa ; checking palindrome of size 3 example : aba ; else : incrementing length of substring ; If there exits single character th... | def lenoflongestnonpalindrome ( s ) : NEW_LINE INDENT max1 , length = 1 , 0 NEW_LINE for i in range ( 0 , len ( s ) - 1 ) : NEW_LINE INDENT if s [ i ] == s [ i + 1 ] : NEW_LINE INDENT length = 0 NEW_LINE DEDENT elif s [ i + 1 ] == s [ i - 1 ] and i > 0 : NEW_LINE INDENT length = 1 NEW_LINE length += 1 NEW_LINE DEDENT D... |
Calculate score for the given binary string | Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return t... | def calcScore ( str ) : NEW_LINE INDENT score = 0 NEW_LINE len1 = len ( str ) NEW_LINE i = 0 NEW_LINE while ( i < len1 ) : NEW_LINE INDENT chunkSize = 1 NEW_LINE currentChar = str [ i ] NEW_LINE i += 1 NEW_LINE while ( i < len1 and str [ i ] == currentChar ) : NEW_LINE INDENT chunkSize += 1 NEW_LINE i += 1 NEW_LINE DED... |
Number of sub | Function to return the count of required sub - strings ; Left and right counters for characters on both sides of sub - string window ; Left and right pointer on both sides of sub - string window ; Initialize the frequency ; Result and length of string ; Initialize the left pointer ; Initialize the right... | def countSubString ( s , c , k ) : NEW_LINE INDENT leftCount = 0 NEW_LINE rightCount = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE freq = 0 NEW_LINE result = 0 NEW_LINE len1 = len ( s ) NEW_LINE while ( s [ left ] != c and left < len1 ) : NEW_LINE INDENT left += 1 NEW_LINE leftCount += 1 NEW_LINE DEDENT right = lef... |
Maximum length palindrome that can be created with characters in range L and R | Python3 implementation of the approach ; Function to return the length of the longest palindrome that can be formed using the characters in the range [ l , r ] ; 0 - based indexing ; Marks if there is an odd frequency character ; Length of... | N = 4 NEW_LINE def performQueries ( l , r , prefix ) : NEW_LINE INDENT l -= 1 NEW_LINE r -= 1 NEW_LINE flag = False NEW_LINE count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT cnt = prefix [ r ] [ i ] NEW_LINE if ( l > 0 ) : NEW_LINE INDENT cnt -= prefix [ l - 1 ] [ i ] NEW_LINE DEDENT if ( cnt % 2 == 1 ) : NEW... |
Number of times the given string occurs in the array in the range [ l , r ] | Python implementation of the approach ; Function to return the number of occurrences of ; To store the indices of strings in the array ; If current string doesn 't have an entry in the map then create the entry ; If the given string is not ... | from bisect import bisect_right as upper_bound NEW_LINE from collections import defaultdict NEW_LINE def numOccurences ( arr : list , n : int , string : str , L : int , R : int ) -> int : NEW_LINE INDENT M = defaultdict ( lambda : list ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if temp ... |
Check whether the given string is a valid identifier | Function that returns true if str1 is a valid identifier ; If first character is invalid ; Traverse the for the rest of the characters ; is a valid identifier ; Driver code | def isValid ( str1 , n ) : NEW_LINE INDENT if ( ( ( ord ( str1 [ 0 ] ) >= ord ( ' a ' ) and ord ( str1 [ 0 ] ) <= ord ( ' z ' ) ) or ( ord ( str1 [ 0 ] ) >= ord ( ' A ' ) and ord ( str1 [ 0 ] ) <= ord ( ' Z ' ) ) or ord ( str1 [ 0 ] ) == ord ( ' _ ' ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in... |
Check if all the 1 's in a binary string are equidistant or not | Function that returns true if all the 1 's in the binary s are equidistant ; Initialize vector to store the position of 1 's ; Store the positions of 1 's ; Size of the position vector ; If condition isn 't satisfied ; Driver code | def check ( s , l ) : NEW_LINE INDENT pos = [ ] NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT DEDENT t = len ( pos ) NEW_LINE for i in range ( 1 , t ) : NEW_LINE INDENT if ( ( pos [ i ] - pos [ i - 1 ] ) != ( pos [ 1 ] - pos [ 0 ] ) ) : NEW_LI... |
Capitalize the first and last character of each word in a string | Python3 program to capitalise the first and last character of each word in a string . ; Create an equivalent char array of given string ; k stores index of first character and i is going to store index of last character . ; Check if the character is a s... | def FirstAndLast ( string ) : NEW_LINE INDENT ch = list ( string ) ; NEW_LINE i = 0 ; NEW_LINE while i < len ( ch ) : NEW_LINE INDENT k = i ; NEW_LINE while ( i < len ( ch ) and ch [ i ] != ' β ' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( ord ( ch [ k ] ) >= 97 and ord ( ch [ k ] ) <= 122 ) : NEW_LINE INDENT ch ... |
Find the number of players who roll the dice when the dice output sequence is given | Function to return the number of players ; Initialize cnt as 0 ; Iterate in the string ; Check for numbers other than x ; Driver code | def findM ( s , x ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) != x ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "3662123" NEW_LINE x = 6 NEW_LINE print ( fin... |
Print the first and last character of each word in a String | Python3 program to print the first and last character of each word in a String ; Function to print the first and last character of each word . ; If it is the first word of the string then print it . ; If it is the last word of the string then also print it .... | ' NEW_LINE def FirstAndLast ( string ) : NEW_LINE INDENT for i in range ( len ( string ) ) : NEW_LINE INDENT if i == 0 : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT if i == len ( string ) - 1 : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT if string [ i ] == " β " : NEW_LINE ... |
Find the longest sub | Function to find longest prefix suffix ; To store longest prefix suffix ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Loop calculates lps [ i ] for i = 1 to n - 1 ; ( pat [ i ] != pat [ Len ] ) ; If Len = 0 ; Function to find the longest substring which is prefix as wel... | def compute_lps ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lps = [ 0 for i in range ( n ) ] NEW_LINE Len = 0 NEW_LINE lps [ 0 ] = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( s [ i ] == s [ Len ] ) : NEW_LINE INDENT Len += 1 NEW_LINE lps [ i ] = Len NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LIN... |
Pairs of strings which on concatenating contains each character of " string " | Python3 implementation of the approach ; Function to return the bitmask for the string ; Function to return the count of pairs ; bitMask [ i ] will store the count of strings from the array whose bitmask is i ; To store the count of pairs ;... | MAX = 64 NEW_LINE def getBitmask ( s ) : NEW_LINE INDENT temp = 0 NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ j ] == ' s ' ) : NEW_LINE INDENT temp = temp | 1 NEW_LINE DEDENT elif ( s [ j ] == ' t ' ) : NEW_LINE INDENT temp = temp | 2 NEW_LINE DEDENT elif ( s [ j ] == ' r ' ) : NEW_LINE INDENT temp... |
Count of pairs of strings which differ in exactly one position | Function to return the count of same pairs ; Function to return total number of strings which satisfy required condition ; Dictionary changed will store strings with wild cards Dictionary same will store strings that are equal ; Iterating for all strings ... | def pair_count ( d ) : NEW_LINE INDENT return sum ( ( i * ( i - 1 ) ) // 2 for i in d . values ( ) ) NEW_LINE DEDENT def Difference ( array , m ) : NEW_LINE INDENT changed , same = { } , { } NEW_LINE for s in array : NEW_LINE INDENT same [ s ] = same . get ( s , 0 ) + 1 NEW_LINE for i in range ( m ) : NEW_LINE INDENT c... |
Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | Function to return the number of ways to form the sub - string ; Initialize a hash - table with 0 ; Iterate in the string and count the frequency of characters that do not lie in the range L and R ; Out of range c... | def calculateWays ( s , n , l , r ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < l or i > r ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ways = 1 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT if ( ... |
Program to find the kth character after decrypting a string | Function to print kth character of String s after decrypting it ; Get the length of string ; Initialise pointer to character of input string to zero ; Total length of resultant string ; Traverse the string from starting and check if each character is alphabe... | def findKthChar ( s , k ) : NEW_LINE INDENT len1 = len ( s ) NEW_LINE i = 0 NEW_LINE total_len = 0 NEW_LINE while ( i < len1 ) : NEW_LINE INDENT if ( s [ i ] . isalpha ( ) ) : NEW_LINE INDENT total_len += 1 NEW_LINE if ( total_len == k ) : NEW_LINE INDENT return s [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT else : NEW... |
Check whether the Average Character of the String is present or not | Python 3 program to check if the average character is present in the string or not ; Checks if the character is present ; Get the length of string ; Iterate from i = 0 to the length of the string to check if the character is present in the string ; F... | from math import floor NEW_LINE def check_char ( st , ch ) : NEW_LINE INDENT l = len ( st ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( st [ i ] == ch ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def find_avg ( st ) : NEW_LINE INDENT sm = 0 NEW_LINE l = len ( st ) NEW_LIN... |
Convert the ASCII value sentence to its equivalent string | Function to print the character sequence for the given ASCII sentence ; Append the current digit ; If num is within the required range ; Convert num to char ; Reset num to 0 ; Driver code | def asciiToSentence ( string , length ) : NEW_LINE INDENT num = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT num = num * 10 + ( ord ( string [ i ] ) - ord ( '0' ) ) ; NEW_LINE if ( num >= 32 and num <= 122 ) : NEW_LINE INDENT ch = chr ( num ) ; NEW_LINE print ( ch , end = " " ) ; NEW_LINE num = 0 ; NEW_LINE... |
Distinct state codes that appear in a string as contiguous sub | Function to return the count of distinct state codes ; Insert every sub - string of length 2 in the set ; Return the size of the set ; Driver code | def countDistinctCode ( string ) : NEW_LINE INDENT codes = set ( ) NEW_LINE for i in range ( 0 , len ( string ) - 1 ) : NEW_LINE INDENT codes . add ( string [ i : i + 2 ] ) NEW_LINE DEDENT return len ( codes ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " UPUP " NEW_LINE print ( countDist... |
Count of buttons pressed in a keypad mobile | Array to store how many times a button has to be pressed for typing a particular character ; Function to return the count of buttons pressed to type the given string ; Count the key presses ; Return the required count ; Driver code | arr = [ 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 4 , 1 , 2 , 3 , 1 , 2 , 3 , 4 ] ; NEW_LINE def countKeyPressed ( string , length ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT count += arr [ ord ( string [ i ] ) - ord ( ' a ' ) ] ; NEW_LINE DEDENT re... |
First string from the given array whose reverse is also present in the same array | Function that returns true if s1 is equal to reverse of s2 ; If both the strings differ in length ; In case of any character mismatch ; Function to return the first word whose reverse is also present in the array ; Check every string ; ... | def isReverseEqual ( s1 , s2 ) : NEW_LINE INDENT if len ( s1 ) != len ( s2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT l = len ( s1 ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if s1 [ i ] != s2 [ l - i - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def getWord ( str ,... |
Check if the given string is K | Function that returns true if sub - string of length k starting at index i is also a prefix of the string ; k length sub - string cannot start at index i ; Character mismatch between the prefix and the sub - string starting at index i ; Function that returns true if str is K - periodic ... | def isPrefix ( string , length , i , k ) : NEW_LINE INDENT if i + k > length : NEW_LINE INDENT return False NEW_LINE DEDENT for j in range ( 0 , k ) : NEW_LINE INDENT if string [ i ] != string [ j ] : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def isKPeriodic ( strin... |
Minimum number of letters needed to make a total of n | Function to return the minimum letters required to make a total of n ; Driver code | def minLettersNeeded ( n ) : NEW_LINE INDENT if n % 26 == 0 : NEW_LINE INDENT return ( n // 26 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n // 26 ) + 1 ) NEW_LINE DEDENT DEDENT n = 52 NEW_LINE print ( minLettersNeeded ( n ) ) NEW_LINE |
Find the first maximum length even word from a string | Function to find maximum length even word ; To store length of current word . ; To store length of maximum length word . ; To store starting index of maximum length word . ; If current character is space then word has ended . Check if it is even length word or not... | def findMaxLenEven ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE i = 0 NEW_LINE currlen = 0 NEW_LINE maxlen = 0 NEW_LINE st = - 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( str [ i ] == ' β ' ) : NEW_LINE INDENT if ( currlen % 2 == 0 ) : NEW_LINE INDENT if ( maxlen < currlen ) : NEW_LINE INDENT maxlen = currl... |
Minimum length substring with exactly K distinct characters | Function to find minimum length substring having exactly k distinct character . ; Starting index of sliding window . ; Ending index of sliding window . ; To store count of character . ; To store count of distinct character in current sliding window . ; To st... | def findMinLenStr ( str , k ) : NEW_LINE INDENT n = len ( str ) NEW_LINE st = 0 NEW_LINE end = 0 NEW_LINE cnt = [ 0 ] * 26 NEW_LINE distEle = 0 NEW_LINE currlen = 0 NEW_LINE minlen = n NEW_LINE startInd = - 1 NEW_LINE while ( end < n ) : NEW_LINE INDENT cnt [ ord ( str [ end ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( cnt... |
Minimum number of replacements to make the binary string alternating | Set 2 | Function to return the minimum number of characters of the given binary string to be replaced to make the string alternating ; If there is 1 at even index positions ; If there is 0 at odd index positions ; Driver code | def minReplacement ( s , length ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if i % 2 == 0 and s [ i ] == '1' : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT if i % 2 == 1 and s [ i ] == '0' : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return min ( ans , length - ans ) NEW_LINE D... |
Deletions of "01" or "10" in binary string to make it free from "01" or "10" | Function to return the count of deletions of sub - strings "01" or "10" ; To store the count of 0 s and 1 s ; Driver code | def substrDeletion ( string , length ) : NEW_LINE INDENT count0 = 0 ; NEW_LINE count1 = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT count0 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count1 += 1 ; NEW_LINE DEDENT DEDENT return min ( count0 , count1 ) ; NEW_LIN... |
Group consecutive characters of same type in a string | Function to return the modified string ; Store original string ; Remove all white spaces ; To store the resultant string ; Traverse the string ; Group upper case characters ; Group numeric characters ; Group arithmetic operators ; Return the resultant string ; Dri... | def groupCharacters ( s , l ) : NEW_LINE INDENT temp = " " NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( s [ i ] != ' β ' ) : NEW_LINE INDENT temp = temp + s [ i ] NEW_LINE DEDENT DEDENT l = len ( temp ) NEW_LINE ans = " " NEW_LINE i = 0 NEW_LINE while ( i < l ) : NEW_LINE INDENT if ( ord ( temp [ i ] ) >= ord (... |
Find the minimum number of preprocess moves required to make two strings equal | Function to return the minimum number of pre - processing moves required on string A ; Length of the given strings ; To store the required answer ; Run a loop upto n / 2 ; To store frequency of 4 characters ; If size is 4 ; If size is 3 ; ... | def Preprocess ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE ans = 0 NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE mp [ A [ i ] ] = 1 NEW_LINE if A [ i ] == A [ n - i - 1 ] : NEW_LINE INDENT mp [ A [ n - i - 1 ] ] += 1 NEW_LINE DEDENT if B [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [... |
Check whether two strings are equivalent or not according to given condition | This function returns the least lexicogr aphical string obtained from its two halves ; Base Case - If string size is 1 ; Divide the string into its two halves ; Form least lexicographical string ; Driver Code | def leastLexiString ( s ) : NEW_LINE INDENT if ( len ( s ) & 1 != 0 ) : NEW_LINE INDENT return s NEW_LINE DEDENT x = leastLexiString ( s [ 0 : int ( len ( s ) / 2 ) ] ) NEW_LINE y = leastLexiString ( s [ int ( len ( s ) / 2 ) : len ( s ) ] ) NEW_LINE return min ( x + y , y + x ) NEW_LINE DEDENT def areEquivalent ( a , ... |
Check if a string can be converted to another string by replacing vowels and consonants | Function to check if the character is vowel or not ; Function that checks if a string can be converted to another string ; Find length of string ; If length is not same ; Iterate for every character ; If both vowel ; Both are cons... | def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def checkPossibility ( s1 , s2 ) : NEW_LINE INDENT l1 = len ( s1 ) NEW_LINE l2 = len ( s2 ) NEW_LINE if ( l1 != l2 ) : NEW_LINE INDENT ... |
Generate a string consisting of characters ' a ' and ' b ' that satisfy the given conditions | Function to generate and print the required string ; More ' b ' , append " bba " ; More ' a ' , append " aab " ; Equal number of ' a ' and ' b ' append " ab " ; Driver code | def generateString ( A , B ) : NEW_LINE INDENT rt = " " NEW_LINE while ( 0 < A or 0 < B ) : NEW_LINE INDENT if ( A < B ) : NEW_LINE INDENT if ( 0 < B ) : NEW_LINE INDENT rt = rt + ' b ' NEW_LINE B -= 1 NEW_LINE DEDENT if ( 0 < B ) : NEW_LINE INDENT rt += ' b ' NEW_LINE B -= 1 NEW_LINE DEDENT if ( 0 < A ) : NEW_LINE IND... |
Number of strings that satisfy the given condition | Function to return the count of valid strings ; Set to store indices of valid strings ; Find the maximum digit for current position ; Add indices of all the strings in the set that contain maximal digit ; Return number of strings in the set ; Driver code | def countStrings ( n , m , s ) : NEW_LINE INDENT ind = dict ( ) NEW_LINE for j in range ( m ) : NEW_LINE INDENT mx = 0 NEW_LINE str1 = s [ j ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT mx = max ( mx , int ( str1 [ i ] ) ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if int ( str1 [ i ] ) == mx : NEW_LIN... |
Lexicographically largest sub | Function to return the lexicographically largest sub - sequence of s ; Get the max character from the string ; Use all the occurrences of the current maximum character ; Repeat the steps for the remaining string ; Driver code | def getSubSeq ( s , n ) : NEW_LINE INDENT res = " " NEW_LINE cr = 0 NEW_LINE while ( cr < n ) : NEW_LINE INDENT mx = s [ cr ] NEW_LINE for i in range ( cr + 1 , n ) : NEW_LINE INDENT mx = max ( mx , s [ i ] ) NEW_LINE DEDENT lst = cr NEW_LINE for i in range ( cr , n ) : NEW_LINE INDENT if ( s [ i ] == mx ) : NEW_LINE I... |
Validation of Equation Given as String | Function that returns true if the equation is valid ; If it is an integer then add it to another string array ; Evaluation of 1 st operator ; Evaluation of 2 nd operator ; Evaluation of 3 rd operator ; If the LHS result is equal to the RHS ; Driver code | def isValid ( string ) : NEW_LINE INDENT k = 0 ; NEW_LINE operands = [ " " ] * 5 ; NEW_LINE operators = [ " " ] * 4 ; NEW_LINE ans = 0 ; ans1 = 0 ; ans2 = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] != ' + ' and string [ i ] != ' = ' and string [ i ] != ' - ' ) : NEW_LINE INDENT o... |
Count of sub | Function to return the count of sub - strings of str that are divisible by k ; Take all sub - strings starting from i ; If current sub - string is divisible by k ; Return the required count ; Driver code | def countSubStr ( str , l , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT n = 0 NEW_LINE for j in range ( i , l , 1 ) : NEW_LINE INDENT n = n * 10 + ( ord ( str [ j ] ) - ord ( '0' ) ) NEW_LINE if ( n % k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NE... |
Find the resulting Colour Combination | Function to return Colour Combination ; Check for B * G = Y ; Check for B * Y = G ; Check for Y * G = B ; Driver Code | def Colour_Combination ( s ) : NEW_LINE INDENT temp = s [ 0 ] NEW_LINE for i in range ( 1 , len ( s ) , 1 ) : NEW_LINE INDENT if ( temp != s [ i ] ) : NEW_LINE INDENT if ( ( temp == ' B ' or temp == ' G ' ) and ( s [ i ] == ' G ' or s [ i ] == ' B ' ) ) : NEW_LINE INDENT temp = ' Y ' NEW_LINE DEDENT elif ( ( temp == ' ... |
Reverse Middle X Characters | Function to reverse the middle x characters in a str1ing ; Find the position from where the characters have to be reversed ; Print the first n characters ; Print the middle x characters in reverse ; Print the last n characters ; Driver code | def reverse ( str1 , x ) : NEW_LINE INDENT n = ( len ( str1 ) - x ) // 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( str1 [ i ] , end = " " ) NEW_LINE DEDENT for i in range ( n + x - 1 , n - 1 , - 1 ) : NEW_LINE INDENT print ( str1 [ i ] , end = " " ) NEW_LINE DEDENT for i in range ( n + x , len ( str1 ) ) ... |
Minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | Function to count numbers ; Count the number of ' a ' , ' b ' and ' c ' in string ; If equal previously ; If not a multiple of 3 ; Increase the number of a ' s β by β β removing β extra β ' b ' and c ; Check if it is... | def lexoSmallest ( s , n ) : NEW_LINE INDENT ca = 0 NEW_LINE cb = 0 NEW_LINE cc = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT ca += 1 NEW_LINE DEDENT elif ( s [ i ] == ' b ' ) : NEW_LINE INDENT cb += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT DEDENT ... |
Minimum moves to reach from i to j in a cyclic string | Function to return the count of steps required to move from i to j ; Starting from i + 1 ; Count of steps ; Current character ; If current character is different from previous ; Increment steps ; Update current character ; Return total steps ; Function to return t... | def getSteps ( str , i , j , n ) : NEW_LINE INDENT k = i + 1 NEW_LINE steps = 0 NEW_LINE ch = str [ i ] NEW_LINE while ( k <= j ) : NEW_LINE INDENT if ( str [ k ] != ch ) : NEW_LINE INDENT steps = steps + 1 NEW_LINE ch = str [ k ] NEW_LINE DEDENT k = k + 1 NEW_LINE DEDENT return steps NEW_LINE DEDENT def getMinSteps ( ... |
Count distinct substrings that contain some characters at most k times | Python3 implementation of the approach ; Function to return the count of valid sub - strings ; Store all characters of anotherStr in a direct index table for quick lookup . ; To store distinct output substrings ; Traverse through the given string ... | MAX_CHAR = 256 NEW_LINE def countSubStrings ( s , anotherStr , k ) : NEW_LINE INDENT illegal = [ False ] * MAX_CHAR NEW_LINE for i in range ( len ( anotherStr ) ) : NEW_LINE INDENT illegal [ ord ( anotherStr [ i ] ) ] = True NEW_LINE DEDENT us = set ( ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ss = " " N... |
Count pairs of parentheses sequences such that parentheses are balanced | Python3 program to count the number of pairs of balanced parentheses ; Function to count the number of pairs ; Hashing function to count the opening and closing brackets ; Traverse for all bracket sequences ; Get the string ; Counts the opening a... | import math as mt NEW_LINE def countPairs ( bracks , num ) : NEW_LINE INDENT openn = dict ( ) NEW_LINE close = dict ( ) NEW_LINE cnt = 0 NEW_LINE for i in range ( num ) : NEW_LINE INDENT s = bracks [ i ] NEW_LINE l = len ( s ) NEW_LINE op , cl = 0 , 0 NEW_LINE for j in range ( l ) : NEW_LINE INDENT if ( s [ j ] == ' ( ... |
Decrypt a string according to given rules | Function to return the original string after decryption ; Stores the decrypted string ; If length is odd ; Step counter ; Starting and ending index ; Iterate till all characters are decrypted ; Even step ; Odd step ; If length is even ; Step counter ; Starting and ending inde... | def decrypt ( s , l ) : NEW_LINE INDENT ans = " " NEW_LINE if ( l % 2 ) : NEW_LINE INDENT cnt = 0 NEW_LINE indl = 0 NEW_LINE indr = l - 1 NEW_LINE while ( len ( ans ) != l ) : NEW_LINE INDENT if ( cnt % 2 == 0 ) : NEW_LINE INDENT ans += s [ indl ] NEW_LINE indl += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += s [ ind... |
Remove consecutive alphabets which are in same case | Function to return the modified string ; Traverse through the remaining characters in the string ; If the current and the previous characters are not in the same case then take the character ; Driver code | def removeChars ( s ) : NEW_LINE INDENT modifiedStr = " " NEW_LINE modifiedStr += s [ 0 ] NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] . isupper ( ) and s [ i - 1 ] . islower ( ) or s [ i ] . islower ( ) and s [ i - 1 ] . isupper ( ) ) : NEW_LINE INDENT modifiedStr += s [ i ] NEW_LINE DEDENT... |
Cost to make a string Panagram | Function to return the total cost required to make the string Pangram ; Mark all the alphabets that occurred in the string ; Calculate the total cost for the missing alphabets ; Driver Code | def pangramCost ( arr , string ) : NEW_LINE INDENT cost = 0 NEW_LINE occurred = [ False ] * 26 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT occurred [ ord ( string [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( not occurred [ i ] ) : NEW_LINE INDENT cost +=... |
Recursive program to insert a star between pair of identical characters | Function to insert * at desired position ; Append current character ; If we reached last character ; If next character is same , append '* ; Driver code | def pairStar ( Input , Output , i = 0 ) : NEW_LINE INDENT Output = Output + Input [ i ] NEW_LINE if ( i == len ( Input ) - 1 ) : NEW_LINE INDENT print ( Output ) NEW_LINE return ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( Input [ i ] == Input [ i + 1 ] ) : NEW_LINE INDENT Output = Output + ' * ' ; NEW_LINE DEDENT p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.