text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count distinct strings possible by replacing each character by its Morse code | Function to count unique array elements by replacing each character by its Morse code ; Stores Morse code of all lowercase characters ; Stores distinct elements of String by replacing each character by Morse code ; Stores length of arr arra...
def uniqueMorseRep ( arr ) : NEW_LINE INDENT morseCode = [ " . - " , " - . . . " , " - . - . " , " - . . " , " . " , " . . - . " , " - - . " , " . . . . " , " . . " , " . - - - " , " - . - " , " . - . . " , " - - " , " - . " , " - - - " , " . - - . " , " - - . - " , " . - . " , " . . . " , " - " , " . . - " , " . . . -...
Maximum repeating character for every index in given String | Function to print the maximum repeating character at each index of the string ; Stores frequency of each distinct character ; Stores frequency of maximum repeating character ; Stores the character having maximum frequency ; Traverse the string ; Stores curre...
def findFreq ( strr , N ) : NEW_LINE INDENT freq = [ 0 ] * 256 NEW_LINE max = 0 NEW_LINE charMax = '0' NEW_LINE for i in range ( N ) : NEW_LINE INDENT ch = ord ( strr [ i ] ) NEW_LINE freq [ ch ] += 1 NEW_LINE if ( freq [ ch ] >= max ) : NEW_LINE INDENT max = freq [ ch ] NEW_LINE charMax = ch NEW_LINE DEDENT print ( ch...
Minimize cost to convert given string to a palindrome | Function to find the minimum cost to convert the into a palindrome ; Length of the string ; If iointer is in the second half ; Reverse the string ; Find the farthest index needed to change on left side ; Find the farthest index needed to change on right side ; Cha...
def findMinCost ( strr , pos ) : NEW_LINE INDENT n = len ( strr ) NEW_LINE if ( pos >= n / 2 ) : NEW_LINE INDENT strr = strr [ : : - 1 ] NEW_LINE pos = n - pos - 1 NEW_LINE DEDENT left , right = pos , pos NEW_LINE for i in range ( pos , - 1 , - 1 ) : NEW_LINE INDENT if ( strr [ i ] != strr [ n - i - 1 ] ) : NEW_LINE IN...
Minimize replacements by previous or next alphabet required to make all characters of a string the same | Function to find the minimum count of operations to make all characters of the string same ; Set min to some large value ; Find minimum operations for each character ; Initialize cnt ; Add the value to cnt ; Update...
def minCost ( s , n ) : NEW_LINE INDENT minValue = 100000000 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT cnt += min ( abs ( i - ( ord ( s [ j ] ) - ord ( ' a ' ) ) ) , 26 - abs ( i - ( ord ( s [ j ] ) - ord ( ' a ' ) ) ) ) NEW_LINE DEDENT minValue = min ( min...
Longest palindromic string possible by concatenating strings from a given array | Python3 program for the above approach ; Stores the distinct strings from the given array ; Insert the strings into set ; Stores the left and right substrings of the given string ; Stores the middle substring ; Traverse the array of strin...
def max_len ( s , N , M ) : NEW_LINE INDENT set_str = { } NEW_LINE for i in s : NEW_LINE INDENT set_str [ i ] = 1 NEW_LINE DEDENT left_ans , right_ans = [ ] , [ ] NEW_LINE mid = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT t = s [ i ] NEW_LINE t = t [ : : - 1 ] NEW_LINE if ( t == s [ i ] ) : NEW_LINE INDENT mid ...
Minimize steps defined by a string required to reach the destination from a given source | Function to find the minimum length of string required to reach from source to destination ; Size of the string ; Stores the index of the four directions E , W , N , S ; If destination reached ; Iterate over the string ; Move eas...
def minimum_length ( x1 , y1 , x2 , y2 , str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE pos1 = - 1 NEW_LINE pos2 = - 1 NEW_LINE pos3 = - 1 NEW_LINE pos4 = - 1 NEW_LINE if ( x1 == x2 and y1 == y2 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( x2 > x...
Remove all duplicate adjacent characters from a string using Stack | Function to remove adjacent duplicate elements ; Store the string without duplicate elements ; Store the index of str ; Traverse the string str ; Checks if stack is empty or top of the stack is not equal to current character ; If top element of the st...
def ShortenString ( str1 ) : NEW_LINE INDENT st = [ ] NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) : NEW_LINE INDENT if len ( st ) == 0 or str1 [ i ] != st [ - 1 ] : NEW_LINE INDENT st . append ( str1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if...
Count ways to place all the characters of two given strings alternately | Function to get the factorial of N ; Function to get the total number of distinct ways ; Length of str1 ; Length of str2 ; If both strings have equal length ; If both strings do not have equal length ; Driver code
def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def distinctWays ( str1 , str2 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE if ( n == m ) : NEW_LINE INDENT return 2 * fact ( n ) * fact ( ...
Smallest string without any multiplication sign that represents the product of two given numbers | Python3 program for the above approach ; Function to find the string which evaluates to the product of A and B ; Stores the result ; 2 ^ logg <= B && 2 ^ ( logg + 1 ) > B ; Update res to res += A X 2 ^ logg ; Update res t...
from math import log NEW_LINE def lenn ( A , B ) : NEW_LINE INDENT res = " " NEW_LINE logg = 0 NEW_LINE while True : NEW_LINE INDENT logg = log ( B ) // log ( 2 ) NEW_LINE if ( logg != 0 ) : NEW_LINE INDENT res += ( str ( A ) + " < < " + str ( int ( logg ) ) ) NEW_LINE DEDENT else : NEW_LINE INDENT res += A NEW_LINE br...
Count substrings of a given string whose anagram is a palindrome | Function to prcount of subStrings whose anagrams are palindromic ; Stores the answer ; Iterate over the String ; Set the current character ; Parity update ; Print final count ; Driver Code ; Function Call
def countSubString ( s ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT x = 0 ; NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT temp = 1 << ord ( s [ j ] ) - ord ( ' a ' ) ; NEW_LINE x ^= temp ; NEW_LINE if ( ( x & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT res += 1 ; NEW_LINE...
Count substrings of a given string whose anagram is a palindrome | Python3 program for the above approach ; Function to get the count of substrings whose anagrams are palindromic ; Store the answer ; Map to store the freq of masks ; Set frequency for mask 00. . .00 to 1 ; Store mask in x from 0 to i ; Update answer ; U...
from collections import defaultdict NEW_LINE def countSubstring ( s ) : NEW_LINE INDENT answer = 0 NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE m [ 0 ] = 1 NEW_LINE x = 0 NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT x ^= 1 << ( ord ( s [ j ] ) - ord ( ' a ' ) ) NEW_LINE answer += m [ x ] NEW_LINE for i i...
Sum of an array of large numbers | Function to prthe result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer...
def printResult ( result ) : NEW_LINE INDENT result = result [ : : - 1 ] NEW_LINE i = 0 NEW_LINE while ( i < len ( result ) ) : NEW_LINE INDENT print ( result [ i ] , end = " " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def sumOfLargeNumbers ( v , k , N ) : NEW_LINE INDENT x = [ [ ] for i in range ( 1000 ) ] NEW_LINE for...
Reverse words in a given string | Set 2 | Function to reverse the words of a given string ; Stack to store each word of the string ; Store the whole string in stream ; Push each word of the into the stack ; Print the in reverse order of the words ; Driver Code
def printRev ( strr ) : NEW_LINE INDENT strr = strr . split ( " ▁ " ) NEW_LINE st = [ ] NEW_LINE for i in strr : NEW_LINE INDENT st . append ( i ) NEW_LINE DEDENT while len ( st ) > 0 : NEW_LINE INDENT print ( st [ - 1 ] , end = " ▁ " ) NEW_LINE del st [ - 1 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NE...
Count of substrings of a Binary string containing only 1 s | Function to find the total number of substring having only ones ; Driver Code
def countOfSubstringWithOnlyOnes ( s ) : NEW_LINE INDENT count = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] == '1' : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 ; NEW_LINE DEDENT res = res + count NEW_LINE DEDENT return res NEW_LINE D...
Count of Distinct strings possible by inserting K characters in the original string | Python3 program for the above approach ; Function to calculate and return x ^ n in log ( n ) time using Binary Exponentiation ; Function to calculate the factorial of a number ; Function to calculate combination ; nCi = ( n ! ) / ( ( ...
mod = 1000000007 NEW_LINE def binExp ( base , power ) : NEW_LINE INDENT x = 1 NEW_LINE while ( power ) : NEW_LINE INDENT if ( power % 2 == 1 ) : NEW_LINE INDENT x = ( ( ( x % mod ) * ( base % mod ) ) % mod ) NEW_LINE DEDENT base = ( ( ( base % mod ) * ( base % mod ) ) % mod ) NEW_LINE power = power // 2 NEW_LINE DEDENT...
Calculate Sum of ratio of special characters to length of substrings of the given string | Python3 program to implement the above approach ; Stores frequency of special characters in the array ; Stores prefix sum ; Function to check whether a character is special or not ; If current character is special ; Otherwise ; F...
N = 100005 NEW_LINE prefix = [ 0 ] * N NEW_LINE sum = [ 0 ] * N NEW_LINE def isSpecial ( c , special ) : NEW_LINE INDENT for i in special : NEW_LINE INDENT if ( i == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def countRatio ( s , special ) : NEW_LINE INDENT n = len ( s ) NEW_L...
Minimum replacements in a string to make adjacent characters unequal | Function which counts the minimum number of required operations ; n stores the length of the string s ; ans will store the required ans ; i is the current index in the string ; Move j until characters s [ i ] & s [ j ] are equal or the end of the st...
def count_minimum ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT j = i NEW_LINE while j < n and ( s [ j ] == s [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT diff = j - i NEW_LINE ans += diff // 2 NEW_LINE i = j NEW_LINE DEDENT print ( ans ) NEW_LINE DEDEN...
Minimum cost to convert given string to consist of only vowels | Function to find the minimum cost ; Store vowels ; Loop for iteration of string ; Loop to calculate the cost ; Add minimum cost ; Given String ; Function Call
def min_cost ( st ) : NEW_LINE INDENT vow = " aeiou " NEW_LINE cost = 0 NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT costs = [ ] NEW_LINE for j in range ( 5 ) : NEW_LINE INDENT costs . append ( abs ( ord ( st [ i ] ) - ord ( vow [ j ] ) ) ) NEW_LINE DEDENT cost += min ( costs ) NEW_LINE DEDENT return cost N...
Check if a given string is Even | Function to check if the string str is palindromic or not ; Pointers to iterate the string from both ends ; If characters are found to be distinct ; Return true if the string is palindromic ; Function to generate string from characters at odd indices ; Function to generate string from ...
def isPalindrome ( Str ) : NEW_LINE INDENT l = 0 NEW_LINE h = len ( Str ) - 1 NEW_LINE while ( h > l ) : NEW_LINE INDENT if ( Str [ l ] != Str [ h ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def makeOddString ( Str ) : NEW_LINE INDENT odd = " " N...
Check given string is oddly palindrome or not | Function to check if the string str is palindromic or not ; Iterate the string str from left and right pointers ; Keep comparing characters while they are same ; If they are not same then return false ; Return true if the string is palindromic ; Function to make string us...
def isPalindrome ( str ) : NEW_LINE INDENT l = 0 ; NEW_LINE h = len ( str ) - 1 ; NEW_LINE while ( h > l ) : NEW_LINE INDENT if ( str [ l ] != str [ h ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT l += 1 NEW_LINE h -= 1 NEW_LINE DEDENT return True ; NEW_LINE DEDENT def makeOddString ( str ) : NEW_LINE INDENT odd...
Count of binary strings of given length consisting of at least one 1 | Function to return the count of Strings ; Calculate pow ( 2 , n ) ; Return pow ( 2 , n ) - 1 ; Driver Code
def count_Strings ( n ) : NEW_LINE INDENT x = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT x = ( 1 << x ) ; NEW_LINE DEDENT return x - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE print ( count_Strings ( n ) ) ; NEW_LINE DEDENT
String formed with middle character of every right substring followed by left sequentially | Function to decrypt and print the new string ; If the whole string has been traversed ; To calculate middle index of the string ; Print the character at middle index ; Recursively call for right - substring ; Recursive call for...
def decrypt ( Str , Start , End ) : NEW_LINE INDENT if ( Start > End ) : NEW_LINE INDENT return ; NEW_LINE DEDENT mid = ( Start + End ) >> 1 ; NEW_LINE print ( Str [ mid ] , end = " " ) ; NEW_LINE decrypt ( Str , mid + 1 , End ) ; NEW_LINE decrypt ( Str , Start , mid - 1 ) ; NEW_LINE DEDENT N = 4 ; NEW_LINE Str = " abc...
Check whether the binary equivalent of a number ends with given string or not | Function returns true if s1 is suffix of s2 ; Function to check if binary equivalent of a number ends in "111" or not ; To store the binary number ; Count used to store exponent value ; Driver code
def isSuffix ( s1 , s2 ) : NEW_LINE INDENT n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE if ( n1 > n2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( n1 ) : NEW_LINE INDENT if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE ...
Count of substrings consisting only of vowels | Function to check if a character is vowel or not ; Function to check whether string contains only vowel ; Check if the character is not vowel then invalid ; Function to Count all substrings in a string which contains only vowels ; Generate all substring of s ; If temp con...
def isvowel ( ch ) : NEW_LINE INDENT return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) NEW_LINE DEDENT def isvalid ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( not isvowel ( s [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT r...
Longest substring of vowels with no two adjacent alphabets same | Function to check a character is vowel or not ; Function to check a substring is valid or not ; If size is 1 then check only first character ; If 0 'th character is not vowel then invalid ; If two adjacent characters are same or i 'th char is not vowel...
def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def isValid ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return ( isVowel ( s [ 0 ] ) ) NEW_LINE DEDENT if ( isVowel ( s [ 0 ] ) == False ) : NEW_LINE INDEN...
Check if the number is balanced | Function to check whether N is Balanced Number or not ; Calculating the Leftsum and rightSum simultaneously ; Typecasting each character to integer and adding the digit to respective sums ; Driver Code ; Function call
def BalancedNumber ( s ) : NEW_LINE INDENT Leftsum = 0 NEW_LINE Rightsum = 0 NEW_LINE for i in range ( 0 , int ( len ( s ) / 2 ) ) : NEW_LINE INDENT Leftsum = Leftsum + int ( s [ i ] ) NEW_LINE Rightsum = ( Rightsum + int ( s [ len ( s ) - 1 - i ] ) ) NEW_LINE DEDENT if ( Leftsum == Rightsum ) : NEW_LINE INDENT print (...
Count of N size strings consisting of at least one vowel and one consonant | Python3 program to count all possible strings of length N consisting of atleast one vowel and one consonant ; Function to return base ^ exponent ; Function to count all possible strings ; All possible strings of length N ; vowels only ; conson...
mod = 1e9 + 7 NEW_LINE def expo ( base , exponent ) : NEW_LINE INDENT ans = 1 NEW_LINE while ( exponent != 0 ) : NEW_LINE INDENT if ( ( exponent & 1 ) == 1 ) : NEW_LINE INDENT ans = ans * base NEW_LINE ans = ans % mod NEW_LINE DEDENT base = base * base NEW_LINE base %= mod NEW_LINE exponent >>= 1 NEW_LINE DEDENT return...
Sum of decomposition values of all suffixes of an Array | Python3 implementation to find the sum of Decomposition values of all suffixes of an array ; Function to find the decomposition values of the array ; Stack ; Variable to maintain min value in stack ; Loop to iterate over the array ; Condition to check if the sta...
import sys NEW_LINE def decompose ( S ) : NEW_LINE INDENT s = [ ] NEW_LINE N = len ( S ) NEW_LINE ans = 0 NEW_LINE nix = sys . maxsize NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( S [ i ] ) NEW_LINE nix = S [ i ] NEW_LINE DEDENT else : NEW_LINE IND...
Maximum number of set bits count in a K | Function that find Maximum number of set bit appears in a substring of size K . ; Traverse string 1 to k ; Increment count if character is set bit ; Traverse string k + 1 to length of string ; Remove the contribution of the ( i - k ) th character which is no longer in the windo...
def maxSetBitCount ( s , k ) : NEW_LINE INDENT maxCount = 0 NEW_LINE n = len ( s ) NEW_LINE count = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT maxCount = count NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT if ( s [ i - k ] == '1' ) :...
Minimum characters to be deleted from the beginning of two strings to make them equal | Function that finds minimum character required to be deleted ; Iterate in the strings ; Check if the characters are not equal ; Return the result ; Driver code
def minDel ( s1 , s2 ) : NEW_LINE INDENT i = len ( s1 ) NEW_LINE j = len ( s2 ) NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( s1 [ i - 1 ] != s2 [ j - 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT return i + j NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE ...
Minimum characters to be deleted from the end to make given two strings equal | Function that finds minimum character required to be deleted ; Iterate in the strings ; Check if the characters are not equal ; Return the result ; Driver code
def minDel ( s1 , s2 ) : NEW_LINE INDENT i = 0 ; NEW_LINE while ( i < min ( len ( s1 ) , len ( s2 ) ) ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT ans = ( ( len ( s1 ) - i ) + ( len ( s2 ) - i ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ =...
Check if given Parentheses expression is balanced or not | Function to check if parenthesis are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more closing parenthesis than opening ; If count is not zero , it means there are more opening parenthesis ; ...
def isBalanced ( exp ) : NEW_LINE INDENT flag = True NEW_LINE count = 0 NEW_LINE for i in range ( len ( exp ) ) : NEW_LINE INDENT if ( exp [ i ] == ' ( ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < 0 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LI...
Check if a given string can be formed using characters of adjacent cells of a Matrix | Function to check if the word exists ; If index exceeds board range ; If the current cell does not contain the required character ; If the cell contains the required character and is the last character of the word required to be matc...
def checkWord ( board , word , index , row , col ) : NEW_LINE INDENT if ( row < 0 or col < 0 or row >= len ( board ) or col >= len ( board [ 0 ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( board [ row ] [ col ] != word [ index ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( index == len ( word ) -...
Split the number N by maximizing the count of subparts divisible by K | Function to count the subparts ; Total subStr till now ; If it can be divided , then this substring is one of the possible answer ; Convert string to long long and check if its divisible with X ; Consider there is no vertical cut between this index...
def count ( N , X , subStr , index , n ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT a = subStr + N [ index ] NEW_LINE b = 0 NEW_LINE if ( int ( a ) % X == 0 ) : NEW_LINE INDENT b = 1 NEW_LINE DEDENT m1 = count ( N , X , a , index + 1 , n ) NEW_LINE m2 = b + count ( N , X , " " , inde...
Check if a number ends with another number or not | Function to check if B is a suffix of A or not ; Convert numbers into strings ; Find the lengths of strings s1 and s2 ; Base Case ; Traverse the strings s1 & s2 ; If at any index characters are unequals then return false ; Return true ; Given numbers ; Function Call ;...
def checkSuffix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) ; NEW_LINE s2 = str ( B ) ; NEW_LINE n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE if ( n1 < n2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) : NEW_LINE INDENT return...
Check if a number ends with another number or not | Function to check if B is a suffix of A or not ; Convert numbers into strings ; Check if s2 is a suffix of s1 or not ; If result is true print " Yes " ; Driver code ; Given numbers ; Function call
def checkSuffix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) NEW_LINE s2 = str ( B ) NEW_LINE result = s1 . endswith ( s2 ) NEW_LINE if ( result ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 12345 ...
Binary string with given frequencies of sums of consecutive pairs of characters | A Function that generates and returns the binary string ; P : Frequency of consecutive characters with sum 0 Q : Frequency of consecutive characters with sum 1 R : Frequency of consecutive characters with sum 2 ; If no consecutive charact...
def build_binary_str ( p , q , r ) : NEW_LINE INDENT ans = " " NEW_LINE if ( q == 0 ) : NEW_LINE INDENT if ( p != 0 and r != 0 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT else : NEW_LINE INDENT if ( p ) : NEW_LINE INDENT temp = " " NEW_LINE for i in range ( p + 1 ) : NEW_LINE INDENT temp += '0' NEW_LINE DEDENT an...
Check if there exists a permutation of given string which doesn 't contain any monotonous substring | Function to check a string doesn 't contains a monotonous substring ; Loop to iterate over the string and check that it doesn 't contains the monotonous substring ; Function to check that there exist a arrangement of ...
def check ( s ) : NEW_LINE INDENT ok = True NEW_LINE for i in range ( 0 , len ( s ) - 1 , 1 ) : NEW_LINE INDENT ok = ( ok & ( abs ( ord ( s [ i ] ) - ord ( s [ i + 1 ] ) ) != 1 ) ) NEW_LINE DEDENT return ok NEW_LINE DEDENT def monotonousString ( s ) : NEW_LINE INDENT odd = " " NEW_LINE even = " " NEW_LINE for i in rang...
Length of the smallest substring which contains all vowels | Function to return the index for respective vowels to increase their count ; Returns - 1 for consonants ; Function to find the minimum length ; Store the starting index of the current substring ; Store the frequencies of vowels ; If the current character is a...
def get_index ( ch ) : NEW_LINE INDENT if ( ch == ' a ' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( ch == ' e ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( ch == ' i ' ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif ( ch == ' o ' ) : NEW_LINE INDENT return 3 NEW_LINE DEDENT elif ( ch == ' u ' ) : NEW_...
Number of strings which starts and ends with same character after rotations | Function to find the count of string with equal end after rotations ; To store the final count ; Traverse the string ; If current character is same as the previous character then increment the count ; Return the final count ; Driver Code ; Gi...
def countStrings ( s ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( 1 , len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aacbb " ; NEW_LINE print ( countStri...
Check if frequency of each character is equal to its position in English Alphabet | Python3 program for the above approach ; Initialise frequency array ; Traverse the string ; Update the frequency ; Check for valid string ; If frequency is non - zero ; If freq is not equals to ( i + 1 ) , then return false ; Return tru...
def checkValidString ( str ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT if ( freq [ i ] != i + 1 ) : NEW_LI...
Print all the non | Function to print all the non - repeating words from the two given sentences ; Concatenate the two strings into one ; Iterating over the whole concatenated string ; Searching for the word in A . If while searching , we reach the end of the string , then the word is not present in the string ; Initia...
def removeRepeating ( s1 , s2 ) : NEW_LINE INDENT s3 = s1 + " ▁ " + s2 + " ▁ " NEW_LINE words = " " NEW_LINE i = 0 NEW_LINE for x in s3 : NEW_LINE INDENT if ( x == ' ▁ ' ) : NEW_LINE INDENT if ( words not in s1 or words not in s2 ) : NEW_LINE INDENT print ( words , end = " " ) NEW_LINE DEDENT words = " ▁ " NEW_LINE DED...
Convert the number from International system to Indian system | Function to convert a number represented in International numeric system to Indian numeric system . ; Find the length of the input string ; Removing all the separators ( , ) from the input string ; Reverse the input string ; Declaring the output string ; P...
def convert ( input ) : NEW_LINE INDENT Len = len ( input ) NEW_LINE i = 0 NEW_LINE while ( i < Len ) : NEW_LINE INDENT if ( input [ i ] == " , " ) : NEW_LINE INDENT input = input [ : i ] + input [ i + 1 : ] NEW_LINE Len -= 1 NEW_LINE i -= 1 NEW_LINE DEDENT elif ( input [ i ] == " ▁ " ) : NEW_LINE INDENT input = input ...
Construct the Cypher string based on the given conditions | Python3 program for the above approach ; Function to check whether a number is prime or not ; Function to check if a prime number can be expressed as sum of two Prime Numbers ; If the N && ( N - 2 ) is Prime ; Function to check semiPrime ; Loop from 2 to sqrt ...
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT sqt = ( int ) ( math . sqrt ( n ) ) NEW_LINE for i in range ( 2 , sqt ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPossib...
Maximum splits in binary string such that each substring is divisible by given odd number | Function to calculate maximum splits possible ; Driver code
def max_segments ( st , K ) : NEW_LINE INDENT n = len ( st ) NEW_LINE s , sum , count = 0 , 0 , 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT a = ord ( st [ i ] ) - 48 NEW_LINE sum += a * pow ( 2 , s ) NEW_LINE s += 1 NEW_LINE if ( sum != 0 and sum % K == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE su...
Make the string lexicographically smallest and non palindromic by replacing exactly one character | Function to find the required string ; Length of the string ; Iterate till half of the string ; Replacing a non ' a ' char with 'a ; Check if there is no ' a ' in string we replace last char of string by 'b ; If the inpu...
def findStr ( S ) : NEW_LINE INDENT S = list ( S ) NEW_LINE n = len ( S ) NEW_LINE for i in range ( 0 , n // 2 ) : NEW_LINE DEDENT ' NEW_LINE INDENT if S [ i ] != ' a ' : NEW_LINE INDENT S [ i ] = ' a ' NEW_LINE return ( ' ' . join ( S ) ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT S [ n - 1 ] = ' b ' NEW_LINE if n < 2 :...
Find the k | Function to find the Kth string in lexicographical order which consists of N - 2 xs and 2 ys ; Iterate for all possible positions of left most Y ; If i is the left most position of Y ; Put Y in their positions ; Driver code ; Function call
def kth_string ( n , k ) : NEW_LINE INDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if k <= ( n - i - 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( j == i or j == n - k ) : NEW_LINE INDENT print ( ' Y ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' X ' , end = " " ) NE...
Transform string str1 into str2 by taking characters from string str3 | Function to check whether str1 can be transformed to str2 ; To store the frequency of characters of string str3 ; Declare two pointers & flag ; Traverse both the string and check whether it can be transformed ; If both pointers point to same charac...
def convertString ( str1 , str2 , str3 ) : NEW_LINE INDENT freq = { } NEW_LINE for i in range ( len ( str3 ) ) : NEW_LINE INDENT if ( freq . get ( str3 [ i ] ) == None ) : NEW_LINE INDENT freq [ str3 [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq . get ( str3 [ i ] , 1 ) NEW_LINE DEDENT DEDENT ptr1 = 0 NEW_LIN...
Decrypt the String according to given algorithm | Python3 implementation of the approach ; Function that returns ( num % 26 ) ; Initialize result ; One by one process all digits of 'num ; Function to return the decrypted string ; To store the final decrypted answer ; One by one check for each character if it is a numer...
MOD = 26 NEW_LINE def modulo_by_26 ( num ) : NEW_LINE INDENT res = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( num ) ) : NEW_LINE INDENT res = ( ( res * 10 + ord ( num [ i ] ) - ord ( '0' ) ) % MOD ) NEW_LINE DEDENT return res NEW_LINE DEDENT def decrypt_message ( s ) : NEW_LINE INDENT decrypted_str = " ...
Maximum number of overlapping string | Function to find the maximum overlapping strings ; Get the current character ; Condition to check if the current character is the first character of the string T then increment the overlapping count ; Condition to check previous character is also occurred ; Update count of previou...
def maxOverlap ( S , T ) : NEW_LINE INDENT str = T NEW_LINE count = [ 0 for i in range ( len ( T ) ) ] NEW_LINE overlap = 0 NEW_LINE max_overlap = 0 NEW_LINE for i in range ( 0 , len ( S ) ) : NEW_LINE INDENT index = str . find ( S [ i ] ) NEW_LINE if ( index == 0 ) : NEW_LINE INDENT overlap += 1 NEW_LINE if ( overlap ...
Minimum number of operations required to make two strings equal | Python3 implementation to find the minimum number of operations to make two strings equal ; Function to find out parent of an alphabet ; Function to merge two different alphabets ; Merge a and b using rank compression ; Function to find the minimum numbe...
MAX = 500001 NEW_LINE parent = [ 0 ] * MAX NEW_LINE Rank = [ 0 ] * MAX NEW_LINE def find ( x ) : NEW_LINE INDENT if parent [ x ] == x : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return find ( parent [ x ] ) NEW_LINE DEDENT DEDENT def merge ( r1 , r2 ) : NEW_LINE INDENT if ( r1 != r2 ) : NEW_LINE I...
Find the N | Function to calculate nth permutation of string ; Creating an empty list ; Subtracting 1 from N because the permutations start from 0 in factroid method ; Loop to generate the factroid of the sequence ; Loop to generate nth permutation ; Remove 1 - element in each cycle ; Final answer ; Driver code
def string_permutation ( n , str ) : NEW_LINE INDENT s = [ ] NEW_LINE result = " " NEW_LINE str = list ( str ) NEW_LINE n = n - 1 NEW_LINE for i in range ( 1 , len ( str ) + 1 ) : NEW_LINE INDENT s . append ( n % i ) NEW_LINE n = int ( n / i ) NEW_LINE DEDENT for i in range ( len ( str ) ) : NEW_LINE INDENT a = s [ - 1...
Defanged Version of Internet Protocol Address | Function to generate a defanged version of IP address . ; Loop to iterate over the characters of the string ; Driver Code
def GeberateDefangIP ( str ) : NEW_LINE INDENT defangIP = " " ; NEW_LINE for c in str : NEW_LINE INDENT if ( c == ' . ' ) : NEW_LINE INDENT defangIP += " [ . ] " NEW_LINE DEDENT else : NEW_LINE INDENT defangIP += c ; NEW_LINE DEDENT DEDENT return defangIP ; NEW_LINE DEDENT str = "255.100.50.0" ; NEW_LINE print ( Gebera...
Longest palindromic string formed by concatenation of prefix and suffix of a string | Function used to calculate the longest prefix which is also a suffix ; Traverse the string ; Update the lps size ; Returns size of lps ; Function to calculate the length of longest palindromic substring which is either a suffix or pre...
def kmp ( s ) : NEW_LINE INDENT lps = [ 0 ] * ( len ( s ) ) NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT previous_index = lps [ i - 1 ] NEW_LINE while ( previous_index > 0 and s [ i ] != s [ previous_index ] ) : NEW_LINE INDENT previous_index = lps [ previous_index - 1 ] NEW_LINE DEDENT lps [ i ] = previ...
Generate a string with maximum possible alphabets with odd frequencies | Function to generate a string of length n with maximum possible alphabets each occuring odd number of times . ; If n is odd ; Add all characters from b - y ; Append a to fill the remaining length ; If n is even ; Add all characters from b - z ; Ap...
def generateTheString ( n ) : NEW_LINE INDENT ans = " " NEW_LINE if ( n % 2 ) : NEW_LINE INDENT for i in range ( min ( n , 24 ) ) : NEW_LINE INDENT ans += chr ( ord ( ' b ' ) + i ) NEW_LINE DEDENT if ( n > 24 ) : NEW_LINE INDENT for i in range ( ( n - 24 ) ) : NEW_LINE INDENT ans += ' a ' NEW_LINE DEDENT DEDENT DEDENT ...
Move all occurrence of letter ' x ' from the string s to the end using Recursion | Function to move all ' x ' in the end ; Store current character ; Check if current character is not 'x ; Recursive function call ; Check if current character is 'x ; Driver code
def moveAtEnd ( s , i , l ) : NEW_LINE INDENT if ( i >= l ) : NEW_LINE return NEW_LINE curr = s [ i ] NEW_LINE DEDENT ' NEW_LINE INDENT if ( curr != ' x ' ) : NEW_LINE INDENT print ( curr , end = " " ) NEW_LINE DEDENT moveAtEnd ( s , i + 1 , l ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( curr == ' x ' ) : NEW_LINE INDENT p...
Construct a string of length L such that each substring of length X has exactly Y distinct letters | Python implementation to construct a string of length L such that each substring of length X has exactly Y distinct letters . ; Initialize p equal to the ASCII value of a ; Iterate till the length of the string ; Driver...
def String ( l , x , y ) : NEW_LINE INDENT p = 97 NEW_LINE for j in range ( l ) : NEW_LINE INDENT ans = chr ( p + j % y ) NEW_LINE print ( ans , end = " " ) NEW_LINE DEDENT DEDENT l = 6 NEW_LINE x = 5 NEW_LINE y = 3 NEW_LINE String ( l , x , y ) NEW_LINE
Find the final co | Function to print the final position of the point after traversing through the given directions ; Traversing through the given directions ; If its north or south the point will move left or right ; If its west or east the point will move upwards or downwards ; Returning the final position ; Driver C...
def finalCoordinates ( SX , SY , D ) : NEW_LINE INDENT for i in range ( len ( D ) ) : NEW_LINE INDENT if ( D [ i ] == ' N ' ) : NEW_LINE INDENT SY += 1 NEW_LINE DEDENT elif ( D [ i ] == ' S ' ) : NEW_LINE INDENT SY -= 1 NEW_LINE DEDENT elif ( D [ i ] == ' E ' ) : NEW_LINE INDENT SX += 1 NEW_LINE DEDENT else : NEW_LINE ...
Frequency of smallest character in first sentence less than that of second sentence | Python3 program for the above approach ; Function to count the frequency of minimum character ; Sort the string s ; Return the count with smallest character ; Function to count number of frequency of smallest character of string arr1 ...
from bisect import bisect_right as upper_bound NEW_LINE def countMinFreq ( s ) : NEW_LINE INDENT s = sorted ( s ) NEW_LINE x = 0 NEW_LINE for i in s : NEW_LINE INDENT if i == s [ 0 ] : NEW_LINE INDENT x += 1 NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def countLessThan ( arr1 , arr2 ) : NEW_LINE INDENT freq = [ ] N...
Lexicographically all Shortest Palindromic Substrings from a given string | Function to find all lexicographically shortest palindromic substring ; Array to keep track of alphabetic characters ; Iterate to print all lexicographically shortest substring ; Driver code
def shortestPalindrome ( s ) : NEW_LINE INDENT abcd = [ 0 ] * 26 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT abcd [ ord ( s [ i ] ) - 97 ] = 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if abcd [ i ] == 1 : NEW_LINE INDENT print ( chr ( i + 97 ) , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT DEDENT s =...
Remove duplicates from string keeping the order according to last occurrences | Python3 program to remove duplicate character from character array and print sorted order ; Used as index in the modified string ; Traverse through all characters ; Check if str [ i ] is present before it ; If not present , then add it to r...
def removeDuplicates ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while j < n : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT res = res + str ...
Remove duplicates from string keeping the order according to last occurrences | Python3 program to remove duplicate character from character array and prin sorted order ; Used as index in the modified string ; Create an empty hash table ; Traverse through all characters from right to left ; If current character is not ...
def removeDuplicates ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE s = set ( ) NEW_LINE res = " " NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] not in s ) : NEW_LINE INDENT res = res + str [ i ] NEW_LINE s . add ( str [ i ] ) NEW_LINE DEDENT DEDENT res = res [ : : - 1 ] NEW_LINE re...
Count of numbers in a range that does not contain the digit M and which is divisible by M . | Function to count all the numbers which does not contain the digit ' M ' and is divisible by M ; Storing all the distinct digits of a number ; Checking if the two conditions are satisfied or not ; Driver code ; Lower Range ; U...
def contain ( L , U , M ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( L , U + 1 ) : NEW_LINE INDENT num = set ( str ( j ) ) NEW_LINE if ( j % M == 0 and str ( M ) not in num ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE L = 106...
Longest string which is prefix string of at least two strings | Python3 program to find longest string which is prefix string of at least two strings ; Function to find max length of the prefix ; Base case ; Iterating over all the alphabets ; Checking if char exists in current string or not ; If atleast 2 string have t...
max1 = 0 NEW_LINE def MaxLength ( v , i , m ) : NEW_LINE INDENT global max1 NEW_LINE if ( i >= m ) : NEW_LINE INDENT return m - 1 NEW_LINE DEDENT for k in range ( 26 ) : NEW_LINE INDENT c = chr ( ord ( ' a ' ) + k ) NEW_LINE v1 = [ ] NEW_LINE for j in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ j ] [ i ] == c ) : NE...
Periodic Binary String With Minimum Period and a Given Binary String as Subsequence . | Function to find the periodic string with minimum period ; Print the S if it consists of similar elements ; Find the required periodic with period 2 ; Driver Code
def findPeriodicString ( S ) : NEW_LINE INDENT l = 2 * len ( S ) NEW_LINE count = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == len ( S ) or count == 0 ) : NEW_LINE INDENT print ( S ) NEW_LINE DEDENT else : NEW_LINE INDE...
Print Strings In Reverse Dictionary Order Using Trie | Python3 program to print array of string in reverse dictionary order using trie ; Trie node ; endOfWord is true if the node represents end of a word ; Function will return the new node initialized NONE ; Initialize null to the all child ; Function will insert the s...
CHILDREN = 26 NEW_LINE MAX = 100 NEW_LINE class trie : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . child = [ 0 for i in range ( CHILDREN ) ] NEW_LINE self . endOfWord = False ; NEW_LINE DEDENT DEDENT def createNode ( ) : NEW_LINE INDENT temp = trie ( ) ; NEW_LINE temp . endOfWord = False ; NEW_LINE f...
Queries to find total number of duplicate character in range L to R in the string S | Python implementation to Find the total number of duplicate character in a range L to R for Q number of queries in a string S ; Vector of vector to store position of all characters as they appear in string ; Function to store position...
import bisect NEW_LINE v = [ [ ] for _ in range ( 26 ) ] NEW_LINE def calculate ( s : str ) -> None : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT DEDENT def query ( L : int , R : int ) -> None : NEW_LINE INDENT duplicates = 0 NEW_LI...
Count the minimum number of groups formed in a string | Function to count the minimum number of groups formed in the given string s ; Initializing count as one since the string is not NULL ; Comparing adjacent characters ; Driver Code
def group_formed ( S ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( len ( S ) - 1 ) : NEW_LINE INDENT a = S [ i ] NEW_LINE b = S [ i + 1 ] NEW_LINE if ( a != b ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " TTWWW " N...
Find the Substring with maximum product | Function to return the value of a character ; Function to find the maximum product sub ; To store subs ; Check if current product is maximum possible or not ; If product is 0 ; Return the sub with maximum product ; Driver code ; Function call
def value ( x ) : NEW_LINE INDENT return ( ord ( x ) - ord ( ' a ' ) ) NEW_LINE DEDENT def maximumProduct ( strr , n ) : NEW_LINE INDENT answer = " " NEW_LINE curr = " " NEW_LINE maxProduct = 0 NEW_LINE product = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT product *= value ( strr [ i ] ) NEW_LINE curr += strr [ i...
Sum of minimum and the maximum difference between two given Strings | Function to find the sum of the minimum and the maximum difference between two given strings ; Variables to store the minimum difference and the maximum difference ; Iterate through the length of the as both the given strings are of the same length ;...
def solve ( a , b ) : NEW_LINE INDENT l = len ( a ) NEW_LINE min = 0 NEW_LINE max = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( a [ i ] == ' + ' or b [ i ] == ' + ' or a [ i ] != b [ i ] ) : NEW_LINE INDENT max += 1 NEW_LINE DEDENT if ( a [ i ] != ' + ' and b [ i ] != ' + ' and a [ i ] != b [ i ] ) : NEW_LIN...
Minimum letters to be removed to make all occurrences of a given letter continuous | Function to find the minimum number of deletions required to make the occurrences of the given character K continuous ; Find the first occurrence of the given letter ; Iterate from the first occurrence till the end of the sequence ; Fi...
def noOfDeletions ( string , k ) : NEW_LINE INDENT ans = 0 ; cnt = 0 ; pos = 0 ; NEW_LINE while ( pos < len ( string ) and string [ pos ] != k ) : NEW_LINE INDENT pos += 1 ; NEW_LINE DEDENT i = pos ; NEW_LINE while ( i < len ( string ) ) : NEW_LINE INDENT while ( i < len ( string ) and string [ i ] == k ) : NEW_LINE IN...
Check whether an array of strings can correspond to a particular number X | Function to find the maximum base possible for the number N ; Function to find the decimal equivalent of the number ; Condition to check if the number is convertible to another base ; Function to check that the array can correspond to a number ...
def val ( c ) : NEW_LINE INDENT if ( c >= '0' and c <= '9' ) : NEW_LINE INDENT return int ( c ) NEW_LINE DEDENT else : NEW_LINE INDENT return c - ' A ' + 10 NEW_LINE DEDENT DEDENT def toDeci ( strr , base ) : NEW_LINE INDENT lenn = len ( strr ) NEW_LINE power = 1 NEW_LINE num = 0 NEW_LINE for i in range ( lenn - 1 , - ...
Count of same length Strings that exists lexicographically in between two given Strings | Function to find the count of strings less than given string lexicographically ; Find length of string s ; Looping over the string characters and finding strings less than that character ; Function to find the count of same length...
def LexicoLesserStrings ( s ) : NEW_LINE INDENT count = 0 NEW_LINE length = len ( s ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT count += ( ( ord ( s [ i ] ) - ord ( ' a ' ) ) * pow ( 26 , length - i - 1 ) ) NEW_LINE DEDENT return count NEW_LINE DEDENT def countString ( S1 , S2 ) : NEW_LINE INDENT countS1 = L...
Longest Subsequence of a String containing only vowels | Function to check whether a character is vowel or not ; Returns true if x is vowel ; Function to find the longest subsequence which contain all vowels ; Length of the string ; Iterating through the string ; Checking if the character is a vowel or not ; If it is a...
def isVowel ( x ) : NEW_LINE INDENT return ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' ) NEW_LINE DEDENT def longestVowelSubsequence ( str ) : NEW_LINE INDENT answer = " " NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isVowel ( str [ i ] ) ) : NEW_LINE INDENT ans...
Maximum repeated frequency of characters in a given string | Function to find the maximum repeated frequency of the characters in the given string ; Hash - Array to store the frequency of characters ; Loop to find the frequency of the characters ; Hash map to store the occurrence of frequencies of characters ; Loop to ...
def findMaxFrequency ( s ) : NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT arr [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT hash = { } NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT if arr [ i ] not in hash : NEW_LINE INDEN...
Generate string with Hamming Distance as half of the hamming distance between strings A and B | Function to find the required string ; Find the hamming distance between A and B ; If distance is odd , then resultant string is not possible ; Make the resultant string ; To store the final string ; Pick k characters from e...
def findString ( A , B ) : NEW_LINE INDENT dist = 0 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT dist += 1 ; NEW_LINE DEDENT DEDENT if ( dist & 1 ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res = " " ; NEW_LINE K = di...
Longest suffix such that occurrence of each character is less than N after deleting atmost K characters | Function to find the maximum length suffix in the string ; Length of the string ; Map to store the number of occurrence of character ; Loop to iterate string from the last character ; Condition to check if the occu...
def maximumSuffix ( s , n , k ) : NEW_LINE INDENT i = len ( s ) - 1 NEW_LINE arr = [ 0 for i in range ( 26 ) ] NEW_LINE suffix = " " NEW_LINE while ( i > - 1 ) : NEW_LINE INDENT index = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( arr [ index ] < n ) : NEW_LINE INDENT arr [ index ] += 1 NEW_LINE suffix += s [ i ] NE...
XOR of two Binary Strings | Function to find the XOR of the two Binary Strings ; Loop to iterate over the Binary Strings ; If the Character matches ; Driver Code
def xor ( a , b , n ) : NEW_LINE INDENT ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == b [ i ] ) : NEW_LINE INDENT ans += "0" NEW_LINE DEDENT else : NEW_LINE INDENT ans += "1" NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = "1010" NEW_LI...
Find Kth largest string from the permutations of the string with two characters | Function to print the kth largest string ; loop to iterate through series ; total takes the position of second y ; i takes the position of first y ; calculating first y position ; calculating second y position from first y ; print all x b...
def kthString ( n , k ) : NEW_LINE INDENT total = 0 NEW_LINE i = 1 NEW_LINE while ( total < k ) : NEW_LINE INDENT total = total + n - i NEW_LINE i += 1 NEW_LINE DEDENT first_y_position = i - 1 NEW_LINE second_y_position = k - ( total - n + first_y_position ) NEW_LINE for j in range ( 1 , first_y_position , 1 ) : NEW_LI...
Largest and Smallest N | Function to return the largest N - digit number in Octal Number System ; Append '7' N times ; Function to return the smallest N - digit number in Octal Number System ; Append '0' ( N - 1 ) times to 1 ; Function to print the largest and smallest N - digit Octal number ; Driver code ; Function Ca...
def findLargest ( N ) : NEW_LINE INDENT largest = strings ( N , '7' ) ; NEW_LINE return largest ; NEW_LINE DEDENT def findSmallest ( N ) : NEW_LINE INDENT smallest = "1" + strings ( ( N - 1 ) , '0' ) ; NEW_LINE return smallest ; NEW_LINE DEDENT def strings ( N , c ) : NEW_LINE INDENT temp = " " ; NEW_LINE for i in rang...
Count of substrings whose Decimal equivalent is greater than or equal to K | Function to count number of substring whose decimal equivalent is greater than or equal to K ; Left pointer of the substring ; Right pointer of the substring ; Loop to maintain the last occurrence of the 1 in the string ; Variable to count the...
def countSubstr ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE l = n - 1 NEW_LINE r = n - 1 NEW_LINE arr = [ 0 ] * n NEW_LINE last_indexof1 = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT arr [ i ] = i NEW_LINE last_indexof1 = i NEW_LINE DEDENT else : NEW_LINE INDENT ar...
Perfect Cube String | Python3 program to find if str1ing is a perfect cube or not . ; Finding ASCII values of each character and finding its sum ; Find the cube root of sum ; Check if sum is a perfect cube ; Driver code
from math import ceil NEW_LINE def isPerfectCubeString ( str1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT sum += ord ( str1 [ i ] ) NEW_LINE DEDENT cr = ceil ( ( sum ) ** ( 1 / 3 ) ) NEW_LINE return ( cr * cr * cr == sum ) NEW_LINE DEDENT str1 = " ll " NEW_LINE if ( isPerfectC...
Program to find the XOR of ASCII values of characters in a string | Function to find the XOR of ASCII value of characters in str1ing ; store value of first character ; Traverse str1ing to find the XOR ; Return the XOR ; Driver code
def XorAscii ( str1 , len1 ) : NEW_LINE INDENT ans = ord ( str1 [ 0 ] ) NEW_LINE for i in range ( 1 , len1 ) : NEW_LINE INDENT ans = ( ans ^ ( ord ( str1 [ i ] ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT str1 = " geeksforgeeks " NEW_LINE len1 = len ( str1 ) NEW_LINE print ( XorAscii ( str1 , len1 ) ) NEW_LINE str1...
CamelCase Pattern Matching | Function that prints the camel case pattern matching ; Map to store the hashing of each words with every uppercase letter found ; Traverse the words array that contains all the string ; Initialise str as empty ; length of string words [ i ] ; For every uppercase letter found map that upperc...
def CamelCase ( words , pattern ) : NEW_LINE INDENT map = dict . fromkeys ( words , None ) ; NEW_LINE for i in range ( len ( words ) ) : NEW_LINE INDENT string = " " ; NEW_LINE l = len ( words [ i ] ) ; NEW_LINE for j in range ( l ) : NEW_LINE INDENT if ( words [ i ] [ j ] >= ' A ' and words [ i ] [ j ] <= ' Z ' ) : NE...
Encryption and Decryption of String according to given technique | Python3 implementation for Custom Encryption and Decryption of String ; Function to encrypt the ; Matrix to generate the Encrypted String ; Fill the matrix row - wise ; Loop to generate encrypted ; Function to decrypt the ; Matrix to generate the Encryp...
from math import ceil , floor , sqrt NEW_LINE def encryption ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE b = ceil ( sqrt ( l ) ) NEW_LINE a = floor ( sqrt ( l ) ) NEW_LINE encrypted = " " NEW_LINE if ( b * a < l ) : NEW_LINE INDENT if ( min ( b , a ) == b ) : NEW_LINE INDENT b = b + 1 NEW_LINE DEDENT else : NEW_LINE...
Program to accept String starting with Capital letter | Function to check if first character is Capital ; Function to check ; Driver function
def checkIfStartsWithCapital ( string ) : NEW_LINE INDENT if ( string [ 0 ] >= ' A ' and string [ 0 ] <= ' Z ' ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT def check ( string ) : NEW_LINE INDENT if ( checkIfStartsWithCapital ( string ) ) : NEW_LINE INDENT print...
Program to accept a Strings which contains all the Vowels | Function to to check that a string contains all vowels ; Hash Array of size 5 such that the index 0 , 1 , 2 , 3 and 4 represent the vowels a , e , i , o and u ; Loop the string to mark the vowels which are present ; Loop to check if there is any vowel which is...
def checkIfAllVowels ( string ) : NEW_LINE INDENT hash = [ 0 ] * 5 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ' A ' or string [ i ] == ' a ' ) : NEW_LINE INDENT hash [ 0 ] = 1 ; NEW_LINE DEDENT elif ( string [ i ] == ' E ' or string [ i ] == ' e ' ) : NEW_LINE INDENT hash [ 1 ] ...
Smallest odd number with even sum of digits from the given number N | Function to find the smallest odd number whose sum of digits is even from the given string ; Converting the given string to a list of digits ; An empty array to store the digits ; For loop to iterate through each digit ; If the given digit is odd the...
def smallest ( s ) : NEW_LINE INDENT a = list ( s ) NEW_LINE b = [ ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( int ( a [ i ] ) % 2 != 0 ) : NEW_LINE INDENT b . append ( a [ i ] ) NEW_LINE DEDENT DEDENT b = sorted ( b ) NEW_LINE if ( len ( b ) > 1 ) : NEW_LINE INDENT return int ( b [ 0 ] ) * 10 + int ...
Number formed by deleting digits such that sum of the digits becomes even and the number odd | Function to convert a number into odd number such that digit - sum is odd ; Loop to find any first two odd number such that their sum is even and number is odd ; Print the result ; Driver Code
def converthenumber ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE res = " " ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' or s [ i ] == '3' or s [ i ] == '5' or s [ i ] == '7' or s [ i ] == '9' ) : NEW_LINE INDENT res += s [ i ] ; NEW_LINE DEDENT if ( len ( res ) == 2 ) : NEW_LINE IND...
Longest palindromic String formed using concatenation of given strings in any order | Function to find the longest palindromic from given array of strings ; Loop to find the pair of strings which are reverse of each other ; Loop to find if any palindromic is still left in the array ; Update the answer with all strings ...
def longestPalindrome ( a , n ) : NEW_LINE INDENT pair1 = [ 0 ] * n NEW_LINE pair2 = [ 0 ] * n NEW_LINE r = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = a [ i ] NEW_LINE s = s [ : : - 1 ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( a [ i ] != " " and a [ j ] != " " ) : NEW_LINE INDENT if ( s =...
Program to print the given digit in words | Function to return the word of the corresponding digit ; For digit 0 ; For digit 1 ; For digit 2 ; For digit 3 ; For digit 4 ; For digit 5 ; For digit 6 ; For digit 7 ; For digit 8 ; For digit 9 ; Function to iterate through every digit in the given number ; Finding each digi...
def printValue ( digit ) : NEW_LINE INDENT if digit == '0' : NEW_LINE INDENT print ( " Zero ▁ " , end = " ▁ " ) NEW_LINE DEDENT elif digit == '1' : NEW_LINE INDENT print ( " One ▁ " , end = " ▁ " ) NEW_LINE DEDENT elif digit == '2' : NEW_LINE INDENT print ( " Two ▁ " , end = " ▁ " ) NEW_LINE DEDENT elif digit == '3' : ...
Jaro and Jaro | Python3 implementation of above approach ; Function to calculate the Jaro Similarity of two s ; If the s are equal ; Length of two s ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first ; Check if there is any matches ; If there is a match ...
from math import floor , ceil NEW_LINE def jaro_distance ( s1 , s2 ) : NEW_LINE INDENT if ( s1 == s2 ) : NEW_LINE INDENT return 1.0 NEW_LINE DEDENT len1 = len ( s1 ) NEW_LINE len2 = len ( s2 ) NEW_LINE max_dist = floor ( max ( len1 , len2 ) / 2 ) - 1 NEW_LINE match = 0 NEW_LINE hash_s1 = [ 0 ] * len ( s1 ) NEW_LINE has...
Find the resultant String after replacing X with Y and removing Z | Function to replace and remove ; Two pointer start and end points to beginning and end position in the string ; If start is having Z find X pos in end and replace Z with another character ; Find location for having different character instead of Z ; If...
def replaceRemove ( s , X , Y , Z ) : NEW_LINE INDENT s = list ( s ) ; NEW_LINE start = 0 ; NEW_LINE end = len ( s ) - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT if ( s [ start ] == Z ) : NEW_LINE INDENT while ( end >= 0 and s [ end ] == Z ) : NEW_LINE INDENT end -= 1 ; NEW_LINE DEDENT if ( end > start ) : N...
Check if all bits can be made same by flipping two consecutive bits | Function to check if Binary string can be made equal ; Counting occurence of zero and one in binary string ; From above observation ; Driver code
def canMake ( s ) : NEW_LINE INDENT o = 0 ; z = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) == 1 ) : NEW_LINE INDENT o += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT z += 1 ; NEW_LINE DEDENT DEDENT if ( o % 2 == 1 and z % 2 == 1 ) : NEW_LINE INDENT return " NO " ; NEW_L...
Count of non | Python3 implementation of the above approach ; Function to find the count of the number of strings ; Loop to iterate over the frequency of character of string ; Reduce the frequency of current element ; Recursive call ; Backtrack ; Function to count the number of non - empty sequences ; store the frequen...
count = 0 NEW_LINE def countNumberOfStringsUtil ( freq , Count ) : NEW_LINE INDENT global count NEW_LINE count = Count NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT freq [ i ] -= 1 NEW_LINE count += 1 NEW_LINE countNumberOfStringsUtil ( freq , count ) ; NEW_LINE freq [ i ] += ...
Minimum swaps required to make a binary string divisible by 2 ^ k | Function to return the minimum swaps required ; To store the final answer ; To store the count of one and zero ; Loop from end of the string ; If s [ i ] = 1 ; If s [ i ] = 0 ; If c_zero = k ; If the result can 't be achieved ; Return the final answer...
def findMinSwaps ( s , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE c_one = 0 ; c_zero = 0 ; NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT c_one += 1 ; NEW_LINE DEDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT c_zero += 1 ; NEW_LINE ans += c_one ; NEW_LINE DED...
Remove vowels from a string stored in a Binary Tree | Structure Representing the Node in the Binary tree ; Function to perform a level order insertion of a Node in the Binary tree ; If the root is empty , make it point to the Node ; In case there are elements in the Binary tree , perform a level order traversal using a...
class Node : NEW_LINE INDENT def __init__ ( self , _val ) : NEW_LINE INDENT self . data = _val NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def addinBT ( root , data ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT root = Node ( data ) NEW_LINE DEDENT else : NEW_LINE INDENT Q = [ ] NEW_LIN...
Number of sub | Function to return the count of the required substrings ; To store the final answer ; Loop to find the answer ; Condition to update the answer ; Driver code
def countSubStr ( strr , lenn ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] == '0' ) : NEW_LINE INDENT ans += ( i + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT strr = "10010" NEW_LINE lenn = len ( strr ) NEW_LINE print ( countSubStr ( strr , lenn ) ) NEW_LINE
Smallest non | Function to return the length of the smallest subdivisible by 2 ^ k ; To store the final answer ; Left pointer ; Right pointer ; Count of the number of zeros and ones in the current substring ; Loop for two pointers ; Condition satisfied ; Updated the answer ; Update the pointer and count ; Update the po...
def findLength ( s , k ) : NEW_LINE INDENT ans = 10 ** 9 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE cnt_zero = 0 NEW_LINE cnt_one = 0 NEW_LINE while ( l < len ( s ) and r <= len ( s ) ) : NEW_LINE INDENT if ( cnt_zero >= k and cnt_one >= 1 ) : NEW_LINE INDENT ans = min ( ans , r - l ) NEW_LINE l += 1 NEW_LINE if ( s [ l - ...
Largest sub | Function to return the largest substring divisible by 2 ; While the last character of the string is '1' , pop it ; If the original string had no '0 ; Driver code
def largestSubStr ( s ) : NEW_LINE INDENT while ( len ( s ) and s [ len ( s ) - 1 ] == '1' ) : NEW_LINE INDENT s = s [ : len ( s ) - 1 ] ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return " - 1" ; NEW_LINE DEDENT else : NEW_LINE INDENT return s ; NEW_LINE DEDENT DEDENT if __name__...