text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Generate all possible permutations of a Number divisible by N | Function to generate all permutations and print the ones that are divisible by the N ; Convert string to integer ; Check for divisibility and print it ; Print all the permutations ; Swap characters ; Permute remaining characters ; Revoke the swaps ; Driver...
def permute ( st , l , r , n ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT p = ' ' . join ( st ) NEW_LINE j = int ( p ) NEW_LINE if ( j % n == 0 ) : NEW_LINE INDENT print ( p ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( l , r ) : NEW_LINE INDENT st [ l ] , st [ i ] = st [ i ] , st [ l ] NEW_LINE perm...
Check if binary representations of 0 to N are present as substrings in given binary string | Function to convert decimal to binary representation ; Iterate over all bits of N ; If bit is 1 ; Return binary representation ; Function to check if binary conversion of numbers from N to 1 exists in the string as a substring ...
def decimalToBinary ( N ) : NEW_LINE INDENT ans = " " NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT ans = '1' + ans NEW_LINE DEDENT else : NEW_LINE INDENT ans = '0' + ans NEW_LINE DEDENT N //= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT def checkBinaryString ( str , N ) : NEW_LINE INDENT ma...
Find the word with most anagrams in a given sentence | Function to find the word with maximum number of anagrams ; Primes assigned to 26 alphabets ; Stores the product and word mappings ; Stores the frequencies of products ; Calculate the product of primes assigned ; If product already exists ; Otherwise ; Fetch the mo...
def largestAnagramGrp ( arr ) : NEW_LINE INDENT prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 , 101 ] NEW_LINE max = - 1 NEW_LINE maxpdt = - 1 NEW_LINE W = { } NEW_LINE P = { } NEW_LINE for temp in arr : NEW_LINE INDENT c = [ i for i in ...
Replace every vowels with lexicographically next vowel in a String | Function to replace every vowel with next vowel lexicographically ; Storing the vowels in the map with custom numbers showing their index ; Iterate over the string ; If the current character is a vowel Find the index in Hash and Replace it with next v...
def print_next_vovel_string ( st ) : NEW_LINE INDENT m = { } NEW_LINE m [ ' a ' ] = 0 NEW_LINE m [ ' e ' ] = 1 NEW_LINE m [ ' i ' ] = 2 NEW_LINE m [ ' o ' ] = 3 NEW_LINE m [ ' u ' ] = 4 NEW_LINE arr = [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] NEW_LINE N = len ( st ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT c = s...
Check if string is palindrome after removing all consecutive duplicates | Function to check if a string is palindrome or not ; Length of the string ; Check if its a palindrome ; If the palindromic condition is not met ; Return true as Str is palindromic ; Function to check if string str is palindromic after removing ev...
def isPalindrome ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( Str [ i ] != Str [ Len - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isCompressablePalindrome ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE compr...
Count of substrings consisting only of vowels | function to check vowel or not ; Function to Count all substrings in a string which contains only vowels ; if current character is vowel ; increment ; Count all possible substring of calculated length ; Reset the length ; Add remaining possible substrings consisting of vo...
def isvowel ( ch ) : NEW_LINE INDENT return ( ch in " aeiou " ) NEW_LINE DEDENT def CountTotal ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE n = len ( s ) NEW_LINE cnt = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( isvowel ( s [ i ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += (...
Number formed by flipping all bits to the left of rightmost set bit | Function to get the total count ; Moving until we get the rightmost set bit ; To get total number of bits in a number ; Function to find the integer formed after flipping all bits to the left of the rightmost set bit ; Find the total count of bits an...
def getTotCount ( num ) : NEW_LINE INDENT totCount = 1 NEW_LINE firstCount = 1 NEW_LINE temp = 1 NEW_LINE while ( not ( num & temp ) ) : NEW_LINE INDENT temp = temp << 1 NEW_LINE totCount += 1 NEW_LINE DEDENT firstCount = totCount NEW_LINE temp = num >> totCount NEW_LINE while ( temp ) : NEW_LINE INDENT totCount += 1 N...
Longest substring of vowels with no two adjacent alphabets same | Function to check a character is vowel or not ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid subString ; Stores length of current valid subString ; If curr and prev ...
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 findMaxLen ( s ) : NEW_LINE INDENT maxLen = 0 NEW_LINE cur = 0 NEW_LINE if ( isVowel ( s [ 0 ] ) ) : NEW_LINE INDENT maxLen = 1 ; NEW_LINE DEDENT cur = maxLen NEW_LINE for i in range (...
Count of non | Iterative Function to calculate base ^ pow in O ( log y ) ; Function to return the count of non palindromic strings ; Count of strings using n characters with repetitions allowed ; Count of palindromic strings ; Count of non - palindromic strings ; Driver code
def power ( base , pwr ) : NEW_LINE INDENT res = 1 NEW_LINE while ( pwr > 0 ) : NEW_LINE INDENT if ( pwr & 1 ) : NEW_LINE INDENT res = res * base NEW_LINE DEDENT base = base * base NEW_LINE pwr >>= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def countNonPalindromicString ( n , m ) : NEW_LINE INDENT total = power ( n ,...
Count of K | To store the frequency array ; Function to check palindromic of of any substring using frequency array ; Initialise the odd count ; Traversing frequency array to compute the count of characters having odd frequency ; Returns true if odd count is atmost 1 ; Function to count the total number substring whose...
freq = [ 0 ] * 26 NEW_LINE def checkPalindrome ( ) : NEW_LINE INDENT oddCnt = 0 NEW_LINE for x in freq : NEW_LINE INDENT if ( x % 2 == 1 ) : NEW_LINE INDENT oddCnt += 1 NEW_LINE DEDENT DEDENT return oddCnt <= 1 NEW_LINE DEDENT def countPalindromePermutation ( s , k ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE IN...
Minimum flips required to form given binary string where every flip changes all bits to its right as well | Function to return the count of minimum flips required ; If curr occurs in the final string ; Switch curr to '0' if '1' or vice - versa ; Driver Code
def minFlips ( target ) : NEW_LINE INDENT curr = '1' NEW_LINE count = 0 NEW_LINE for i in range ( len ( target ) ) : NEW_LINE INDENT if ( target [ i ] == curr ) : NEW_LINE INDENT count += 1 NEW_LINE curr = chr ( 48 + ( ord ( curr ) + 1 ) % 2 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ mai...
Check if a number ends with another number or not | Python3 program for the above approach ; Function to check if B is a suffix of A or not ; Find the number of digit in B ; Subtract B from A ; Returns true , if B is a suffix of A ; Given numbers ; Function Call ; If B is a suffix of A , then print " Yes "
import math NEW_LINE def checkSuffix ( A , B ) : NEW_LINE INDENT digit_B = int ( math . log10 ( B ) ) + 1 ; NEW_LINE A -= B ; NEW_LINE return ( A % int ( math . pow ( 10 , digit_B ) ) ) ; NEW_LINE DEDENT A = 12345 ; B = 45 ; NEW_LINE result = checkSuffix ( A , B ) ; NEW_LINE if ( result == 0 ) : NEW_LINE INDENT print (...
Minimum length of substring whose rotation generates a palindromic substring | Python3 program to find the minimum length of substring whose rotation generates a palindromic substring ; Function to return the minimum length of substring ; Store the index of previous occurrence of the character ; Variable to store the m...
import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def count_min_length ( s ) : NEW_LINE INDENT hash = [ 0 ] * 26 ; NEW_LINE ans = sys . maxsize ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT hash [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( hash [ ord ( s [ i ] ) - ord ( ' ...
Program to remove HTML tags from a given String | Python3 program for the above approach ; Function to remove the HTML tags from the given tags ; Print string after removing tags ; Driver code ; Given String ; Function call to print the HTML string after removing tags
import re NEW_LINE def RemoveHTMLTags ( strr ) : NEW_LINE INDENT print ( re . compile ( r ' < [ ^ > ] + > ' ) . sub ( ' ' , strr ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " < div > < b > Geeks ▁ for ▁ Geeks < / b > < / div > " NEW_LINE RemoveHTMLTags ( strr ) ; NEW_LINE DEDENT
Score of Parentheses using Tree | Customized tree class or struct , contains all required methods . ; Function to add a child into the list of children ; Function to change the parent pointer to the node passed ; Function to return the parent of the current node ; Function to compute the score recursively . ; Base case...
class TreeNode : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . parent = None NEW_LINE self . children = [ ] NEW_LINE DEDENT def addChild ( self , node ) : NEW_LINE INDENT self . children . append ( node ) ; NEW_LINE DEDENT def setParent ( self , node ) : NEW_LINE INDENT self . parent = node ; NEW_LINE ...
Move all occurrence of letter ' x ' from the string s to the end using Recursion | Recursive program to bring ' x ' to the end ; When the string is completed from reverse direction end of recursion ; If the character x is found ; Transverse the whole string ; Swap the x so that it moves to the last ; Call to the smalle...
def rec ( a , i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT a . pop ( ) NEW_LINE print ( " " . join ( a ) ) NEW_LINE return NEW_LINE DEDENT if ( a [ i ] == ' x ' ) : NEW_LINE j = i NEW_LINE while ( a [ j ] != ' \0' and a [ j + 1 ] != ' \0' ) : NEW_LINE INDENT ( a [ j ] , a [ j + 1 ] ) = ( a [ j + 1 ] , a [ j ] ...
Find the largest Alphabetic character present in the string | Function to find the Largest Alphabetic Character ; Array for keeping track of both uppercase and lowercase english alphabets ; Iterate from right side of array to get the largest index character ; Check for the character if both its uppercase and lowercase ...
def largestCharacter ( str ) : NEW_LINE INDENT uppercase = [ False ] * 26 NEW_LINE lowercase = [ False ] * 26 NEW_LINE arr = list ( str ) NEW_LINE for c in arr : NEW_LINE INDENT if ( c . islower ( ) ) : NEW_LINE INDENT lowercase [ ord ( c ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT if ( c . isupper ( ) ) : NEW_LINE INDE...
Print string after removing all ( β€œ 10 ” or β€œ 01 ” ) from the binary string | Function to print the final string after removing all the occurrences of "10" and "01" from the given binary string ; Variables to store the count of 1 ' s ▁ and ▁ 0' s ; Length of the string ; For loop to count the occurrences of 1 ' s ▁ and...
def finalString ( st ) : NEW_LINE INDENT x , y = 0 , 0 NEW_LINE n = len ( st ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == '1' ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT if ( x > y ) : NEW_LINE INDENT left = 1 NEW_LINE DEDENT else : NEW_LINE INDE...
Longest palindrome formed by concatenating and reordering strings of equal length | Function to print the longest palindrome ; Printing every string in left vector ; Printing the palindromic string in the middle ; Printing the reverse of the right vector to make the final output palindromic ; Function to find and print...
def printPalindrome ( left , mid , right ) : NEW_LINE INDENT for x in left : NEW_LINE INDENT print ( x , end = " " ) NEW_LINE DEDENT print ( mid , end = " " ) NEW_LINE right = right [ : : - 1 ] NEW_LINE for x in right : NEW_LINE INDENT print ( x , end = " " ) NEW_LINE DEDENT print ( ' ' , end = " " ) NEW_LINE DEDENT de...
Lexicographically smaller string by swapping at most one character pair | Function that finds whether is it possible to make string A lexicographically smaller than string B ; Condition if string A is already smaller than B ; Sorting temp string ; Condition for first changed character of string A and temp ; Condition i...
def IsLexicographicallySmaller ( A , B ) : NEW_LINE INDENT if ( A < B ) : NEW_LINE INDENT return True NEW_LINE DEDENT temp = A NEW_LINE temp = ' ' . join ( sorted ( temp ) ) NEW_LINE index = - 1 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] != temp [ i ] ) : NEW_LINE INDENT index = i NEW_LINE bre...
Length of longest palindromic sub | Function to find maximum of the two variables ; Function to find the longest palindromic substring : Recursion ; Base condition when the start index is greater than end index ; Base condition when both the start and end index are equal ; Condition when corner characters are equal in ...
def maxi ( x , y ) : NEW_LINE INDENT if x > y : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return y NEW_LINE DEDENT DEDENT def longestPalindromic ( strn , i , j , count ) : NEW_LINE INDENT if i > j : NEW_LINE INDENT return count NEW_LINE DEDENT if i == j : NEW_LINE INDENT return ( count + 1 ) NEW_L...
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency | Function to find the maximum possible prefix of the string ; Hash map to store the frequency of the characters in the string ; Iterate over the string to find the occurence of each Character ; Minimum fre...
def MaxPrefix ( string ) : NEW_LINE INDENT Dict = { } NEW_LINE maxprefix = 0 NEW_LINE for i in string : NEW_LINE INDENT Dict [ i ] = Dict . get ( i , 0 ) + 1 NEW_LINE DEDENT minfrequency = min ( Dict . values ( ) ) NEW_LINE countminFrequency = 0 NEW_LINE for x in Dict : NEW_LINE INDENT if ( Dict [ x ] == minfrequency )...
Count of Substrings that can be formed without using the given list of Characters | Function to find the Number of sub - strings without using given character ; the freq array ; Count variable to store the count of the characters until a character from given L is encountered ; If a character from L is encountered , the...
def countSubstring ( S , L , n ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ( ord ( L [ i ] ) - ord ( ' a ' ) ) ] = 1 NEW_LINE DEDENT count , ans = 0 , 0 NEW_LINE for x in S : NEW_LINE INDENT if ( freq [ ord ( x ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT ans...
Program to accept Strings starting with a Vowel | Function to check if first character is vowel ; Function to check ; Driver function
def checkIfStartsWithVowels ( string ) : NEW_LINE INDENT if ( not ( string [ 0 ] == ' A ' or string [ 0 ] == ' a ' or string [ 0 ] == ' E ' or string [ 0 ] == ' e ' or string [ 0 ] == ' I ' or string [ 0 ] == ' i ' or string [ 0 ] == ' O ' or string [ 0 ] == ' o ' or string [ 0 ] == ' U ' or string [ 0 ] == ' u ' ) ) :...
Find the Nth occurrence of a character in the given String | Function to find the Nth occurrence of a character ; Loop to find the Nth occurrence of the character ; Driver Code
def findNthOccur ( string , ch , N ) : NEW_LINE INDENT occur = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ch ) : NEW_LINE INDENT occur += 1 ; NEW_LINE DEDENT if ( occur == N ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _...
Longest equal substring with cost less than K | Function to find the maximum length ; Fill the prefix array with the difference of letters ; Update the maximum length ; Driver code
def solve ( X , Y , N , K ) : NEW_LINE INDENT count = [ 0 ] * ( N + 1 ) ; NEW_LINE sol = 0 ; NEW_LINE count [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT count [ i ] = ( count [ i - 1 ] + abs ( ord ( X [ i - 1 ] ) - ord ( Y [ i - 1 ] ) ) ) ; NEW_LINE DEDENT j = 0 ; NEW_LINE for i in range ( 1 , N ...
Jaro and Jaro | Python3 implementation of above approach ; Function to calculate the Jaro Similarity of two strings ; If the strings are equal ; Length of two strings ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first string ; Check if there is any match...
from math import floor 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 if ( len1 == 0 or len2 == 0 ) : NEW_LINE INDENT return 0.0 ; NEW_LINE DEDENT max_dist = ( max ( len ( s1 ) , len ( s2 )...
Check if a word is present in a sentence | Function that returns true if the word is found ; To break the sentence in words ; To temporarily store each individual word ; Comparing the current word with the word to be searched ; Driver code
def isWordPresent ( sentence , word ) : NEW_LINE INDENT s = sentence . split ( " ▁ " ) NEW_LINE for i in s : NEW_LINE INDENT if ( i == word ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s = " Geeks ▁ for ▁ Geeks " NEW_LINE word = " Geeks " NEW_LINE if ( isWordPresent ( s , word ) )...
Check if a word is present in a sentence | Function that returns true if the word is found ; To convert the word in uppercase ; To convert the complete sentence in uppercase ; To break the sentence in words ; To store the individual words of the sentence ; Compare the current word with the word to be searched ; Driver ...
def isWordPresent ( sentence , word ) : NEW_LINE INDENT word = word . upper ( ) NEW_LINE sentence = sentence . upper ( ) NEW_LINE s = sentence . split ( ) ; NEW_LINE for temp in s : NEW_LINE INDENT if ( temp == word ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == "...
Count of 1 | Function to return the count of required characters ; While there are characters left ; Single bit character ; Two - bit character ; Update the count ; Driver code
def countChars ( string , n ) : NEW_LINE INDENT i = 0 ; cnt = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT i += 2 ; NEW_LINE DEDENT cnt += 1 ; NEW_LINE DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW...
Print the frequency of each character in Alphabetical order | Python3 implementation of the approach ; Function to print the frequency of each of the characters of s in alphabetical order ; To store the frequency of the characters ; Update the frequency array ; Print the frequency in alphatecial order ; If the current ...
MAX = 26 ; NEW_LINE def compressString ( s , n ) : NEW_LINE INDENT freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT print ( ( c...
Find the number obtained after concatenation of binary representation of M and N | Python3 implementation of the approach ; Function to convert decimal number n to its binary representation stored as an array arr [ ] ; Funtion to convert the number represented as a binary array arr [ ] its decimal equivalent ; Function...
import math NEW_LINE def decBinary ( arr , n ) : NEW_LINE INDENT k = int ( math . log2 ( n ) ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT arr [ k ] = n % 2 NEW_LINE k = k - 1 NEW_LINE n = n // 2 NEW_LINE DEDENT DEDENT def binaryDec ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDEN...
Find the number obtained after concatenation of binary representation of M and N | Utility function to calculate binary length of a number . ; Function to concatenate the binary numbers and return the decimal result ; find binary length of n ; left binary shift m and then add n ; Driver code
def getBinaryLength ( n ) : NEW_LINE INDENT length = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT length += 1 NEW_LINE n //= 2 NEW_LINE DEDENT return length NEW_LINE DEDENT def concat ( m , n ) : NEW_LINE INDENT length = getBinaryLength ( n ) NEW_LINE return ( m << length ) + n NEW_LINE DEDENT m , n = 4 , 5 NEW_LINE pr...
XOR two binary strings of unequal lengths | Function to insert n 0 s in the beginning of the given string ; Function to return the XOR of the given strings ; Lengths of the given strings ; Make both the strings of equal lengths by inserting 0 s in the beginning ; Updated length ; To store the resultant XOR ; Driver cod...
def addZeros ( strr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT strr = "0" + strr NEW_LINE DEDENT return strr NEW_LINE DEDENT def getXOR ( a , b ) : NEW_LINE INDENT aLen = len ( a ) NEW_LINE bLen = len ( b ) NEW_LINE if ( aLen > bLen ) : NEW_LINE INDENT b = addZeros ( b , aLen - bLen ) NEW_LINE DEDEN...
Minimum operations required to make the string satisfy the given condition | Python implementation of the approach ; Function to return the minimum operations required ; To store the first and the last occurrence of all the characters ; Set the first and the last occurrence of all the characters to - 1 ; Update the occ...
MAX = 26 ; NEW_LINE def minOperation ( str , len ) : NEW_LINE INDENT first , last = [ 0 ] * MAX , [ 0 ] * MAX ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT first [ i ] = - 1 ; NEW_LINE last [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ) : NEW_LINE INDENT index = ( ord ( str [ i ] ) - ord ( ' a ' ) ) ; NEW_L...
Queries to find the count of vowels in the substrings of the given string | Python3 implementation of the approach ; Function that returns true if ch is a vowel ; Function to return the count of vowels in the substring str [ l ... r ] ; To store the count of vowels ; For every character in the index range [ l , r ] ; I...
N = 2 ; NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) ; NEW_LINE DEDENT def countVowels ( string , l , r ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( isVowel ( string [ i ] ) ) : NEW_LINE IND...
Convert a String to a Singly Linked List | Structure for a Singly Linked List ; Function to add a node to the Linked List ; Function to convert the string to Linked List . ; curr pointer points to the current node where the insertion should take place ; Function to print the data present in all the nodes ; Driver code
class node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT data = None NEW_LINE next = None NEW_LINE DEDENT DEDENT def add ( data ) : NEW_LINE INDENT newnode = node ( ) NEW_LINE newnode . data = data NEW_LINE newnode . next = None NEW_LINE return newnode NEW_LINE DEDENT def string_to_SLL ( text , head ) : NEW...
Reduce the string to minimum length with the given operation | Function to return the minimum possible length str can be reduced to with the given operation ; Stack to store the characters of the given string ; For every character of the string ; If the stack is empty then push the current character in the stack ; Get ...
def minLength ( string , l ) : NEW_LINE INDENT s = [ ] ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( string [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT c = s [ - 1 ] ; NEW_LINE if ( c != string [ i ] and c . upper ( ) == string [ i ] . upper ( ) ) : NEW_LINE...
Check whether two strings can be made equal by copying their characters with the adjacent ones | Python3 implementation of the approach ; Function that returns true if both the strings can be made equal with the given operation ; Lengths of both the strings have to be equal ; To store the frequency of the characters of...
MAX = 26 NEW_LINE def canBeMadeEqual ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE if ( len1 == len2 ) : NEW_LINE INDENT freq = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT f...
Minimum characters that are to be inserted such that no three consecutive characters are same | Function to return the count of characters that are to be inserted in str1 such that no three consecutive characters are same ; To store the count of operations required ; A character needs to be inserted after str1 [ i + 1 ...
def getCount ( str1 , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n - 2 ) : NEW_LINE INDENT if ( str1 [ i ] == str1 [ i + 1 ] and str1 [ i ] == str1 [ i + 2 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE i = i + 2 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LIN...
Find the number of strings formed using distinct characters of a given string | Function to return the factorial of n ; Function to return the count of all possible strings that can be formed with the characters of the given string without repeating characters ; To store the distinct characters of the string str ; Driv...
def fact ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact *= i ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def countStrings ( string , n ) : NEW_LINE INDENT distinct_char = set ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT distinct_char . add ( string [ i ] ) ;...
Find the character made by adding all the characters of the given string | Function to return the required character ; To store the summ of the characters of the given string ; Add the current character to the summ ; Return the required character ; Driver code
def getChar ( strr ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in range ( len ( strr ) ) : NEW_LINE INDENT summ += ( ord ( strr [ i ] ) - ord ( ' a ' ) + 1 ) NEW_LINE DEDENT if ( summ % 26 == 0 ) : NEW_LINE INDENT return ord ( ' z ' ) NEW_LINE DEDENT else : NEW_LINE INDENT summ = summ % 26 NEW_LINE return chr ( ord ( '...
Reverse the given string in the range [ L , R ] | Function to return the string after reversing characters in the range [ L , R ] ; Invalid range ; While there are characters to swap ; Swap ( str [ l ] , str [ r ] ) ; Driver code
def reverse ( string , length , l , r ) : NEW_LINE INDENT if ( l < 0 or r >= length or l > r ) : NEW_LINE INDENT return string ; NEW_LINE DEDENT string = list ( string ) NEW_LINE while ( l < r ) : NEW_LINE INDENT c = string [ l ] ; NEW_LINE string [ l ] = string [ r ] ; NEW_LINE string [ r ] = c ; NEW_LINE l += 1 ; NEW...
Program to Encrypt a String using ! and @ | Function to encrypt the string ; evenPos is for storing encrypting char at evenPosition oddPos is for storing encrypting char at oddPosition ; Get the number of times the character is to be repeated ; if i is odd , print ' ! ' else print '@ ; Driver code ; Encrypt the String
def encrypt ( input_arr ) : NEW_LINE INDENT evenPos = ' @ ' ; oddPos = ' ! ' ; NEW_LINE for i in range ( len ( input_arr ) ) : NEW_LINE INDENT ascii = ord ( input_arr [ i ] ) ; NEW_LINE repeat = ( ascii - 96 ) if ascii >= 97 else ( ascii - 64 ) ; NEW_LINE for j in range ( repeat ) : NEW_LINE DEDENT DEDENT ' NEW_LINE IN...
Check if expression contains redundant bracket or not | Set 2 | Function to check for redundant braces ; count of no of signs ; Driver Code
def IsRedundantBraces ( A ) : NEW_LINE INDENT a , b = 0 , 0 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] == ' ( ' and A [ i + 2 ] == ' ) ' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( A [ i ] == ' * ' or A [ i ] == ' + ' or A [ i ] == ' - ' or A [ i ] == ' / ' ) : NEW_LINE INDENT a +...
Convert an unbalanced bracket sequence to a balanced sequence | Function to return balancedBrackets String ; Initializing dep to 0 ; Stores maximum negative depth ; if dep is less than minDep ; if minDep is less than 0 then there is need to add ' ( ' at the front ; Reinitializing to check the updated String ; if dep is...
def balancedBrackets ( Str ) : NEW_LINE INDENT dep = 0 NEW_LINE minDep = 0 NEW_LINE for i in Str : NEW_LINE INDENT if ( i == ' ( ' ) : NEW_LINE INDENT dep += 1 NEW_LINE DEDENT else : NEW_LINE INDENT dep -= 1 NEW_LINE DEDENT if ( minDep > dep ) : NEW_LINE INDENT minDep = dep NEW_LINE DEDENT DEDENT if ( minDep < 0 ) : NE...
Minimum operations required to convert a binary string to all 0 s or all 1 s | Function to return the count of minimum operations required ; Increment count when consecutive characters are different ; Answer is rounding off the ( count / 2 ) to lower ; Driver code
def minOperations ( str , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( str [ i ] != str [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return ( count + 1 ) // 2 NEW_LINE DEDENT str = "000111" NEW_LINE n = len ( str ) NEW_LINE print ( minOperations ( str , n )...
Append a digit in the end to make the number equal to the length of the remaining string | Function to return the required digit ; To store the position of the first numeric digit in the string ; To store the length of the string without the numeric digits in the end ; pw stores the current power of 10 and num is to st...
def find_digit ( s , n ) : NEW_LINE INDENT first_digit = - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if s [ i ] < '0' or s [ i ] > '9' : NEW_LINE INDENT first_digit = i NEW_LINE break NEW_LINE DEDENT DEDENT first_digit += 1 NEW_LINE s_len = first_digit NEW_LINE num = 0 NEW_LINE pw = 1 NEW_LINE i...
Check whether str1 can be converted to str2 with the given operations | Function that returns true if str1 can be converted to str2 with the given operations ; Traverse from left to right ; If the two characters do not match ; If possible to combine ; If not possible to combine ; If the two characters match ; If possib...
def canConvert ( str1 , str2 ) : NEW_LINE INDENT i , j = 0 , 0 ; NEW_LINE while ( i < len ( str1 ) and j < len ( str2 ) ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT if ( str1 [ i ] == '0' and str2 [ j ] == '1' and i + 1 < len ( str1 ) and str1 [ i + 1 ] == '0' ) : NEW_LINE INDENT i += 2 ; NEW_L...
Reverse the Words of a String using Stack | function to reverse the words of the given string without using strtok ( ) . ; create an empty string stack ; create an empty temporary string ; traversing the entire string ; push the temporary variable into the stack ; assigning temporary variable as empty ; for the last wo...
def reverse ( s ) : NEW_LINE INDENT stc = [ ] NEW_LINE temp = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] == ' ▁ ' : NEW_LINE stc . append ( temp ) NEW_LINE temp = " " NEW_LINE else : NEW_LINE temp = temp + s [ i ] NEW_LINE DEDENT stc . append ( temp ) NEW_LINE while len ( stc ) != 0 : NEW_LI...
Print an N x M matrix such that each row and column has all the vowels in it | Function to print the required matrix ; Impossible to generate the required matrix ; Store all the vowels ; Print the matrix ; Print vowels for every index ; Shift the vowels by one ; Driver code
def printMatrix ( n , m ) : NEW_LINE INDENT if ( n < 5 or m < 5 ) : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) ; NEW_LINE return ; NEW_LINE DEDENT s = " aeiou " ; NEW_LINE s = list ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT print ( s [ j % 5 ] , end = " ▁ " ) ; NEW_L...
Check if a given string is made up of two alternating characters | Function that returns true if the string is made up of two alternating characters ; Check if ith character matches with the character at index ( i + 2 ) ; If string consists of a single character repeating itself ; Driver code
def isTwoAlter ( s ) : NEW_LINE INDENT for i in range ( len ( s ) - 2 ) : NEW_LINE INDENT if ( s [ i ] != s [ i + 2 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( s [ 0 ] == s [ 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE IN...
Number of character corrections in the given strings to make them equal | Function to return the count of operations required ; To store the count of operations ; No operation required ; One operation is required when any two characters are equal ; Two operations are required when none of the characters are equal ; Ret...
def minOperations ( n , a , b , c ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE y = b [ i ] NEW_LINE z = c [ i ] NEW_LINE if ( x == y and y == z ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( x == y or y == z or x == z ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT ...
Check if string can be made lexicographically smaller by reversing any substring | Function that returns true if s can be made lexicographically smaller by reversing a sub - string in s ; Traverse in the string ; Check if s [ i + 1 ] < s [ i ] ; Not possible ; Driver code
def check ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s [ i ] > s [ i + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE if ( check ( s ) ) : NEW_LIN...
Count of sub | Function to return the count of required sub - strings ; Number of sub - strings from position of current x to the end of str ; To store the number of characters before x ; Driver code
def countSubStr ( str , n , x ) : NEW_LINE INDENT res = 0 ; count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == x ) : NEW_LINE INDENT res += ( ( count + 1 ) * ( n - i ) ) ; NEW_LINE count = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DED...
Count of sub | Function to return the count of possible sub - strings of length n ; Driver code
def countSubStr ( string , n ) : NEW_LINE INDENT length = len ( string ) ; NEW_LINE return ( length - n + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE n = 5 ; NEW_LINE print ( countSubStr ( string , n ) ) ; NEW_LINE DEDENT
Count of sub | Function to return the number of sub - strings that do not contain the given character c ; Length of the string ; Traverse in the string ; If current character is different from the given character ; Update the number of sub - strings ; Reset count to 0 ; For the characters appearing after the last occur...
def countSubstrings ( s , c ) : NEW_LINE INDENT n = len ( s ) NEW_LINE cnt = 0 NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] != c ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Sum += ( cnt * ( cnt + 1 ) ) // 2 NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT Sum += ( cnt * (...
Minimize ASCII values sum after removing all occurrences of one character | Python3 implementation of the approach ; Function to return the minimized sum ; To store the occurrences of each character of the string ; Update the occurrence ; Calculate the sum ; Get the character which is contributing the maximum value to ...
import sys NEW_LINE def getMinimizedSum ( string , length ) : NEW_LINE INDENT maxVal = - ( sys . maxsize - 1 ) NEW_LINE sum = 0 ; NEW_LINE occurrences = [ 0 ] * 26 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT occurrences [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE sum += ord ( string [ i ] ) ; NE...
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Function that returns true if s is palindrome ; Function to return the required index ; Copy the ith character in S ; Copy all the character of string s2 in Temp ; Check whether the string is palindrome ; Driver code
def isPalindrome ( s ) : NEW_LINE INDENT i = 0 ; NEW_LINE j = len ( s ) - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( s [ i ] is not s [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def getIndex ( S1 , S2 , n ) : NEW_LINE INDENT ...
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | Function that returns true if the sub - string starting from index i and ending at index j is a palindrome ; Function to get the required index ; Start comparing the two strings from both ends . ; Break from the loop at fi...
def isPalindrome ( s , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def getIndex ( s1 , s2 , length ) : NEW_LINE INDENT i = 0 ; j = length - 1 ; NEW_LINE whi...
Acronym words | Function to return the number of strings that can be an acronym for other strings ; Frequency array to store the frequency of the first character of every string in the array ; To store the count of required strings ; Current word ; Frequency array to store the frequency of each of the character of the ...
def count_acronym ( n , arr ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( arr [ i ] [ 0 ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT st = arr [ i ] NEW_LINE num = [ 0 ] * 26 NEW_LINE for j in range ( len ( st ) ) ...
Sub | Function that returns true if every lowercase character appears atmost once ; Every character frequency must be not greater than one ; Function that returns the modified good string if possible ; If the length of the string is less than n ; Sub - strings of length 26 ; To store frequency of each character ; Get t...
def valid ( cnt ) : NEW_LINE INDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT if cnt [ i ] >= 2 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def getGoodString ( s , n ) : NEW_LINE INDENT if n < 26 : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT for i in range ( 25 , n ) : NEW_LINE...
Modify the string by swapping continuous vowels or consonants | Function to check if a character is a vowel ; Function to swap two consecutively repeated vowels or consonants ; Traverse through the length of the string ; Check if the two consecutive characters are vowels or consonants ; swap the two characters ; Driver...
def isVowel ( c ) : NEW_LINE INDENT c = c . lower ( ) ; NEW_LINE if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def swapRepeated ( string ) : NEW_LINE INDENT for i in range ( len ( string ) - 1 ) : NEW_LINE INDENT ...
Find the lexicographically largest palindromic Subsequence of a String | Function to find the largest palindromic subsequence ; Find the largest character ; Append all occurrences of largest character to the resultant string ; Driver Code
def largestPalinSub ( s ) : NEW_LINE INDENT res = " " NEW_LINE mx = s [ 0 ] NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT mx = max ( mx , s [ i ] ) NEW_LINE DEDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] == mx : NEW_LINE INDENT res += s [ i ] NEW_LINE DEDENT DEDENT return res NEW_LIN...
Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | Function to print the required string ; count number of 1 s ; To check if the all the 1 s have been used or not ; Print all the 1 s if any 2 is encountered ; If Str1 [ i ] = 0 or Str1 [ i ] = 2 ; If 1 s are not printed yet ; Driver ...
def printString ( Str1 , n ) : NEW_LINE INDENT ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str1 [ i ] == '1' ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT DEDENT used = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str1 [ i ] == '2' and used == False ) : NEW_LINE INDENT used = 1 NEW_LINE ...
K length words that can be formed from given characters without repetition | Python3 implementation of the approach ; Function to return the required count ; To store the count of distinct characters in str ; Traverse str character by character ; If current character is appearing for the first time in str ; Increment t...
import math as mt NEW_LINE def findPermutation ( string , k ) : NEW_LINE INDENT has = [ False for i in range ( 26 ) ] NEW_LINE cnt = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( has [ ord ( string [ i ] ) - ord ( ' a ' ) ] == False ) : NEW_LINE INDENT cnt += 1 NEW_LINE has [ ord ( string [ i ] ) ...
Find the number in a range having maximum product of the digits | Returns the product of digits of number x ; This function returns the number having maximum product of the digits ; Converting both integers to strings ; Let the current answer be r ; Stores the current number having current digit one less than current d...
def product ( x ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( x ) : NEW_LINE INDENT prod *= ( x % 10 ) NEW_LINE x //= 10 ; NEW_LINE DEDENT return prod NEW_LINE DEDENT def findNumber ( l , r ) : NEW_LINE INDENT a = str ( l ) ; NEW_LINE b = str ( r ) ; NEW_LINE ans = r NEW_LINE for i in range ( len ( b ) ) : NEW_LINE IND...
Longest Ordered Subsequence of Vowels | Python3 program to find the longest subsequence of vowels in the specified order ; Mapping values for vowels ; Function to check if given subsequence contains all the vowels or not ; not contain vowel ; Function to find the longest subsequence of vowels in the given string in spe...
vowels = [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] NEW_LINE mapping = { ' a ' : 0 , ' e ' : 1 , ' i ' : 2 , ' o ' : 3 , ' u ' : 4 } NEW_LINE def isValidSequence ( subList ) : NEW_LINE INDENT for vowel in vowels : NEW_LINE INDENT if vowel not in subList : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True N...
Concatenate suffixes of a String | Function to print the expansion of the string ; Take sub - string from i to n - 1 ; Print the sub - string ; Driver code
def printExpansion ( str ) : NEW_LINE INDENT for i in range ( len ( str ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( i , len ( str ) ) : NEW_LINE INDENT print ( str [ j ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT str = " geeks " NEW_LINE printExpansion ( str ) NEW_LINE
Construct a binary string following the given constraints | Function to print a binary string which has ' a ' number of 0 ' s , ▁ ' b ' ▁ number ▁ of ▁ 1' s and there are at least ' x ' indices such that s [ i ] != s [ i + 1 ] ; Divide index value by 2 and store it into d ; If index value x is even and x / 2 is not equ...
def constructBinString ( a , b , x ) : NEW_LINE INDENT d = x // 2 NEW_LINE if x % 2 == 0 and x // 2 != a : NEW_LINE INDENT d -= 1 NEW_LINE print ( "0" , end = " " ) NEW_LINE a -= 1 NEW_LINE DEDENT for i in range ( d ) : NEW_LINE INDENT print ( "10" , end = " " ) NEW_LINE DEDENT a = a - d NEW_LINE b = b - d NEW_LINE for...
Check If every group of a ' s ▁ is ▁ followed ▁ by ▁ a ▁ group ▁ of ▁ b ' s of same length | Function to match whether there are always n consecutive b ' s ▁ followed ▁ by ▁ n ▁ consecutive ▁ a ' s throughout the string ; Traverse through the string ; Count a 's in current segment ; Count b 's in current segment ; If b...
def matchPattern ( s ) : NEW_LINE INDENT count = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT while ( i < n and s [ i ] == ' a ' ) : NEW_LINE INDENT count += 1 ; NEW_LINE i = + 1 ; NEW_LINE DEDENT while ( i < n and s [ i ] == ' b ' ) : NEW_LINE INDENT count -= 1 ; NEW_LINE i ...
Length of longest consecutive ones by at most one swap in a Binary String | Function to calculate the length of the longest consecutive 1 's ; To count all 1 's in the string ; To store cumulative 1 's ; Counting cumulative 1 's from left ; If 0 then start new cumulative one from that i ; perform step 3 of the approach...
def maximum_one ( s , n ) : NEW_LINE INDENT cnt_one = 0 NEW_LINE cnt , max_cnt = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT cnt_one += 1 NEW_LINE cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT max_cnt = max ( max_cnt , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT max...
Maximum length substring with highest frequency in a string | function to return maximum occurred substring of a string ; size of string ; to store maximum frequency ; To store string which has maximum frequency ; return substring which has maximum freq ; Driver code ; Function call
def MaxFreq ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT string = ' ' NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT string += s [ j ] NEW_LINE if string in m . keys ( ) : NEW_LINE INDENT m [ string ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ str...
Lexicographically smallest substring with maximum occurrences containing a ' s ▁ and ▁ b ' s only | Function to Find the lexicographically smallest substring in a given string with maximum frequency and contains a ' s ▁ and ▁ b ' s only . ; To store frequency of digits ; size of string ; Take lexicographically larger d...
def maxFreq ( s , a , b ) : NEW_LINE INDENT fre = [ 0 for i in range ( 10 ) ] NEW_LINE n = len ( s ) NEW_LINE if ( a > b ) : NEW_LINE INDENT swap ( a , b ) NEW_LINE DEDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT a = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE fre [ a ] += 1 NEW_LINE DEDENT if ( fre [ a ] == 0 and fre...
Minimum steps to convert one binary string to other only using negation | Function to find the minimum steps to convert string a to string b ; List to mark the positions needed to be negated ; If two character are not same then they need to be negated ; To count the blocks of 1 ; To count the number of 1 ' s ▁ in ▁ eac...
def convert ( n , a , b ) : NEW_LINE INDENT l = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT l [ i ] = 1 NEW_LINE DEDENT DEDENT cc = 0 NEW_LINE vl = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( l [ i ] == 0 ) : NEW_LINE INDENT if ( vl != 0 ) : NEW_LINE ...
Generate a sequence with the given operations | function to find minimum required permutation ; Driver code
def StringMatch ( S ) : NEW_LINE INDENT lo , hi = 0 , len ( S ) NEW_LINE ans = [ ] NEW_LINE for x in S : NEW_LINE INDENT if x == ' I ' : NEW_LINE INDENT ans . append ( lo ) NEW_LINE lo += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( hi ) NEW_LINE hi -= 1 NEW_LINE DEDENT DEDENT return ans + [ lo ] NEW_LINE DE...
Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes | Function to find number of ways ; initialise result that store No . of swaps required ; Traverse both strings and check the bits as explained ; calculate result ; Driver code
def countWays ( s1 , s2 , n ) : NEW_LINE INDENT a = b = c = d = 0 NEW_LINE result = 0 ; NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( s2 [ i ] == '0' ) : NEW_LINE INDENT if ( s1 [ i ] == '0' ) : NEW_LINE INDENT c += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT d += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE ...
Find the player who rearranges the characters to get a palindrome string first | Function that returns the winner of the game ; Initialize the freq array to 0 ; Iterate and count the frequencies of each character in the string ; Count the odd occurring character ; If odd occurrence ; Check condition for Player - 1 winn...
def returnWinner ( s , l ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( 0 , l , 1 ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] % 2 != 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DE...
Maximum sum and product of the M consecutive digits in a number | Python implementation of above approach ; Function to find the maximum product ; Driver code
import sys NEW_LINE def maxProductSum ( string , m ) : NEW_LINE INDENT n = len ( string ) NEW_LINE maxProd , maxSum = ( - ( sys . maxsize ) - 1 , - ( sys . maxsize ) - 1 ) NEW_LINE for i in range ( n - m + 1 ) : NEW_LINE INDENT product , sum = 1 , 0 NEW_LINE for j in range ( i , m + i ) : NEW_LINE INDENT product = prod...
Find time taken for signal to reach all positions in a string | Python3 program to Find time taken for signal to reach all positions in a string ; Returns time needed for signal to traverse through complete string . ; for the calculation of last index ; for strings like oxoooo , xoxxoooo ; if coun is greater than max_l...
import sys NEW_LINE import math NEW_LINE def maxLength ( s , n ) : NEW_LINE INDENT right = 0 NEW_LINE left = 0 NEW_LINE coun = 0 NEW_LINE max_length = - ( sys . maxsize - 1 ) NEW_LINE s = s + '1' NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT if s [ i ] == ' o ' : NEW_LINE INDENT coun += 1 NEW_LINE DEDENT else...
Lexicographically largest string formed from the characters in range L and R | Function to return the lexicographically largest string ; hash array ; make 0 - based indexing ; iterate and count frequencies of character ; ans string ; iterate in frequency array ; add til all characters are added ; Driver Code
def printLargestString ( s , l , r ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE for i in range ( min ( l , r ) , max ( l , r ) + 1 ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = " " NEW_LINE for i in range ( 25 , - 1 , - 1 ) : NEW_LINE INDENT wh...
Arrange a binary string to get maximum value within a range of indices | Python implementation of the approach ; Storing the count of 1 's in the string ; Query of l and r ; Applying range update technique . ; Taking prefix sum to get the range update values ; Final array which will store the arranged string ; if after...
def arrange ( s ) : NEW_LINE INDENT cc = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == "1" ) : NEW_LINE INDENT cc += 1 NEW_LINE DEDENT DEDENT a = [ 0 ] * ( len ( s ) + 1 ) NEW_LINE qq = [ ( 2 , 3 ) , ( 5 , 5 ) ] NEW_LINE n = len ( qq ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT l , r = ...
Check whether the vowels in a string are in alphabetical order or not | Function that checks whether the vowel characters in a string are in alphabetical order or not ; ASCII Value 64 is less than all the alphabets so using it as a default value ; check if the vowels in the string are sorted or not ; if the vowel is sm...
def areVowelsInOrder ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE c = chr ( 64 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) : NEW_LINE INDENT if s [ i ] < c : NEW_LINE INDENT return False NEW_LINE DEDENT e...
Program to replace every space in a string with hyphen | Python program for the above approach ; Split by space and converting String to list and ; joining the list and storing in string ; returning thee string ; Driver code
def printHyphen ( string ) : NEW_LINE INDENT lis = list ( string . split ( " ▁ " ) ) NEW_LINE string = ' - ' . join ( lis ) NEW_LINE return string NEW_LINE DEDENT string = " Text ▁ contains ▁ malayalam ▁ and ▁ level ▁ words " NEW_LINE print ( printHyphen ( string ) ) NEW_LINE
Rearrange the string to maximize the number of palindromic substrings | Function to return the newString ; length of string ; hashing array ; iterate and count ; resulting string ; form the resulting string ; number of times character appears ; append to resulting string ; Driver Code
def newString ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE freq = [ 0 ] * ( 26 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = " " NEW_LINE for i in range ( 0 , 26 ) : NEW_LINE INDENT for j in range ( 0 , freq [ i ] ) : NEW_LINE INDENT ans += c...
Program to find remainder when large number is divided by r | Function to Return Remainder ; len is variable to store the length of Number string . ; loop that find Remainder ; Return the remainder ; Driver code ; Get the large number as string ; Get the divisor R ; Find and print the remainder
def Remainder ( str , R ) : NEW_LINE INDENT l = len ( str ) NEW_LINE Rem = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT Num = Rem * 10 + ( ord ( str [ i ] ) - ord ( '0' ) ) NEW_LINE Rem = Num % R NEW_LINE DEDENT return Rem NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "13589234356546756" ...
Number of balanced bracket subsequence of length 2 and 4 | Python 3 implementation of above approach ; Taking the frequency suffix sum of the number of 2 's present after every index ; Storing the count of subsequence ; Subsequence of length 2 ; Subsequence of length 4 of type 1 1 2 2 ; Subsequence of length 4 of type...
def countWays ( a , n ) : NEW_LINE INDENT suff = [ 0 ] * n NEW_LINE if ( a [ n - 1 ] == 2 ) : NEW_LINE INDENT suff [ n - 1 ] = 1 NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] == 2 ) : NEW_LINE INDENT suff [ i ] = suff [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT suff [ i ] ...
Count the number of carry operations required to add two numbers | Function to count the number of carry operations ; Initialize the value of carry to 0 ; Counts the number of carry operations ; Initialize len_a and len_b with the sizes of strings ; Assigning the ascii value of the character ; Add both numbers / digits...
def count_carry ( a , b ) : NEW_LINE INDENT carry = 0 ; NEW_LINE count = 0 ; NEW_LINE len_a = len ( a ) ; NEW_LINE len_b = len ( b ) ; NEW_LINE while ( len_a != 0 or len_b != 0 ) : NEW_LINE INDENT x = 0 ; NEW_LINE y = 0 ; NEW_LINE if ( len_a > 0 ) : NEW_LINE INDENT x = int ( a [ len_a - 1 ] ) + int ( '0' ) ; NEW_LINE l...
Check if a number is in given base or not | Python3 program to check if given number is in given base or not . ; Allowed bases are till 16 ( Hexadecimal ) ; If base is below or equal to 10 , then all digits should be from 0 to 9. ; If base is below or equal to 16 , then all digits should be from 0 to 9 or from 'A ; Dri...
def isInGivenBase ( Str , base ) : NEW_LINE INDENT if ( base > 16 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( base <= 10 ) : NEW_LINE INDENT for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( Str [ i ] . isnumeric ( ) and ( ord ( Str [ i ] ) >= ord ( '0' ) and ord ( Str [ i ] ) < ( ord ( '0' ) + base ) )...
Find indices of all occurrence of one string in other | Python program to find indices of all occurrences of one String in other . ; Driver code
def printIndex ( str , s ) : NEW_LINE INDENT flag = False ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i : i + len ( s ) ] == s ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE flag = True ; NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " NONE " ) ; NEW_LINE DED...
Alternatively Merge two Strings in Java | Function for alternatively merging two strings ; To store the final string ; For every index in the strings ; First choose the ith character of the first string if it exists ; Then choose the ith character of the second string if it exists ; Driver Code
def merge ( s1 , s2 ) : NEW_LINE INDENT result = " " NEW_LINE i = 0 NEW_LINE while ( i < len ( s1 ) ) or ( i < len ( s2 ) ) : NEW_LINE INDENT if ( i < len ( s1 ) ) : NEW_LINE INDENT result += s1 [ i ] NEW_LINE DEDENT if ( i < len ( s2 ) ) : NEW_LINE INDENT result += s2 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT retur...
Maximum occurring character in an input string | Set | function to find the maximum occurring character in an input string which is lexicographically first ; freq [ ] used as hash table ; to store maximum frequency ; length of str ; get frequency of each character of 'str ; for each character , where character is obtai...
def getMaxOccurringChar ( str ) : NEW_LINE INDENT freq = [ 0 for i in range ( 100 ) ] NEW_LINE max = - 1 NEW_LINE len__ = len ( str ) NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , len__ , 1 ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in ran...
Check if the given string of words can be formed from words present in the dictionary | Python3 program to check if a sentence can be formed from a given set of words . include < bits / stdc ++ . h > ; here isEnd is an integer that will store count of words ending at that node ; utility function to create a new node ; ...
ALPHABET_SIZE = 26 ; NEW_LINE class trieNode : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . t = [ None for i in range ( ALPHABET_SIZE ) ] NEW_LINE self . isEnd = 0 NEW_LINE DEDENT DEDENT def getNode ( ) : NEW_LINE INDENT temp = trieNode ( ) NEW_LINE return temp ; NEW_LINE DEDENT def insert ( root , ke...
Given two numbers as strings , find if one is a power of other | Python3 program to check if one number is a power of other ; Multiply the numbers . It multiplies each digit of second string to each digit of first and stores the result . ; If the digit exceeds 9 , add the cumulative carry to previous digit . ; If all z...
def isGreaterThanEqualTo ( s1 , s2 ) : NEW_LINE INDENT if len ( s1 ) > len ( s2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return s1 == s2 NEW_LINE DEDENT def multiply ( s1 , s2 ) : NEW_LINE INDENT n , m = len ( s1 ) , len ( s2 ) NEW_LINE result = [ 0 ] * ( n + m ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : N...
Check for balanced parentheses in an expression | O ( 1 ) space | Function1 to match closing bracket ; Function1 to match opening bracket ; Function to check balanced parentheses ; helper variables ; Handling case of opening parentheses ; Handling case of closing parentheses ; If corresponding matching opening parenthe...
def matchClosing ( X , start , end , open , close ) : NEW_LINE INDENT c = 1 NEW_LINE i = start + 1 NEW_LINE while ( i <= end ) : NEW_LINE INDENT if ( X [ i ] == open ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT elif ( X [ i ] == close ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT return i NEW...
Sorting array with conditional swapping | Function to check if it is possible to sort the array ; Calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; Otherwise , we can sort the array . ; Driver Code
def possibleToSort ( arr , n , str ) : NEW_LINE INDENT max_element = - 1 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT max_element = max ( max_element , arr [ i ] ) NEW_LINE if ( str [ i ] == '0' ) : NEW_LINE INDENT if ( max_element > i + 1 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT DEDENT ret...
Prime String | Function that checks if sum is prime or not ; corner cases ; This is checked so that we can skip middle five numbers in below loop ; Driver code
def isPrimeString ( str1 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE n = 0 NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT n += ord ( str1 [ i ] ) NEW_LINE DEDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LI...
Ways to split string such that each partition starts with distinct character | Returns the number of we can split the string ; Finding the frequency of each character . ; making frequency of first character of string equal to 1. ; Finding the product of frequency of occurrence of each character . ; Driver Code
def countWays ( s ) : NEW_LINE INDENT count = [ 0 ] * 26 ; NEW_LINE for x in s : NEW_LINE INDENT count [ ord ( x ) - ord ( ' a ' ) ] = ( count [ ord ( x ) - ord ( ' a ' ) ] ) + 1 ; NEW_LINE DEDENT count [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] = 1 ; NEW_LINE ans = 1 ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( co...
Lexicographically next greater string using same character set | function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; searching the first character left of index k and...
def lexoString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE v = [ ] NEW_LINE mp = { s [ i ] : 0 for i in range ( len ( s ) ) } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( mp [ s [ i ] ] == 0 ) : NEW_LINE INDENT mp [ s [ i ] ] = 1 NEW_LINE v . append ( s [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( r...
Number of palindromic permutations | Set 1 | Python3 program to find number of palindromic permutations of a given string ; Returns factorial of n ; Returns count of palindromic permutations of str . ; Count frequencies of all characters ; Since half of the characters decide count of palindromic permutations , we take ...
MAX = 256 NEW_LINE def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def countPalinPermutations ( str ) : NEW_LINE INDENT global MAX NEW_LINE n = len ( str ) NEW_LINE freq = [ 0 ] * MAX ; NEW_LINE for i in range ( 0 ...