text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Reduce Hamming distance by swapping two characters | Python 3 code to decrease hamming distance using swap . ; Function to return the swapped indexes to get minimum hamming distance . ; Find the initial hamming distance ; Case - I : To decrease distance by two ; ASCII values of present character . ; If two same letters... | MAX = 26 NEW_LINE def Swap ( s , t , n ) : NEW_LINE INDENT dp = [ [ - 1 for x in range ( MAX ) ] for y in range ( MAX ) ] NEW_LINE tot = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] != t [ i ] ) : NEW_LINE INDENT tot += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT a = ord ( s [ i ... |
Convert string X to an anagram of string Y with minimum replacements | Python3 program to convert string X to string Y which minimum number of changes . ; Function that converts string X into lexicographically smallest anagram of string Y with minimal changes ; Counting frequency of characters in each string . ; We mai... | MAX = 26 NEW_LINE def printAnagramAndChanges ( x , y ) : NEW_LINE INDENT x = list ( x ) NEW_LINE y = list ( y ) NEW_LINE countx , county = [ 0 ] * MAX , [ 0 ] * MAX NEW_LINE ctrx , ctry = [ 0 ] * MAX , [ 0 ] * MAX NEW_LINE change = 0 NEW_LINE l = len ( x ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT countx [ ord ( ... |
Count number of equal pairs in a string | Python3 program to count the number of pairs ; Function to count the number of equal pairs ; Hash table ; Traverse the string and count occurrence ; Stores the answer ; Traverse and check the occurrence of every character ; Driver code | MAX = 256 NEW_LINE def countPairs ( s ) : NEW_LINE INDENT cnt = [ 0 for i in range ( 0 , MAX ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - 97 ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 0 , MAX ) : NEW_LINE INDENT ans += cnt [ i ] * cnt [ i ] NEW_LINE DEDENT return ans... |
Find a string in lexicographic order which is in between given two strings | Function to find the lexicographically next string ; Iterate from last character ; If not ' z ' , increase by one ; if ' z ' , change it to 'a ; Driver Code ; If not equal , print the resultant string | def lexNext ( s , n ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if s [ i ] != ' z ' : NEW_LINE INDENT k = ord ( s [ i ] ) NEW_LINE s [ i ] = chr ( k + 1 ) NEW_LINE return ' ' . join ( s ) NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT s [ i ] = ' a ' NEW_LINE DEDENT if __name__ == " _ _ ... |
Find the arrangement of queue at given time | prints the arrangement at time = t ; Checking the entire queue for every moment from time = 1 to time = t . ; If current index contains ' B ' and next index contains ' G ' then swap ; Driver code | def solve ( n , t , p ) : NEW_LINE INDENT s = list ( p ) NEW_LINE for i in range ( 0 , t ) : NEW_LINE INDENT for j in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( s [ j ] == ' B ' and s [ j + 1 ] == ' G ' ) : NEW_LINE INDENT temp = s [ j ] ; NEW_LINE s [ j ] = s [ j + 1 ] ; NEW_LINE s [ j + 1 ] = temp ; NEW_LINE j = j + ... |
Add two numbers represented by two arrays | Return sum of two number represented by the arrays . Size of a [ ] is greater than b [ ] . It is made sure be the wrapper function ; array to store sum . ; Until we reach beginning of array . we are comparing only for second array because we have already compare the size of a... | def calSumUtil ( a , b , n , m ) : NEW_LINE INDENT sum = [ 0 ] * n NEW_LINE i = n - 1 NEW_LINE j = m - 1 NEW_LINE k = n - 1 NEW_LINE carry = 0 NEW_LINE s = 0 NEW_LINE while j >= 0 : NEW_LINE INDENT s = a [ i ] + b [ j ] + carry NEW_LINE sum [ k ] = ( s % 10 ) NEW_LINE carry = s // 10 NEW_LINE k -= 1 NEW_LINE i -= 1 NEW... |
Longest Common Anagram Subsequence | Python 3 implementation to find the length of the longest common anagram subsequence ; function to find the length of the longest common anagram subsequence ; List for storing frequencies of each character ; calculate frequency of each character of 'str1[] ; calculate frequency of e... | SIZE = 26 NEW_LINE def longCommomAnagramSubseq ( str1 , str2 , n1 , n2 ) : NEW_LINE INDENT freq1 = [ 0 ] * SIZE NEW_LINE freq2 = [ 0 ] * SIZE NEW_LINE l = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( n1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDEN... |
Panalphabetic window in a string | Return if given string contain panalphabetic window . ; traversing the string ; if character of string is equal to ch , increment ch . ; if all characters are found , return true . ; Driver Code | def isPanalphabeticWindow ( s , n ) : NEW_LINE INDENT ch = ' a ' NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == ch ) : NEW_LINE INDENT ch = chr ( ord ( ch ) + 1 ) NEW_LINE DEDENT if ( ch == ' z ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s = " abujm β zvcd ... |
Program to print characters present at prime indexes in a given string | Python3 program to print Characters at Prime index in a given String ; Corner case ; Check from 2 to n - 1 ; Function to print character at prime index ; Loop to check if index prime or not ; Driver Code | def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def prime_index ( input ) : NEW_LINE INDENT p = list ( input ) NEW_LINE s = " " NEW_LI... |
Check whether a given string is Heterogram or not | Python3 code to check whether the given string is Heterogram or not . ; traversing the string . ; ignore the space ; if already encountered ; else return false . ; Driven Code | def isHeterogram ( s , n ) : NEW_LINE INDENT hash = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] != ' β ' : NEW_LINE INDENT if hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] == 0 : NEW_LINE INDENT hash [ ord ( s [ i ] ) - ord ( ' a ' ) ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LIN... |
Print given sentence into its equivalent ASCII form | Function to compute the ASCII value of each character one by one ; Driver code | def ASCIISentence ( str ) : NEW_LINE INDENT for i in str : NEW_LINE INDENT print ( ord ( i ) , end = ' ' ) NEW_LINE DEDENT print ( ' ' , β end β = β ' ' ) NEW_LINE DEDENT str = " GeeksforGeeks " NEW_LINE print ( " ASCII β Sentence : " ) NEW_LINE ASCIISentence ( str ) NEW_LINE |
Snake case of a given sentence | Function to replace spaces and convert into snake case ; Converting space to underscor ; If not space , convert into lower character ; Driver program ; Calling function | def convert ( string ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE string = list ( string ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( string [ i ] == ' β ' ) : NEW_LINE INDENT string [ i ] = ' _ ' ; NEW_LINE DEDENT else : NEW_LINE INDENT string [ i ] = string [ i ] . lower ( ) ; NEW_LINE DEDENT DEDENT ... |
Find the size of largest subset of anagram words | Utility function to find size of largest subset of anagram ; sort the string ; Increment the count of string ; Compute the maximum size of string ; Driver code | def largestAnagramSet ( arr , n ) : NEW_LINE INDENT maxSize = 0 NEW_LINE count = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = ' ' . join ( sorted ( arr [ i ] ) ) NEW_LINE if arr [ i ] in count : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ arr [ i ] ] = 1 NE... |
Program to count vowels , consonant , digits and special characters in string . | Function to count number of vowels , consonant , digits and special character in a string . ; Declare the variable vowels , consonant , digit and special characters ; str . length ( ) function to count number of character in given string ... | def countCharacterType ( str ) : NEW_LINE INDENT vowels = 0 NEW_LINE consonant = 0 NEW_LINE specialChar = 0 NEW_LINE digit = 0 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT ch = str [ i ] NEW_LINE if ( ( ch >= ' a ' and ch <= ' z ' ) or ( ch >= ' A ' and ch <= ' Z ' ) ) : NEW_LINE INDENT ch = ch . lower... |
Next word that does not contain a palindrome and has characters from first k | Function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ASCII value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th... | def findNextWord ( s , m ) : NEW_LINE INDENT m += 97 NEW_LINE n = len ( s ) NEW_LINE i = len ( s ) - 1 NEW_LINE s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE while i >= 0 and i <= n - 1 : NEW_LINE INDENT if ord ( s [ i ] ) >= m : NEW_LINE INDENT s [ i ] = ' a ' NEW_LINE i -= 1 NEW_LINE s [ i ] = chr ( ord ( s [ i ] ) ... |
Replace a character c1 with c2 and c2 with c1 in a string S | Python3 program to replace c1 with c2 and c2 with c1 ; loop to traverse in the string ; check for c1 and replace ; check for c2 and replace ; Driver Code | def replace ( s , c1 , c2 ) : NEW_LINE INDENT l = len ( s ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( s [ i ] == c1 ) : NEW_LINE INDENT s = s [ 0 : i ] + c2 + s [ i + 1 : ] NEW_LINE DEDENT elif ( s [ i ] == c2 ) : NEW_LINE INDENT s = s [ 0 : i ] + c1 + s [ i + 1 : ] NEW_LINE DEDENT DEDENT return s NEW_LINE D... |
Fibonacci Word | Returns n - th Fibonacci word ; driver program | def fibWord ( n ) : NEW_LINE INDENT Sn_1 = "0" NEW_LINE Sn = "01" NEW_LINE tmp = " " NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT tmp = Sn NEW_LINE Sn += Sn_1 NEW_LINE Sn_1 = tmp NEW_LINE DEDENT return Sn NEW_LINE DEDENT n = 6 NEW_LINE print ( fibWord ( n ) ) NEW_LINE |
Change string to a new character set | function for converting the string ; find the index of each element of the string in the modified set of alphabets replace the element with the one having the same index in the actual set of alphabets ; Driver Code | def conversion ( charSet , str1 ) : NEW_LINE INDENT s2 = " " NEW_LINE for i in str1 : NEW_LINE INDENT s2 += alphabets [ charSet . index ( i ) ] NEW_LINE DEDENT return s2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT alphabets = " abcdefghijklmnopqrstuvwxyz " NEW_LINE charSet = " qwertyuiopasdfghjklz... |
Different substrings in a string that start and end with given strings | function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; We use a hash to make s... | def numberOfDifferentSubstrings ( s , a , b ) : NEW_LINE INDENT ans = 0 NEW_LINE ls = len ( s ) NEW_LINE la = len ( a ) NEW_LINE lb = len ( b ) NEW_LINE x = [ 0 ] * ls NEW_LINE y = [ 0 ] * ls NEW_LINE for i in range ( ls ) : NEW_LINE INDENT if ( s [ i : la + i ] == a ) : NEW_LINE INDENT x [ i ] = 1 NEW_LINE DEDENT if (... |
Printing string in plus β + β pattern in the matrix | Python 3 program to print the string in ' plus ' pattern ; Function to make a cross in the matrix ; As , it is not possible to make the cross exactly in the middle of the matrix with an even length string . ; declaring a 2D array i . e a matrix ; Now , we will fill ... | max = 100 NEW_LINE def carveCross ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT print ( " Not β possible . β Please β enter β " , " odd length string . " ) NEW_LINE DEDENT else : NEW_LINE INDENT arr = [ [ False for x in range ( max ) ] for y in range ( max ) ] NEW_LINE m = n /... |
Binary String of given length that without a palindrome of size 3 | Python3 program find a binary String of given length that doesn 't contain a palindrome of size 3. ; Printing the character according to i ; Driver code | def generateString ( n ) : NEW_LINE INDENT s = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( i & 2 ) > 1 ) : NEW_LINE INDENT s += ' b ' ; NEW_LINE DEDENT else : NEW_LINE INDENT s += ' a ' ; NEW_LINE DEDENT DEDENT print ( s ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_... |
Print all subsequences of a string | Iterative Method | function to find subsequence ; check if jth bit in binary is 1 ; if jth bit is 1 , include it in subsequence ; function to print all subsequences ; map to store subsequence lexicographically by length ; Total number of non - empty subsequence in string is 2 ^ len ... | def subsequence ( s , binary , length ) : NEW_LINE INDENT sub = " " NEW_LINE for j in range ( length ) : NEW_LINE INDENT if ( binary & ( 1 << j ) ) : NEW_LINE INDENT sub += s [ j ] NEW_LINE DEDENT DEDENT return sub NEW_LINE DEDENT def possibleSubsequences ( s ) : NEW_LINE INDENT sorted_subsequence = { } NEW_LINE length... |
Print all subsequences of a string | Iterative Method | Python3 program to print all Subsequences of a string in an iterative manner ; function to find subsequence ; loop while binary is greater than ; get the position of rightmost set bit ; append at beginning as we are going from LSB to MSB ; resets bit at pos in bin... | from math import log2 , floor NEW_LINE def subsequence ( s , binary ) : NEW_LINE INDENT sub = " " NEW_LINE while ( binary > 0 ) : NEW_LINE INDENT pos = floor ( log2 ( binary & - binary ) + 1 ) NEW_LINE sub = s [ pos - 1 ] + sub NEW_LINE binary = ( binary & ~ ( 1 << ( pos - 1 ) ) ) NEW_LINE DEDENT sub = sub [ : : - 1 ] ... |
Program to find remainder when large number is divided by 11 | Function to return remainder ; len is variable to store the length of number string . ; loop that find remainder ; Driver code | def remainder ( st ) : NEW_LINE INDENT ln = len ( st ) NEW_LINE rem = 0 NEW_LINE for i in range ( 0 , ln ) : NEW_LINE INDENT num = rem * 10 + ( int ) ( st [ i ] ) NEW_LINE rem = num % 11 NEW_LINE DEDENT return rem NEW_LINE DEDENT st = "3435346456547566345436457867978" NEW_LINE print ( remainder ( st ) ) NEW_LINE |
Longest subsequence of the form 0 * 1 * 0 * in a binary string | Returns length of the longest subsequence of the form 0 * 1 * 0 * ; Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i -... | def longestSubseq ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE pre_count_0 = [ 0 for i in range ( n + 2 ) ] NEW_LINE pre_count_1 = [ 0 for i in range ( n + 1 ) ] NEW_LINE post_count_0 = [ 0 for i in range ( n + 2 ) ] NEW_LINE pre_count_0 [ 0 ] = 0 NEW_LINE post_count_0 [ n + 1 ] = 0 NEW_LINE pre_count_1 [ 0 ] = 0 NEW... |
Distinct permutations of the string | Set 2 | Returns true if str [ curr ] does not matches with any of the characters after str [ start ] ; Prints all distinct permutations in str [ 0. . n - 1 ] ; Proceed further for str [ i ] only if it doesn 't match with any of the characters after str[index] ; Driver code | def shouldSwap ( string , start , curr ) : NEW_LINE INDENT for i in range ( start , curr ) : NEW_LINE INDENT if string [ i ] == string [ curr ] : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def findPermutations ( string , index , n ) : NEW_LINE INDENT if index >= n : NEW_LINE INDENT print (... |
Generate permutations with only adjacent swaps allowed | Python3 program to generate permutations with only one swap allowed . ; don 't swap the current position ; Swap with the next character and revert the changes . As explained above , swapping with previous is is not needed as it anyways happens for next character ... | def findPermutations ( string , index , n ) : NEW_LINE INDENT if index >= n or ( index + 1 ) >= n : NEW_LINE INDENT print ( ' ' . join ( string ) ) NEW_LINE return NEW_LINE DEDENT findPermutations ( string , index + 1 , n ) NEW_LINE string [ index ] , string [ index + 1 ] = string [ index + 1 ] , string [ index ] NEW_L... |
Decode a median string to the original string | function to calculate the median back string ; length of string ; initialize a blank string ; Flag to check if length is even or odd ; traverse from first to last ; if len is even then add first character to beginning of new string and second character to end ; if current... | def decodeMedianString ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE s1 = " " NEW_LINE if ( l % 2 == 0 ) : NEW_LINE INDENT isEven = True NEW_LINE DEDENT else : NEW_LINE INDENT isEven = False NEW_LINE DEDENT for i in range ( 0 , l , 2 ) : NEW_LINE INDENT if ( isEven ) : NEW_LINE INDENT s1 = s [ i ] + s1 NEW_LINE s1 += ... |
Maximum number of characters between any two same character in a string | Simple Python3 program to find maximum number of characters between two occurrences of same character ; Driver code | def maximumChars ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = - 1 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT res = max ( res , abs ( j - i - 1 ) ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DED... |
Maximum number of characters between any two same character in a string | Efficient Python3 program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ... | MAX_CHAR = 256 NEW_LINE def maximumChars ( str1 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = - 1 NEW_LINE firstInd = [ - 1 for i in range ( MAX_CHAR ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT first_ind = firstInd [ ord ( str1 [ i ] ) ] NEW_LINE if ( first_ind == - 1 ) : NEW_LINE INDENT firstInd [ ord ( ... |
Check if an encoding represents a unique binary string | Python 3 program to check if given encoding represents a single string . ; Return true if sum becomes k ; Driver Code | def isUnique ( a , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT sum += n - 1 NEW_LINE return ( sum == k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 3 , 3 , 3 ] NEW_LINE n = len ( a ) NEW_LINE k = 12 NEW_LINE if ( i... |
Lexicographically next string | Python 3 program to find lexicographically next string ; If string is empty . ; Find first character from right which is not z . ; If all characters are ' z ' , append an ' a ' at the end . ; If there are some non - z characters ; Driver code | def nextWord ( s ) : NEW_LINE INDENT if ( s == " β " ) : NEW_LINE INDENT return " a " NEW_LINE DEDENT i = len ( s ) - 1 NEW_LINE while ( s [ i ] == ' z ' and i >= 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT s = s + ' a ' NEW_LINE DEDENT else : NEW_LINE INDENT s = s . replace ( s [ i ]... |
Length of the longest substring with equal 1 s and 0 s | Function to check if a contains equal number of one and zeros or not ; Function to find the length of the longest balanced substring ; Driver code ; Function call | def isValid ( p ) : NEW_LINE INDENT n = len ( p ) NEW_LINE c1 = 0 NEW_LINE c0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] == '0' ) : NEW_LINE INDENT c0 += 1 NEW_LINE DEDENT if ( p [ i ] == '1' ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT DEDENT if ( c0 == c1 ) : NEW_LINE INDENT return True NEW_LINE ... |
Common characters in n strings | Python3 Program to find all the common characters in n strings ; primary array for common characters we assume all characters are seen before . ; for each strings ; secondary array for common characters Initially marked false ; for every character of ith strings ; if character is presen... | MAX_CHAR = 26 NEW_LINE def commonCharacters ( strings , n ) : NEW_LINE INDENT prim = [ True ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT sec = [ False ] * MAX_CHAR NEW_LINE for j in range ( len ( strings [ i ] ) ) : NEW_LINE INDENT if ( prim [ ord ( strings [ i ] [ j ] ) - ord ( ' a ' ) ] ) : NEW_LINE I... |
Number of positions where a letter can be inserted such that a string becomes palindrome | Function to check if the string is palindrome ; to know the length of string ; if the given string is a palindrome ( Case - I ) ; Sub - case - III ) ; if ( n % 2 == 0 ) : if the length is even ; count = 2 * count + 1 sub - case -... | def isPalindrome ( s , i , j ) : NEW_LINE INDENT p = j NEW_LINE for k in range ( i , p + 1 ) : NEW_LINE INDENT if ( s [ k ] != s [ p ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT p -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def countWays ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE count = 0 NEW_LINE if ( ... |
Count of substrings of a binary string containing K ones | method returns total number of substring having K ones ; initialize index having zero sum as 1 ; loop over binary characters of string ; update countOfOne variable with value of ith character ; if value reaches more than K , then update result ; add frequency o... | def countOfSubstringWithKOnes ( s , K ) : NEW_LINE INDENT N = len ( s ) NEW_LINE res = 0 NEW_LINE countOfOne = 0 NEW_LINE freq = [ 0 for i in range ( N + 1 ) ] NEW_LINE freq [ 0 ] = 1 NEW_LINE for i in range ( 0 , N , 1 ) : NEW_LINE INDENT countOfOne += ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( countOfOne >= K ) : NE... |
Generate two output strings depending upon occurrence of character in input string . | Python3 program to print two strings made of character occurring once and multiple times ; function to print two strings generated from single string one with characters occurring onces other with character occurring multiple of time... | MAX_CHAR = 256 NEW_LINE def printDuo ( string ) : NEW_LINE INDENT countChar = [ 0 for i in range ( MAX_CHAR ) ] NEW_LINE n = len ( string ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT countChar [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT str1 = " " NEW_LINE str2 = " " NEW_LINE for i in range ( MAX... |
Next higher palindromic number using the same set of digits | function to reverse the digits in the range i to j in 'num ; function to find next higher palindromic number using the same set of digits ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in... | ' NEW_LINE def reverse ( num , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT temp = num [ i ] NEW_LINE num [ i ] = num [ j ] NEW_LINE num [ j ] = temp NEW_LINE i = i + 1 NEW_LINE j = j - 1 NEW_LINE DEDENT DEDENT def nextPalin ( num , n ) : NEW_LINE INDENT if ( n <= 3 ) : NEW_LINE INDENT print " Not β Poss... |
Print N | function to generate n digit numbers ; if number generated ; Append 1 at the current number and reduce the remaining places by one ; If more ones than zeros , append 0 to the current number and reduce the remaining places by one ; Driver Code ; Function call | def printRec ( number , extraOnes , remainingPlaces ) : NEW_LINE INDENT if ( 0 == remainingPlaces ) : NEW_LINE INDENT print ( number , end = " β " ) NEW_LINE return NEW_LINE DEDENT printRec ( number + "1" , extraOnes + 1 , remainingPlaces - 1 ) NEW_LINE if ( 0 < extraOnes ) : NEW_LINE INDENT printRec ( number + "0" , e... |
Longest Common Substring in an Array of Strings | function to find the stem ( longestcommon substring ) from the string array ; Determine size of the array ; Take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; Check if the generated stem is common to ... | def findstem ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE s = arr [ 0 ] NEW_LINE l = len ( s ) NEW_LINE res = " " NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( i + 1 , l + 1 ) : NEW_LINE INDENT stem = s [ i : j ] NEW_LINE k = 1 NEW_LINE for k in range ( 1 , n ) : NEW_LINE INDENT if stem not in ... |
Make a string from another by deletion and rearrangement of characters | Python 3 program to find if it is possible to make a string from characters present in other string . ; Returns true if it is possible to make s1 from characters present in s2 . ; Count occurrences of all characters present in s2 . . ; For every c... | MAX_CHAR = 256 NEW_LINE def isPossible ( s1 , s2 ) : NEW_LINE INDENT count = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( len ( s2 ) ) : NEW_LINE INDENT count [ ord ( s2 [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( count [ ord ( s1 [ i ] ) ] == 0 ) : NEW_LINE INDENT return False NEW... |
Next higher number using atmost one swap operation | function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of ri... | def nextHighUsingAtMostOneSwap ( st ) : NEW_LINE INDENT num = list ( st ) NEW_LINE l = len ( num ) NEW_LINE posRMax = l - 1 NEW_LINE index = - 1 NEW_LINE i = l - 2 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( num [ i ] >= num [ posRMax ] ) : NEW_LINE INDENT posRMax = i NEW_LINE DEDENT else : NEW_LINE INDENT index = i N... |
Longest substring of vowels | Python3 program to find the longest substring of vowels . ; Increment current count if s [ i ] is vowel ; check previous value is greater then or not ; Driver code | def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def longestVowel ( s ) : NEW_LINE INDENT count , res = 0 , 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT e... |
Number of substrings with count of each character as k | Python3 program to count number of substrings with counts of distinct characters as k . ; Returns true if all values in freq [ ] are either 0 or k . ; Returns count of substrings where frequency of every present character is k ; Pick a starting point ; Initialize... | MAX_CHAR = 26 NEW_LINE def check ( freq , k ) : NEW_LINE INDENT for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT if ( freq [ i ] and freq [ i ] != k ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def substrings ( s , k ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) ) : NEW_LINE... |
Number of substrings with count of each character as k | | from collections import defaultdict NEW_LINE def have_same_frequency ( freq : defaultdict , k : int ) : NEW_LINE INDENT return all ( [ freq [ i ] == k or freq [ i ] == 0 for i in freq ] ) NEW_LINE DEDENT def count_substrings ( s : str , k : int ) -> int : NEW_LINE INDENT count = 0 NEW_LINE distinct = len ( set ( [ i fo... |
Frequency of a string in an array of strings | Python3 program to count number of times a string appears in an array of strings ; To store number of times a string is present . It is 0 is string is not present ; function to insert a string into the Trie ; calculation ascii value ; If the given node is not already prese... | MAX_CHAR = 26 NEW_LINE class Trie : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . cnt = 0 NEW_LINE self . node = [ None for i in range ( MAX_CHAR ) ] NEW_LINE DEDENT DEDENT def insert ( root , s ) : NEW_LINE INDENT temp = root NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index... |
Longest subsequence where every character appears at | Python3 program to Find longest subsequence where every character appears at - least k times ; Count frequencies of all characters ; Traverse given string again and print all those characters whose frequency is more than or equal to k . ; Driver code | MAX_CHARS = 26 NEW_LINE def longestSubseqWithK ( str , k ) : NEW_LINE INDENT n = len ( str ) NEW_LINE freq = [ 0 ] * MAX_CHARS NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( freq [ ord ( str [ i ] ) - ord ( ' a ... |
Generating distinct subsequences of a given string in lexicographic order | Finds and stores result in st for a given string s . ; If current string is not already present . ; Traverse current string , one by one remove every character and recur . ; Driver Code | def generate ( st , s ) : NEW_LINE INDENT if len ( s ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT if s not in st : NEW_LINE INDENT st . add ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT t = list ( s ) . copy ( ) NEW_LINE t . remove ( s [ i ] ) NEW_LINE t = ' ' . join ( t ) NEW_LINE generate ( st , t ... |
Recursive solution to count substrings with same first and last characters | Function to count substrings with same first and last characters ; base cases ; driver code | def countSubstrs ( str , i , j , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = ( countSubstrs ( str , i + 1 , j , n - 1 ) + countSubstrs ( str , i , j - 1 , n - 1 ) - countSubstrs ( str , i + 1 , j - 1 , n - 2 ) ) NEW_LINE i... |
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Counts the no of manipulations required ; store the count of character ; iterate though the first String and update count ; iterate through the second string update char_count . if character is not found in char_count t... | def countManipulations ( s1 , s2 ) : NEW_LINE INDENT count = 0 NEW_LINE char_count = [ 0 ] * 26 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT char_count [ i ] = 0 NEW_LINE DEDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT char_count [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ... |
Least number of manipulations needed to ensure two strings have identical characters | Python3 program to count least number of manipulations to have two strings set of same characters ; return the count of manipulations required ; count the number of different characters in both strings ; check the difference in chara... | MAX_CHAR = 26 NEW_LINE def leastCount ( s1 , s2 , n ) : NEW_LINE INDENT count1 = [ 0 ] * MAX_CHAR NEW_LINE count2 = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT count1 [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE count2 [ ord ( s2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE... |
Given two strings check which string makes a palindrome first | Given two strings , check which string makes palindrome first . ; returns winner of two strings ; Count frequencies of characters in both given strings ; Check if there is a character that appears more than once in A and does not appear in B ; Driver Code | MAX_CHAR = 26 NEW_LINE def stringPalindrome ( A , B ) : NEW_LINE INDENT countA = [ 0 ] * MAX_CHAR NEW_LINE countB = [ 0 ] * MAX_CHAR NEW_LINE l1 = len ( A ) NEW_LINE l2 = len ( B ) NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT countA [ ord ( A [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NE... |
Print the longest common substring | function to find and print the longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of longest common suffix of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ... | def printLCSSubStr ( X : str , Y : str , m : int , n : int ) : NEW_LINE INDENT LCSuff = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE length = 0 NEW_LINE row , col = 0 , 0 NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if i == 0 or j == 0 : NEW_LINE... |
Convert all substrings of length ' k ' from base ' b ' to decimal | Simple Python3 program to convert all substrings from decimal to given base . ; Saving substring in sub ; Evaluating decimal for current substring and printing it . ; Driver code | import math NEW_LINE def substringConversions ( s , k , b ) : NEW_LINE INDENT l = len ( s ) ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( ( i + k ) < l + 1 ) : NEW_LINE INDENT sub = s [ i : i + k ] ; NEW_LINE sum , counter = 0 , 0 ; NEW_LINE for i in range ( len ( sub ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum ... |
Longest Possible Chunked Palindrome | Here curr_str is the string whose LCP is needed leng is length of string evaluated till now and s is original string ; If there is nothing at all ! ! ; If a single letter is left out ; For each length of substring chunk in string ; If left side chunk and right side chunk are same ;... | def LPCRec ( curr_str , count , leng , s ) : NEW_LINE INDENT if not curr_str : NEW_LINE INDENT return 0 NEW_LINE DEDENT if len ( curr_str ) <= 1 : NEW_LINE INDENT if count != 0 and len ( s ) - leng <= 1 : NEW_LINE INDENT return ( count + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT n = len... |
Find numbers of balancing positions in string | Python3 program to find number of balancing points in string ; function to return number of balancing points ; hash array for storing hash of string initialized by 0 being global ; process string initially for rightVisited ; check for balancing points ; for every position... | MAX_CHAR = 256 NEW_LINE def countBalance ( string ) : NEW_LINE INDENT leftVisited = [ 0 ] * ( MAX_CHAR ) NEW_LINE rightVisited = [ 0 ] * ( MAX_CHAR ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT rightVisited [ ord ( string [ i ] ) ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT... |
Min flips of continuous characters to make all characters same in a string | To find min number of flips in binary string ; If last character is not equal to str [ i ] increase res ; To return min flips ; Driver Code | def findFlips ( str , n ) : NEW_LINE INDENT last = ' β ' NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( last != str [ i ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT last = str [ i ] NEW_LINE DEDENT return res // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "00011110... |
Maximum length substring having all same characters after k changes | function to find the maximum length of substring having character ch ; traverse the whole string ; if character is not same as ch increase count ; While count > k traverse the string again until count becomes less than k and decrease the count when c... | def findLen ( A , n , k , ch ) : NEW_LINE INDENT maxlen = 1 NEW_LINE cnt = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while r < n : NEW_LINE INDENT if A [ r ] != ch : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT while cnt > k : NEW_LINE INDENT if A [ l ] != ch : NEW_LINE INDENT cnt -= 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT... |
Given a sequence of words , print all anagrams together using STL | Python3 program for finding all anagram pairs in the given array ; Utility function for printing anagram list ; Utility function for storing the vector of strings into HashMap ; Check for sorted string if it already exists ; Push new string to already ... | from collections import defaultdict NEW_LINE def printAnagram ( store : dict ) -> None : NEW_LINE INDENT for ( k , v ) in store . items ( ) : NEW_LINE INDENT temp_vec = v NEW_LINE size = len ( temp_vec ) NEW_LINE if ( size > 1 ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( temp_vec [ i ] , end = ... |
Quick way to check if all the characters of a string are same | Function to check is all the characters in string are or not ; Insert characters in the set ; If all characters are same Size of set will always be 1 ; Driver code | def allCharactersSame ( s ) : NEW_LINE INDENT s1 = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT s1 . append ( s [ i ] ) NEW_LINE DEDENT s1 = list ( set ( s1 ) ) NEW_LINE if ( len ( s1 ) == 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDE... |
Check if both halves of the string have same set of characters | Python3 program to check if it is possible to split string or not ; Function to check if we can split string or not ; Counter array initialized with 0 ; Length of the string ; Traverse till the middle element is reached ; First half ; Second half ; Checki... | MAX_CHAR = 26 NEW_LINE def checkCorrectOrNot ( s ) : NEW_LINE INDENT global MAX_CHAR NEW_LINE count1 = [ 0 ] * MAX_CHAR NEW_LINE count2 = [ 0 ] * MAX_CHAR NEW_LINE n = len ( s ) NEW_LINE if n == 1 : NEW_LINE INDENT return true NEW_LINE DEDENT i = 0 ; j = n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT count1 [ ord ( s... |
Extract maximum numeric value from a given string | Set 1 ( General approach ) | Utility function to find maximum string ; If both having equal lengths ; Reach first unmatched character / value ; Return string with maximum value ; If different lengths return string with maximum length ; Function to extract the maximum ... | def maximumNum ( curr_num , res ) : NEW_LINE INDENT len1 = len ( curr_num ) ; NEW_LINE len2 = len ( res ) ; NEW_LINE if ( len1 == len2 ) : NEW_LINE INDENT i = 0 ; NEW_LINE while ( curr_num [ i ] == res [ i ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( curr_num [ i ] < res [ i ] ) : NEW_LINE INDENT return res ; NE... |
To check divisibility of any large number by 999 | function to check divisibility ; Append required 0 s at the beginning . ; add digits in group of three in gSum ; group saves 3 - digit group ; calculate result till 3 digit sum ; Driver code | def isDivisible999 ( num ) : NEW_LINE INDENT n = len ( num ) ; NEW_LINE if ( n == 0 or num [ 0 ] == '0' ) : NEW_LINE INDENT return true NEW_LINE DEDENT if ( ( n % 3 ) == 1 ) : NEW_LINE INDENT num = "00" + num NEW_LINE DEDENT if ( ( n % 3 ) == 2 ) : NEW_LINE INDENT num = "0" + num NEW_LINE DEDENT gSum = 0 NEW_LINE for i... |
Rearrange a string in sorted order followed by the integer sum | Python3 program for above implementation ; Function to return string in lexicographic order followed by integers sum ; Traverse the string ; Count occurrence of uppercase alphabets ; Store sum of integers ; Traverse for all characters A to Z ; Append the ... | MAX_CHAR = 26 NEW_LINE def arrangeString ( string ) : NEW_LINE INDENT char_count = [ 0 ] * MAX_CHAR NEW_LINE s = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if string [ i ] >= " A " and string [ i ] <= " Z " : NEW_LINE INDENT char_count [ ord ( string [ i ] ) - ord ( " A " ) ] += 1 NEW_LINE DEDENT el... |
URLify a given string ( Replace spaces is % 20 ) | Instantiate the string ; Trim the given string ; Replace All space ( unicode is \\ s ) to % 20 ; Display the result | s = " Mr β John β Smith β " NEW_LINE s = s . strip ( ) NEW_LINE s = s . replace ( ' β ' , " % 20" ) NEW_LINE print ( s ) NEW_LINE |
Program to print all substrings of a given string | Function to print all sub strings ; Pick starting point ; Pick ending point ; Print characters from current starting point to current ending point . ; Driver program to test above function | def subString ( Str , n ) : NEW_LINE INDENT for Len in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - Len + 1 ) : NEW_LINE INDENT j = i + Len - 1 NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT print ( Str [ k ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT Str = " abc " NEW_... |
Reverse a string preserving space positions | Function to reverse the string and preserve the space position ; Mark spaces in result ; Traverse input string from beginning and put characters in result from end ; Ignore spaces in input string ; Ignore spaces in result . ; Driver code | def reverses ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE result = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == ' β ' ) : NEW_LINE INDENT result [ i ] = ' β ' NEW_LINE DEDENT DEDENT j = n - 1 NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT if ( st [ i ] != ' β ' ) : NEW_LINE I... |
Find uncommon characters of the two strings | size of the hash table ; function to find the uncommon characters of the two strings ; mark presence of each character as 0 in the hash table 'present[] ; for each character of str1 , mark its presence as 1 in 'present[] ; for each character of str2 ; if a character of str2... | MAX_CHAR = 26 NEW_LINE def findAndPrintUncommonChars ( str1 , str2 ) : NEW_LINE ' NEW_LINE INDENT present = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT present [ i ] = 0 NEW_LINE DEDENT l1 = len ( str1 ) NEW_LINE l2 = len ( str2 ) NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , l1... |
Length Of Last Word in a String | Python3 program for implementation of simple approach to find length of last word ; String a is ' final ' -- can not be modified So , create a copy and trim the spaces from both sides ; Driver code | def lengthOfLastWord ( a ) : NEW_LINE INDENT l = 0 NEW_LINE x = a . strip ( ) NEW_LINE for i in range ( len ( x ) ) : NEW_LINE INDENT if x [ i ] == " β " : NEW_LINE INDENT l = 0 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT return l NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDEN... |
Length Of Last Word in a String | Python3 program for implementation of efficient approach to find length of last word ; Split by space and converting String to list and ; Driver code | def length ( str ) : NEW_LINE INDENT lis = list ( str . split ( " β " ) ) NEW_LINE return len ( lis [ - 1 ] ) NEW_LINE DEDENT str = " Geeks β for β Geeks " NEW_LINE print ( " The β length β of β last β word β is " , length ( str ) ) NEW_LINE |
Program to count vowels in a string ( Iterative and Recursive ) | Function to check the Vowel ; Returns count of vowels in str ; Check for vowel ; string object ; Total number of Vowels | def isVowel ( ch ) : NEW_LINE INDENT return ch . upper ( ) in [ ' A ' , ' E ' , ' I ' , ' O ' , ' U ' ] NEW_LINE DEDENT def countVowels ( str ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if isVowel ( str [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count ... |
Toggle case of a string using Bitwise Operators | Python3 program to get toggle case of a string ; tOGGLE cASE = swaps CAPS to lower case and lower case to CAPS ; Bitwise EXOR with 32 ; Driver Code | x = 32 ; NEW_LINE def toggleCase ( a ) : NEW_LINE INDENT for i in range ( len ( a ) ) : NEW_LINE INDENT a = a [ : i ] + chr ( ord ( a [ i ] ) ^ 32 ) + a [ i + 1 : ] ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT str = " CheRrY " ; NEW_LINE print ( " Toggle β case : β " , end = " " ) ; NEW_LINE str = toggleCase ( str ) ; ... |
Determine if a string has all Unique Characters | Python3 program to illustrate String with unique characters ; Converting string to set ; If length of set is equal to len of string then it will have unique characters ; Driver Code | def uniqueCharacters ( str ) : NEW_LINE INDENT setstring = set ( str ) NEW_LINE if ( len ( setstring ) == len ( str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = " GeeksforGeeks " NEW_LINE if ( uniqueCharacters ( input ) ) : NEW_... |
Ropes Data Structure ( Fast String Concatenation ) | Function that concatenates strings a [ 0. . n1 - 1 ] and b [ 0. . n2 - 1 ] and stores the result in c [ ] ; Copy characters of A [ ] to C [ ] ; Copy characters of B [ ] ; Driver Code ; Concatenate a [ ] and b [ ] and store result in c [ ] | def concatenate ( a , b , c , n1 , n2 ) : NEW_LINE INDENT i = - 1 NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT c [ i ] = a [ i ] NEW_LINE DEDENT for j in range ( n2 ) : NEW_LINE INDENT c [ i ] = b [ j ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = " Hi β This β is β g... |
Binary representation of next greater number with same number of 1 ' s β and β 0' s | Function to find the next greater number with same number of 1 ' s β and β 0' s ; locate first ' i ' from end such that bnum [ i ] == '0' and bnum [ i + 1 ] == '1' swap these value and break ; if no swapping performed ; Since we want ... | def nextGreaterWithSameDigits ( bnum ) : NEW_LINE INDENT l = len ( bnum ) NEW_LINE bnum = list ( bnum ) NEW_LINE for i in range ( l - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( bnum [ i ] == '0' and bnum [ i + 1 ] == '1' ) : NEW_LINE INDENT ch = bnum [ i ] NEW_LINE bnum [ i ] = bnum [ i + 1 ] NEW_LINE bnum [ i + 1 ] = ch NEW... |
Generate all rotations of a given string | Print all the rotated strings . ; Generate all rotations one by one and print ; Current index in str ; Current index in temp ; Copying the second part from the point of rotation . ; Copying the first part from the point of rotation . ; Driver Code | def printRotatedString ( str ) : NEW_LINE INDENT lenn = len ( str ) NEW_LINE temp = [ 0 ] * ( lenn ) NEW_LINE for i in range ( lenn ) : NEW_LINE DEDENT j = i NEW_LINE k = 0 NEW_LINE INDENT while ( j < len ( str ) ) : NEW_LINE INDENT temp [ k ] = str [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT j = 0 NEW_LINE w... |
All possible strings of any length that can be formed from a given string | Python3 code to generate all possible strings that can be formed from given string ; Number of subsequences is ( 2 * * n - 1 ) ; Generate all subsequences of a given string . using counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter ... | from itertools import permutations NEW_LINE def printAll ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE opsize = pow ( 2 , n ) NEW_LINE for counter in range ( 1 , opsize ) : NEW_LINE INDENT subs = " " NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( counter & ( 1 << j ) ) : NEW_LINE INDENT subs += ( st [ j ] ) NE... |
Longest Non | utility function to check whether a string is palindrome or not ; Check for palindrome . ; palindrome string ; function to find maximum length substring which is not palindrome ; to check whether all characters of the string are same or not ; All characters are same , we can 't make a non-palindromic str... | def isPalindrome ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if ( str [ i ] != str [ n - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def maxLengthNonPalinSubstring ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE ch = s... |
Move spaces to front of string in single traversal | Function to find spaces and move to beginning ; Traverse from end and swap spaces ; Driver code | def moveSpaceInFront ( s ) : NEW_LINE INDENT i = len ( s ) - 1 ; NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ j ] != ' β ' ) : NEW_LINE INDENT s = swap ( s , i , j ) ; NEW_LINE i -= 1 ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT def swap ( c , i , j ) : NEW_LINE INDENT c = list ( c ) NEW_... |
Move spaces to front of string in single traversal | Function to find spaces and move to beginning ; Keep copying non - space characters ; Move spaces to be beginning ; Driver code | def moveSpaceInFront ( s ) : NEW_LINE INDENT i = len ( s ) - 1 ; NEW_LINE for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ j ] != ' β ' ) : NEW_LINE INDENT s = s [ : i ] + s [ j ] + s [ i + 1 : ] NEW_LINE i -= 1 ; NEW_LINE DEDENT DEDENT while ( i >= 0 ) : NEW_LINE INDENT s = s [ : i ] + ' β ' + s [ i + 1 : ]... |
Minimum number of Appends needed to make a string palindrome | Checking if the String is palindrome or not ; single character is always palindrome ; pointing to first character ; pointing to last character ; Recursive function to count number of appends ; Removing first character of String by incrementing base address ... | def isPalindrome ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE if ( Len == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT ptr1 = 0 NEW_LINE ptr2 = Len - 1 NEW_LINE while ( ptr2 > ptr1 ) : NEW_LINE INDENT if ( Str [ ptr1 ] != Str [ ptr2 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT ptr1 += 1 NEW_LINE ptr2... |
Find Excel column number from column title | Returns resul when we pass title . ; This process is similar to binary - to - decimal conversion ; Driver function | def titleToNumber ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE for B in range ( len ( s ) ) : NEW_LINE INDENT result *= 26 ; NEW_LINE result += ord ( s [ B ] ) - ord ( ' A ' ) + 1 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT print ( titleToNumber ( " CDA " ) ) ; NEW_LINE |
Check whether K | PHP program to check if k - th bit of a given number is set or not using right shift operator . ; Driver code | def isKthBitSet ( n , k ) : NEW_LINE INDENT if ( ( n >> ( k - 1 ) ) and 1 ) : NEW_LINE INDENT print ( " SET " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NOT β SET " ) NEW_LINE DEDENT DEDENT n , k = 5 , 1 NEW_LINE isKthBitSet ( n , k ) NEW_LINE |
Reverse string without using any temporary variable | Function to reverse string and return reversed string ; Iterate loop upto start not equal to end ; XOR for swapping the variable ; Driver Code | def reversingString ( str , start , end ) : NEW_LINE INDENT while ( start < end ) : NEW_LINE INDENT str = ( str [ : start ] + chr ( ord ( str [ start ] ) ^ ord ( str [ end ] ) ) + str [ start + 1 : ] ) ; NEW_LINE str = ( str [ : end ] + chr ( ord ( str [ start ] ) ^ ord ( str [ end ] ) ) + str [ end + 1 : ] ) ; NEW_LIN... |
Check if a string follows a ^ nb ^ n pattern or not | Python3 code to check a ^ nb ^ n pattern ; if length of str is odd return No ; check first half is ' a ' and other half is full of 'b ; Driver code ; Function call | def isanbn ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if n & 1 : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( int ( n / 2 ) ) : NEW_LINE INDENT if str [ i ] != ' a ' or str [ n - i - 1 ] != ' b ' : NEW_LINE return " No " NEW_LINE DEDENT return " Yes " NEW_LINE DEDENT i... |
Number of substrings divisible by 6 in a string of integers | Return the number of substring divisible by 6 and starting at index i in s [ ] and previous sum of digits modulo 3 is m . ; End of the string . ; If already calculated , return the stored value . ; Converting into integer . ; Increment result by 1 , if curre... | def f ( i , m , s , memoize ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( memoize [ i ] [ m ] != - 1 ) : NEW_LINE INDENT return memoize [ i ] [ m ] NEW_LINE DEDENT x = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE ans = ( ( ( x + m ) % 3 == 0 and x % 2 == 0 ) + f ( i + 1 , ( m + x )... |
Lexicographically first palindromic string | Python3 program to find first palindromic permutation of given string ; Function to count frequency of each char in the string . freq [ 0 ] for ' a ' , ... . , freq [ 25 ] for 'z ; Cases to check whether a palindr0mic string can be formed or not ; count_odd to count no of ch... | MAX_CHAR = 26 ; NEW_LINE ' NEW_LINE def countFreq ( str1 , freq , len1 ) : NEW_LINE INDENT for i in range ( len1 ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT DEDENT def canMakePalindrome ( freq , len1 ) : NEW_LINE INDENT count_odd = 0 ; NEW_LINE for i in range ( MAX_CHAR ) : NE... |
Count substrings with same first and last characters | Returns true if first and last characters of s are same . ; Starting point of substring ; Length of substring ; Check if current substring has same starting and ending characters . ; Driver code | def checkEquality ( s ) : NEW_LINE INDENT return ( ord ( s [ 0 ] ) == ord ( s [ len ( s ) - 1 ] ) ) ; NEW_LINE DEDENT def countSubstringWithEqualEnds ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , n - i + 1 ) : NEW_LINE INDENT if ( chec... |
Count substrings with same first and last characters | Space efficient Python3 program to count all substrings with same first and last characters . ; Iterating through all substrings in way so that we can find first and last character easily ; Driver Code | def countSubstringWithEqualEnds ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT s = " abcab... |
Find the missing number in a string of numbers with no separator | Python3 program to find a missing number in a string of consecutive numbers without any separator . ; gets the integer at position i with length m , returns it or - 1 , if none ; Find value at index i and length m . ; Returns value of missing number ; T... | import math NEW_LINE MAX_DIGITS = 6 NEW_LINE def getValue ( Str , i , m ) : NEW_LINE INDENT if ( i + m > len ( Str ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT value = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT c = ( ord ( Str [ i + j ] ) - ord ( '0' ) ) NEW_LINE if ( c < 0 or c > 9 ) : NEW_LINE INDENT retur... |
Maximum consecutive repeating character in string | function to find out the maximum repeating character in given string ; Find the maximum repeating character starting from str [ i ] ; Update result if required ; Driver code | def maxRepeating ( str ) : NEW_LINE INDENT l = len ( str ) NEW_LINE count = 0 NEW_LINE res = str [ 0 ] NEW_LINE for i in range ( l ) : NEW_LINE INDENT cur_count = 1 NEW_LINE for j in range ( i + 1 , l ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT cur_count += 1 NEW_LINE DEDEN... |
Sum of two large numbers | Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Reverse both of strings ; Do school mathematics , compute sum of current digits and carry ; Calculate car... | def findSum ( str1 , str2 ) : NEW_LINE INDENT if ( len ( str1 ) > len ( str2 ) ) : NEW_LINE INDENT t = str1 ; NEW_LINE str1 = str2 ; NEW_LINE str2 = t ; NEW_LINE DEDENT str = " " ; NEW_LINE n1 = len ( str1 ) ; NEW_LINE n2 = len ( str2 ) ; NEW_LINE str1 = str1 [ : : - 1 ] ; NEW_LINE str2 = str2 [ : : - 1 ] ; NEW_LINE ca... |
Sum of two large numbers | Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute sum of cu... | def findSum ( str1 , str2 ) : NEW_LINE INDENT if len ( str1 ) > len ( str2 ) : NEW_LINE INDENT temp = str1 NEW_LINE str1 = str2 NEW_LINE str2 = temp NEW_LINE DEDENT str3 = " " NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE diff = n2 - n1 NEW_LINE carry = 0 NEW_LINE for i in range ( n1 - 1 , - 1 , - 1 ) ... |
Palindrome pair in an array of words ( or strings ) | Utility function to check if a string is a palindrome ; Compare each character from starting with its corresponding character from last ; Function to check if a palindrome pair exists ; Consider each pair one by one ; Concatenate both strings ; Check if the concaten... | def isPalindrome ( st ) : NEW_LINE INDENT length = len ( st ) NEW_LINE for i in range ( length // 2 ) : NEW_LINE INDENT if ( st [ i ] != st [ length - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def checkPalindromePair ( vect ) : NEW_LINE INDENT for i in range ( len ( vec... |
Print consecutive characters together in a line | Python3 program to print consecutive characters together in a line . ; Driver Code | def _print ( string ) : NEW_LINE INDENT print ( string [ 0 ] , end = " " ) NEW_LINE for i in range ( 1 , len ( string ) ) : NEW_LINE INDENT if ( ord ( string [ i ] ) == ord ( string [ i - 1 ] ) + 1 or ord ( string [ i ] ) == ord ( string [ i - 1 ] ) - 1 ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DE... |
Efficiently check if a string has all unique characters without using any additional data structure | Returns true if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters ... | def areCharactersUnique ( s ) : NEW_LINE INDENT checker = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT val = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( checker & ( 1 << val ) ) > 0 : NEW_LINE INDENT return False NEW_LINE DEDENT checker |= ( 1 << val ) NEW_LINE DEDENT return True NEW_LINE DEDENT s = " aa... |
Count of words whose i | Return the count of words . ; If word contain single letter , return 1. ; Checking for first letter . ; Traversing the string and multiplying for combinations . ; If all three letters are same . ; If two letter are distinct . ; If all three letter are distinct . ; Checking for last letter . ; D... | def countWords ( str , l ) : NEW_LINE INDENT count = 1 ; NEW_LINE if ( l == 1 ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( str [ 0 ] == str [ 1 ] ) : NEW_LINE INDENT count *= 1 NEW_LINE DEDENT else : NEW_LINE INDENT count *= 2 NEW_LINE DEDENT for j in range ( 1 , l - 1 ) : NEW_LINE INDENT if ( str [ j ] == str... |
Maximum and minimum sums from two numbers with digit replacements | Find new value of x after replacing digit " from " to " to " ; Required digit found , replace it ; Returns maximum and minimum possible sums of x1 and x2 if digit replacements are allowed . ; We always get minimum sum if we replace 6 with 5. ; We alway... | def replaceDig ( x , from1 , to ) : NEW_LINE INDENT result = 0 NEW_LINE multiply = 1 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT reminder = x % 10 NEW_LINE if ( reminder == from1 ) : NEW_LINE INDENT result = result + to * multiply NEW_LINE DEDENT else : NEW_LINE INDENT result = result + reminder * multiply NEW_LINE DEDE... |
Queries on substring palindrome formation | Query type 1 : update str1ing position i with character x . ; Pr " Yes " if range [ L . . R ] can form palindrome , else pr " No " . ; Find the frequency of each character in S [ L ... R ] . ; Checking if more than one character have frequency greater than 1. ; Driver Code | def qType1 ( l , x , str1 ) : NEW_LINE INDENT str1 [ l - 1 ] = x NEW_LINE DEDENT def qType2 ( l , r , str1 ) : NEW_LINE INDENT freq = [ 0 for i in range ( 27 ) ] NEW_LINE for i in range ( l - 1 , r ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for j in range ( 2... |
Queries on substring palindrome formation | Python3 program to Queries on substr1ing palindrome formation . ; Return the frequency of the character in the i - th prefix . ; Updating the BIT ; Query to update the character in the str1ing . ; Adding - 1 at L position ; Updating the character ; Adding + 1 at R position ; ... | max = 1000 ; NEW_LINE def getFrequency ( tree , idx , i ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( idx > 0 ) : NEW_LINE INDENT sum += tree [ idx ] [ i ] ; NEW_LINE idx -= ( idx & - idx ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def update ( tree , idx , val , i ) : NEW_LINE INDENT while ( idx <= max ) : NEW_L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.