text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Maximum possible time that can be formed from four digits | Python3 implementation of the approach ; Function to return the updated frequency map for the array passed as argument ; Function that returns true if the passed digit is present in the map after decrementing it 's frequency by 1 ; If map contains the digit ; ... | from collections import defaultdict NEW_LINE def getFrequencyMap ( arr , n ) : NEW_LINE INDENT hashMap = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hashMap [ arr [ i ] ] += 1 NEW_LINE DEDENT return hashMap NEW_LINE DEDENT def hasDigit ( hashMap , digit ) : NEW_LINE INDENT if hashMap [ di... |
Most frequent word in first String which is not present in second String | Python3 implementation of above approach ; Function to return frequent word from S1 that isn 't present in S2 ; create map of banned words ; find smallest and most frequent word ; check if word is not banned ; return answer ; Driver Code | from collections import defaultdict NEW_LINE def smallestFreq ( S1 , S2 ) : NEW_LINE INDENT banned = defaultdict ( lambda : 0 ) NEW_LINE i = 0 NEW_LINE while i < len ( S2 ) : NEW_LINE INDENT s = " " NEW_LINE while i < len ( S2 ) and S2 [ i ] != ' β ' : NEW_LINE INDENT s += S2 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i += ... |
Minimum characters to be replaced to remove the given substring | Function to calculate minimum characters to replace ; mismatch occurs ; If all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driv... | def replace ( A , B ) : NEW_LINE INDENT n , m = len ( A ) , len ( B ) NEW_LINE count , i = 0 , 0 NEW_LINE while i < n : NEW_LINE INDENT j = 0 NEW_LINE while j < m : NEW_LINE INDENT if i + j >= n or A [ i + j ] != B [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == m : NEW_LINE INDENT count +=... |
Largest connected component on a grid | Python3 program to print the largest connected component in a grid ; stores information about which cell are already visited in a particular BFS ; result stores the final result grid ; stores the count of cells in the largest connected component ; Function checks if a cell is val... | n = 6 ; NEW_LINE m = 8 ; NEW_LINE visited = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE result = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE COUNT = 0 NEW_LINE def is_valid ( x , y , key , input ) : NEW_LINE INDENT if ( x < n and y < m and x >= 0 and y >= 0 ) : NEW_LINE INDENT if ( vis... |
Check if a string is substring of another | Returns true if s1 is substring of s2 ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; Driver Code | def isSubstring ( s1 , s2 ) : NEW_LINE INDENT M = len ( s1 ) NEW_LINE N = len ( s2 ) NEW_LINE for i in range ( N - M + 1 ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( s2 [ i + j ] != s1 [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j + 1 == M : NEW_LINE INDENT return i NEW_LINE DEDENT DEDE... |
Splitting a Numeric String | Function accepts a string and checks if string can be split . ; if there is only 1 number in the string then it is not possible to split it ; storing the substring from 0 to i + 1 to form initial number of the increasing sequence ; convert string to integer and add 1 and again convert back ... | def split ( Str ) : NEW_LINE INDENT Len = len ( Str ) NEW_LINE if ( Len == 1 ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE return NEW_LINE DEDENT s1 , s2 = " " , " " NEW_LINE for i in range ( ( Len // 2 ) + 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE s1 = Str [ 0 : i + 1 ] NEW_LINE num1 = int ( s1 ) NEW_LINE nu... |
Count of number of given string in 2D character array | utility function to search complete string from any given index of 2d array ; through Backtrack searching in every directions ; Function to search the string in 2d array ; Driver code | def internalSearch ( ii , needle , row , col , hay , row_max , col_max ) : NEW_LINE INDENT found = 0 NEW_LINE if ( row >= 0 and row <= row_max and col >= 0 and col <= col_max and needle [ ii ] == hay [ row ] [ col ] ) : NEW_LINE INDENT match = needle [ ii ] NEW_LINE ii += 1 NEW_LINE hay [ row ] [ col ] = 0 NEW_LINE if ... |
Find minimum shift for longest common prefix | function for KMP search ; preprocessing of longest proper prefix ; find out the longest prefix and position ; for new position with longer prefix in str2 update pos and Len ; prresult ; Driver Code | def KMP ( m , n , str2 , str1 ) : NEW_LINE INDENT pos = 0 NEW_LINE Len = 0 NEW_LINE p = [ 0 for i in range ( m + 1 ) ] NEW_LINE k = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT while ( k > 0 and str1 [ k ] != str1 [ i - 1 ] ) : NEW_LINE INDENT k = p [ k ] NEW_LINE DEDENT if ( str1 [ k ] == str1 [ i - 1 ] )... |
Find all the patterns of "1(0 + ) 1" in a given string | SET 1 ( General Approach ) | Function to count patterns ; Variable to store the last character ; We found 0 and last character was '1' , state change ; After the stream of 0 ' s , β we β got β a β ' 1 ', counter incremented ; Last character stored ; Driver Code | def patternCount ( str ) : NEW_LINE INDENT last = str [ 0 ] NEW_LINE i = 1 ; counter = 0 NEW_LINE while ( i < len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == '0' and last == '1' ) : NEW_LINE INDENT while ( str [ i ] == '0' ) : NEW_LINE INDENT i += 1 NEW_LINE if ( str [ i ] == '1' ) : NEW_LINE INDENT counter += 1 NEW_... |
Boyer Moore Algorithm | Good Suffix heuristic | preprocessing for strong good suffix rule ; m is the length of pattern ; if character at position i - 1 is not equivalent to character at j - 1 , then continue searching to right of the pattern for border ; the character preceding the occurrence of t in pattern P is diffe... | def preprocess_strong_suffix ( shift , bpos , pat , m ) : NEW_LINE INDENT i = m NEW_LINE j = m + 1 NEW_LINE bpos [ i ] = j NEW_LINE while i > 0 : NEW_LINE INDENT while j <= m and pat [ i - 1 ] != pat [ j - 1 ] : NEW_LINE INDENT if shift [ j ] == 0 : NEW_LINE INDENT shift [ j ] = j - i NEW_LINE DEDENT j = bpos [ j ] NEW... |
Maximum length prefix of one string that occurs as subsequence in another | Return the maximum length prefix which is subsequence . ; Iterating string T . ; If end of string S . ; If character match , increment counter . ; Driver Code | def maxPrefix ( s , t ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , len ( t ) ) : NEW_LINE INDENT if ( count == len ( s ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( t [ i ] == s [ count ] ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT S = " digger " NEW_LINE ... |
Replace all occurrences of string AB with C without using extra space | Python 3 program to replace all occurrences of " AB " with " C " ; Start traversing from second character ; If previous character is ' A ' and current character is 'B" ; Replace previous character with ' C ' and move all subsequent characters one p... | def translate ( st ) : NEW_LINE INDENT for i in range ( 1 , len ( st ) ) : NEW_LINE INDENT if ( st [ i - 1 ] == ' A ' and st [ i ] == ' B ' ) : NEW_LINE INDENT st [ i - 1 ] = ' C ' NEW_LINE for j in range ( i , len ( st ) - 1 ) : NEW_LINE INDENT st [ j ] = st [ j + 1 ] NEW_LINE DEDENT st [ len ( st ) - 1 ] = ' β ' NEW_... |
Find all occurrences of a given word in a matrix | Python3 Program to find all occurrences of the word in a matrix ; check whether given cell ( row , col ) is a valid cell or not . ; return true if row number and column number is in range ; These arrays are used to get row and column numbers of 8 neighboursof a given c... | ROW = 3 NEW_LINE COL = 5 NEW_LINE def isvalid ( row , col , prevRow , prevCol ) : NEW_LINE INDENT return ( row >= 0 ) and ( row < ROW ) and ( col >= 0 ) and ( col < COL ) and not ( row == prevRow and col == prevCol ) NEW_LINE DEDENT rowNum = [ - 1 , - 1 , - 1 , 0 , 0 , 1 , 1 , 1 ] NEW_LINE colNum = [ - 1 , 0 , 1 , - 1 ... |
Generate N Random Hexadecimal Numbers | Python3 program for the above approach ; Maximum length of the random integer ; Function to generate N Hexadecimal integers ; Stores all the possible charcters in the Hexadecimal notation ; Loop to print N integers ; Randomly select length of the int in the range [ 1 , maxSize ] ... | import random , math NEW_LINE maxSize = 10 ; NEW_LINE def randomHexInt ( N ) : NEW_LINE INDENT hexChar = [ '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT Len = math . floor ( random . random ( ) * ( maxSize - ... |
Check if two array of string are equal by performing swapping operations | Function to check whether brr [ ] can be made equal to arr [ ] by doing swapping operations ; siz variable to store size of string ; iterate till N to sort strings ; sort each string in arr [ ] ; sort each string in brr [ ] ; Sort both the vecto... | def checkEqualArrays ( arr , brr , N ) : NEW_LINE INDENT siz = len ( arr [ 0 ] ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp1 = list ( arr [ i ] ) ; NEW_LINE temp1 . sort ( ) ; NEW_LINE arr [ i ] = " " . join ( temp1 ) NEW_LINE temp2 = list ( brr [ i ] ) ; NEW_LINE temp2 . sort ( ) ; NEW_LINE brr [ i ] = " "... |
Maximum length of string formed by concatenation having even frequency of each character | Python3 implementation of the above approach ; Function to check the string ; Count the frequency of the string ; Check the frequency of the string ; Store the length of the new String ; Function to find the longest concatenated ... | maxi = 0 ; NEW_LINE ans1 = " " ; NEW_LINE def calculate ( ans ) : NEW_LINE INDENT global maxi , ans1 ; NEW_LINE dp = [ 0 ] * 26 ; NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT dp [ ord ( ans [ i ] ) - ord ( ' A ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( dp [ i ] % 2 == 1 ) : N... |
Find the next number by adding natural numbers in order on alternating indices from last | Function to generate the resultant number using the given criteria ; Storing end result ; Find the length of numeric string ; Traverse the string ; Storing digit at ith position ; Checking that the number would be added or not ; ... | def generateNumber ( number ) : NEW_LINE INDENT temp = 0 ; adding_number = 0 ; NEW_LINE result = " " ; NEW_LINE l = len ( number ) ; NEW_LINE for i in range ( l - 1 , - 1 , - 1 ) : NEW_LINE INDENT digit = ord ( number [ i ] ) - ord ( '0' ) ; NEW_LINE if ( temp % 2 == 0 ) : NEW_LINE INDENT adding_number += 1 ; NEW_LINE ... |
Find the single digit sum of alphabetical values of a string | Python program for the above approach ; Traverse the given string ; If character is an alphabet ; Stores the sum of order of values ; Find the score ; Find the single digit sum ; Return the resultant sum ; Driver Code | def findTheSum ( str ) : NEW_LINE INDENT alpha = " " NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if ( ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) or ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) ) : NEW_LINE INDENT alpha += str [ i ] NEW_LINE DEDENT DEDENT score = 0 NEW_LINE n = 0 NEW_LINE for i in ... |
Minimum value of K such that each substring of size K has the given character | Function to find the minimum value of K such that char c occurs in all K sized substrings of string S ; Store the string length ; Store difference of lengths of segments of every two consecutive occurrences of c ; Stores the maximum differe... | def findK ( s , c ) : NEW_LINE INDENT n = len ( s ) NEW_LINE diff = 0 NEW_LINE max = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == c ) : NEW_LINE INDENT diff = i - prev NEW_LINE prev = i NEW_LINE if ( diff > max ) : NEW_LINE INDENT max = diff NEW_LINE DEDENT DEDENT DEDENT if ( ... |
Count subsequences 01 in string generated by concatenation of given numeric string K times | Function to calculate the number of subsequences of "01" ; Store count of 0 ' s β and β 1' s ; Count of subsequences without concatenation ; Case 1 ; Case 2 ; Return the total count ; Driver Code | def countSubsequence ( S , N , K ) : NEW_LINE INDENT C = 0 NEW_LINE C1 = 0 NEW_LINE C0 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT C1 += 1 NEW_LINE DEDENT elif ( S [ i ] == '0' ) : NEW_LINE INDENT C0 += 1 NEW_LINE DEDENT DEDENT B1 = 0 NEW_LINE for i in range ( 0 , N )... |
Count of distinct groups of strings formed after performing equivalent operation | Function to perform the find operation to find the parent of a disjoint set ; Function to perform union operation of disjoint set union ; Find the parent of node a and b ; Update the rank ; Function to find the number of distinct strings... | def Find ( parent , a ) : NEW_LINE INDENT if parent [ a ] == a : NEW_LINE INDENT parent [ a ] = a NEW_LINE return parent [ a ] NEW_LINE DEDENT else : NEW_LINE INDENT parent [ a ] = Find ( parent , parent [ a ] ) NEW_LINE return parent [ a ] NEW_LINE DEDENT DEDENT def Union ( parent , rank , a , b ) : NEW_LINE INDENT a ... |
Minimum adjacent swaps required to make a binary string alternating | Function to find the minimum number of adjacent swaps to make the string alternating ; Count the no of zeros and ones ; Base Case ; Store no of min swaps when string starts with "1" ; Keep track of the odd positions ; Checking for when the string sta... | def minSwaps ( s ) : NEW_LINE INDENT ones = 0 NEW_LINE zeros = 0 NEW_LINE N = len ( s ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if s [ i ] == '1' : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zeros += 1 NEW_LINE DEDENT DEDENT if ( ( N % 2 == 0 and ones != zeros ) or ( N % 2 == 1 and abs ( o... |
Print all ways to reach the Nth stair with the jump of 1 or 2 units at a time | Function to find all the ways to reach Nth stair using one or two jumps ; Base Cases ; Recur for jump1 and jump2 ; Stores the total possible jumps ; Add "1" with every element present in jump1 ; Add "2" with every element present in jump2 ;... | def TotalPossibleJumps ( N ) : NEW_LINE INDENT if ( ( N - 1 ) == 0 ) : NEW_LINE INDENT newvec = [ ] NEW_LINE newvec . append ( " " ) NEW_LINE return newvec NEW_LINE DEDENT else : NEW_LINE INDENT if ( N < 0 ) : NEW_LINE INDENT newvec = [ ] NEW_LINE return newvec NEW_LINE DEDENT DEDENT jump1 = TotalPossibleJumps ( N - 1 ... |
Find any permutation of Binary String of given size not present in Array | Function to find a binary string of N bits that does not occur in the givrn array arr [ ] ; Stores the resultant string ; Loop to iterate over all the given strings in a diagonal order ; Append the complement of element at current index into ans... | def findString ( arr , N ) : NEW_LINE INDENT ans = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans += '1' if arr [ i ] [ i ] == '0' else '0' NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ "111" , "011" , "001" ] NEW_LINE N = len ( arr ) NEW_LINE print ( find... |
Check if the string has a reversible equal substring at the ends | Function to print longest substring that appears at beginning of string and also at end in reverse order ; Stores the resultant string ; If the characters are same ; Otherwise , break ; If the string can 't be formed ; Otherwise print resultant string ;... | def commonSubstring ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE ans = " " NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE i = i + 1 NEW_LINE j = j - 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT ... |
Length of Smallest Non Prime Subsequence in given numeric String | Function to find the smallest length of resultant subsequence ; Check for a subsequence of size 1 ; Check for a subsequence of size 2 ; If none of the above check is successful then subsequence must be of size 3 ; Never executed ; Driver Code | def findMinimumSubsequence ( S ) : NEW_LINE INDENT flag = False NEW_LINE dummy = ' ' NEW_LINE for j in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ j ] != '2' and S [ j ] != '3' and S [ j ] != '5' and S [ j ] != '7' ) : NEW_LINE INDENT print ( 1 ) NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag =... |
Minimize changes to make all characters equal by changing vowel to consonant and vice versa | Python 3 program for the above approach ; Function to find the minimum number of steps to make all characters equal ; Initializing the variables ; Store the frequency ; Iterate over the string ; Calculate the total number of v... | import sys NEW_LINE from collections import defaultdict NEW_LINE def operations ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE vowels = 0 NEW_LINE consonants = 0 NEW_LINE max_vowels = - sys . maxsize - 1 NEW_LINE max_consonants = - sys . maxsize - 1 NEW_LINE freq_consonants = defaultdict ( int ) NEW_LINE freq_vowels = defaul... |
Count of ways to empty given String by recursively removing all adjacent duplicates | Python3 implementation for the above approach ; Define the dp table globally ; Recursive function to calculate the dp values for range [ L , R ] ; The range is odd length ; The state is already calculated ; If the length is 2 ; Total ... | import numpy as np NEW_LINE dp = np . zeros ( ( 505 , 505 ) ) ; NEW_LINE choose = np . zeros ( ( 502 , 502 ) ) ; NEW_LINE def calc ( l , r , s ) : NEW_LINE INDENT if ( abs ( r - l ) % 2 == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( l > r ) : NEW_LINE INDENT dp [ l ] [ r ] = 1 ; NEW_LINE return dp [ l ] [ r ]... |
Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation | Function to check for valid subsequences ; Stores which element belongs to which subsequence ; Check for each pos if a possible subsequence exist or not ; Last member of 1 subsequence ; Last Member ... | def findSubsequence ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = [ '0' for i in range ( n ) ] NEW_LINE for pos in range ( 10 ) : NEW_LINE INDENT lst1 = '0' NEW_LINE flag = 1 NEW_LINE lst2 = chr ( pos + 48 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( lst2 <= str [ i ] ) : NEW_LINE INDENT res [ i ] ... |
Find Kth lexicographical ordered numeric string of length N with distinct products of each substring | Java program for the above approach ; Function to find the required String ; If the current length is equal to n exit from here only ; Iterate for all the characters ; Check if the product is present before ; If the c... | s = ' ' NEW_LINE K = 0 NEW_LINE def getString ( curlen , N , prod ) : NEW_LINE INDENT global s , K NEW_LINE if ( curlen == N ) : NEW_LINE INDENT K -= 1 NEW_LINE if ( K == 0 ) : NEW_LINE INDENT ans = s NEW_LINE DEDENT return NEW_LINE DEDENT ch = '2' NEW_LINE while ( ch <= '9' ) : NEW_LINE INDENT s = chr ( ord ( s ) + or... |
Minimum swaps to balance the given brackets at any index | Function to balance the given bracket by swap ; To count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; ... | def BalancedStringBySwapping ( s ) : NEW_LINE INDENT unbalancedPair = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( unbalancedPair > 0 and s [ i ] == ' ] ' ) : NEW_LINE INDENT unbalancedPair -= 1 ; NEW_LINE DEDENT elif ( s [ i ] == ' [ ' ) : NEW_LINE INDENT unbalancedPair += 1 ; NEW_LINE DEDENT DEDEN... |
Count of palindromic strings of size upto N consisting of first K alphabets occurring at most twice | Function of return the number of palindromic strings of length N with first K alphabets possible ; If N is odd , half + 1 position can be filled to cope with the extra middle element ; K is reduced by one , because cou... | def lengthNPalindrome ( N , K ) : NEW_LINE INDENT half = N // 2 ; NEW_LINE if ( N & 1 ) : NEW_LINE INDENT half += 1 ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( 1 , half + 1 ) : NEW_LINE INDENT ans *= K ; NEW_LINE K -= 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def palindromicStrings ( N , K ) : NEW_LINE... |
Minimum number of characters required to be added to a String such that all lowercase alphabets occurs as a subsequence in increasing order | Python3 program for the above approach ; Function to find the LCS of strings S and string T ; Base Case ; Already Calculated State ; If the characters are the same ; Otherwise ; ... | import numpy as np NEW_LINE def LCS ( S , N , T , M , dp ) : NEW_LINE INDENT if ( N == 0 or M == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ N ] [ M ] != 0 ) : NEW_LINE INDENT return dp [ N ] [ M ] ; NEW_LINE DEDENT if ( S [ N - 1 ] == T [ M - 1 ] ) : NEW_LINE INDENT dp [ N ] [ M ] = 1 + LCS ( S , N - 1 ... |
Count ways to make the number formed by K concatenations of a numeric string divisible by 5 | Python program for the above approach ; Function to find the value of a ^ b modulo 1000000007 ; Stores the resultant value a ^ b ; Find the value of a ^ b ; Function to count the number of ways such that the formed number is d... | MOD = 1000000007 NEW_LINE def exp_mod ( a , b ) : NEW_LINE INDENT ret = 1 NEW_LINE while ( b ) : NEW_LINE INDENT if ( b & 1 ) : NEW_LINE INDENT ret = ret * a % MOD NEW_LINE DEDENT b >>= 1 NEW_LINE a = a * a % MOD NEW_LINE DEDENT return ret NEW_LINE DEDENT def countOfWays ( s , k ) : NEW_LINE INDENT N = len ( s ) NEW_LI... |
Find the string present at the middle of a lexicographically increasing sequence of strings from S to T | Function to print the string at the middle of lexicographically increasing sequence of strings from S to T ; Stores the base 26 digits after addition ; Iterete from right to left and add carry to next position ; Re... | def printMiddleString ( S , T , N ) : NEW_LINE INDENT a1 = [ 0 ] * ( N + 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT a1 [ i + 1 ] = ord ( S [ i ] ) - ord ( " a " ) + ord ( T [ i ] ) - ord ( " a " ) ; NEW_LINE DEDENT for i in range ( N , 1 , - 1 ) : NEW_LINE INDENT a1 [ i - 1 ] += a1 [ i ] // 26 ; NEW_LINE a1 ... |
Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Python program to solve the above approach ; initializing first and second variable as to store how many string ' s ' and string ' t ' will be appended ; storing tmp length ; if length of string tmp is greater than k , then we have reached... | def KthCharacter ( s , t , k ) : NEW_LINE INDENT f = 1 NEW_LINE ss = 2 NEW_LINE tmp = " " NEW_LINE lenn = len ( tmp ) NEW_LINE while ( lenn < k ) : NEW_LINE INDENT tf = f NEW_LINE ts = ss NEW_LINE while ( tf != 0 ) : NEW_LINE INDENT tf -= 1 NEW_LINE tmp += s NEW_LINE DEDENT while ( ts != 0 ) : NEW_LINE INDENT ts -= 1 N... |
Find character at Kth index by appending S1 ( M ) times and S2 ( M + 1 ) times | Python program to solve the above approach ; storing length ; variables for temporary strings of s and t ; final output variable ; if k is greater than even after adding string ' s ' ' first ' times ( let ' s β call β it β x ) β we ' ll su... | def KthCharacter ( s , t , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = len ( t ) NEW_LINE first = 1 NEW_LINE second = 2 NEW_LINE output = ' ? ' NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( k > first * n ) : NEW_LINE INDENT x = first * n NEW_LINE k = k - x NEW_LINE first = first + 2 NEW_LINE if ( k > second * m ... |
Count of ways to rearrange N digits and M alphabets keeping all alphabets together | Python program of the above approach ; Function to find the factorial of the given number ; Function to count ways to rearrange characters of the string such that all alphabets are adjacent . ; Stores factorial of ( N + 1 ) ; Stores fa... | import math NEW_LINE def fact ( a ) : NEW_LINE INDENT return math . factorial ( a ) NEW_LINE DEDENT def findComb ( N , M ) : NEW_LINE INDENT x = fact ( N + 1 ) NEW_LINE y = fact ( M ) NEW_LINE return ( x * y ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE M = 2 NEW_LINE print ( findCo... |
Count of camel case characters present in a given string | Function to count all the camelcase characters in the string S ; Stores the total count of camelcase characters ; Traverse the string S ; If ASCII value of character lies over the range [ 65 , 91 ] then increment the count ; Print the total count obtained ; Dri... | def countCamelCase ( S ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( ord ( S [ i ] ) >= 65 and ord ( S [ i ] ) <= 91 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ckjkUUYII " NEW_... |
Decode a given string by removing duplicate occurrences | Function to count the appearances of each character ; If the character is lower case ; If the character is uppercase ; If the character is a punctuation mark ; Function to decode the given encoded string ; Iterate the given string str ; Find the index of the nex... | def findRepetition ( a ) : NEW_LINE INDENT if a <= ' z ' and a >= ' a ' : NEW_LINE INDENT return ord ( a ) - 97 NEW_LINE DEDENT elif a <= ' Z ' and a >= ' A ' : NEW_LINE INDENT return ord ( a ) - 65 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def decodeString ( str_ ) : NEW_LINE INDENT output... |
Program to perform a letter frequency attack on a monoalphabetic substitution cipher | Function to decrypt a monoalphabetic substitution cipher using the letter frequency attack ; Stores final 5 possible deciphered plaintext ; Store the frequency of each letter in cipher text ; Stores the frequency of each letter in ci... | def printString ( S , N ) : NEW_LINE INDENT plaintext = [ None ] * 5 NEW_LINE freq = [ 0 ] * 26 NEW_LINE freqSorted = [ None ] * 26 NEW_LINE used = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] != ' β ' : NEW_LINE INDENT freq [ ord ( S [ i ] ) - 65 ] += 1 NEW_LINE DEDENT DEDENT for i in range ( ... |
Count of substrings in a Binary String that contains more 1 s than 0 s | Function to merge two partitions such that the merged array is sorted ; Counting inversions ; Function to implement merge sort ; Function to calculate number of inversions in a given array ; Calculate the number of inversions ; Return the number o... | def merge ( v , left , mid , right , inversions ) : NEW_LINE INDENT temp = [ 0 for i in range ( right - left + 1 ) ] NEW_LINE i = left NEW_LINE j = mid + 1 NEW_LINE k = 0 NEW_LINE cnt = 0 NEW_LINE while ( i <= mid and j <= right ) : NEW_LINE INDENT if ( v [ i ] <= v [ j ] ) : NEW_LINE INDENT temp [ k ] = v [ i ] NEW_LI... |
Check if a string consisting only of a , b , c can be made empty by removing substring " abc " recursively | Function to check if the given string S can be made empty ; Stores the characters of the string S ; Traverse the given string ; If the character is c ; If stack size is greater than 2 ; Pop from the stack ; Top ... | def canMadeEmpty ( s , n ) : NEW_LINE INDENT st = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] == ' c ' : NEW_LINE INDENT if len ( st ) >= 2 : NEW_LINE INDENT b = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE a = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE if a != ' a ' or b != ' b ' : NEW_LINE INDENT retur... |
Check if summation of two words is equal to target word | Function to check weather summation of two words equal to target word ; Store the length of each string ; Reverse the strings A , B and C ; Stores the remainder ; Iterate in the range [ 0 , max ( L , max ( M , N ) ) ] ; Stores the integer at ith position from th... | def isSumEqual ( A , B , C ) : NEW_LINE INDENT L = len ( A ) NEW_LINE M = len ( B ) NEW_LINE N = len ( A ) NEW_LINE A = A [ : : - 1 ] NEW_LINE B = B [ : : - 1 ] NEW_LINE C = C [ : : - 1 ] NEW_LINE rem = 0 NEW_LINE for i in range ( max ( L , max ( M , N ) ) ) : NEW_LINE INDENT curr = rem NEW_LINE if ( i < L ) : NEW_LINE... |
Minimum K such that every substring of length at least K contains a character c | Set | Function to find minimum value of K such that there exist atleast one K amazing character ; Stores the answer ; Update the S ; Iterate over the characters in range [ a , z ] ; Stores the last index where c appears ; Stores the maxim... | def MinimumLengthSubstring ( S , N ) : NEW_LINE INDENT ans = N NEW_LINE S = "0" + S + "0" NEW_LINE S = [ i for i in S ] NEW_LINE for c in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT prev = 0 NEW_LINE max_len = 0 NEW_LINE S [ 0 ] = chr ( c ) NEW_LINE S [ N + 1 ] = chr ( c ) NEW_LINE for i in range ( 1 ... |
Minimize hamming distance in Binary String by setting only one K size substring bits | Function to find minimum Hamming Distance after atmost one operation ; Store the size of the string ; Store the prefix sum of 1 s ; Create Prefix Sum array ; Initialize cnt as number of ones in string S ; Store the required result ; ... | def minimumHammingDistance ( S , K ) : NEW_LINE INDENT n = len ( S ) NEW_LINE pref = [ 0 ] * n NEW_LINE pref [ 0 ] = ord ( S [ 0 ] ) - ord ( '0' ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + ( ord ( S [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT cnt = pref [ n - 1 ] NEW_LINE ans = cnt N... |
Check if a permutation of S2 can be obtained by adding or removing characters from S1 | Python 3 program for the above approach ; Function to check if the given number is prime or not ; If the number is less than 2 ; If the number is 2 ; If N is a multiple of 2 ; Otherwise , check for the odds values ; Function to chec... | from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( n ) ) + 1 , 2 ) : NEW_LINE IN... |
Count ways to split a string into two subsets that are reverse of each other | Function to find the total number of ways to partitiaon the string into two subset satisfying the conditions ; Stores the resultant number of ways of splitting ; Iterate over the range [ 0 , 2 ^ N ] ; Traverse the string S ; If ith bit is se... | def countWays ( S , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for mask in range ( ( 1 << N ) ) : NEW_LINE INDENT X , Y = " " , " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( mask >> i & 1 ) : NEW_LINE INDENT X += S [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT Y += S [ i ] NEW_LINE DEDENT DEDENT Y = Y [ : : - 1 ]... |
Check if String formed by first and last X characters of a String is a Palindrome | Function to check whether the first x characters of both string str and reversed string str are same or not ; Length of the string str ; Traverse over the string while first and last x characters are not equal ; If the current and n - k... | def isEqualSubstring ( string , x ) : NEW_LINE INDENT n = len ( string ) NEW_LINE i = 0 NEW_LINE while i < n and i < x : NEW_LINE INDENT if ( string [ i ] != string [ n - i - 1 ] ) : NEW_LINE INDENT print ( " false " ) NEW_LINE return NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( " true " ) NEW_LINE return NEW_LINE DE... |
Flip the String by either swapping given characters or rotating it horizontally for Q queries | Function to find final string after applying all Queries on it ; Traverse the Queries array ; Convert A , B to zero indexing ; Query of 1 st type ; Swap ath and bth characters ; Query of 2 nd type ; Swap first N characters w... | def solve ( S , N , Queries , Q ) : NEW_LINE INDENT S = list ( S ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT T = Queries [ i ] [ 0 ] NEW_LINE A = Queries [ i ] [ 1 ] NEW_LINE B = Queries [ i ] [ 2 ] NEW_LINE A -= 1 NEW_LINE B -= 1 NEW_LINE if ( T == 1 ) : NEW_LINE INDENT temp = S [ A ] NEW_LINE S [ A ] = S [ B ] ... |
Minimum number of replacement done of substring "01" with "110" to remove it completely | Function to find the minimum number of replacement of "01" with "110" s . t . S doesn 't contain substring "10" ; Stores the number of operations performed ; Stores the resultant count of substrings ; Traverse the string S from en... | def minimumOperations ( S , N ) : NEW_LINE INDENT ans = 0 NEW_LINE cntOne = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT ans += cntOne NEW_LINE cntOne *= 2 NEW_LINE DEDENT else : NEW_LINE INDENT cntOne += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( ans ) ... |
Count different Bitwise OR values of equal length strings S1 and S2 by swapping exactly one pair of characters from the first string | Function to find the number of ways to obtain different Bitwise OR ; Stores the count of pairs t00 , t10 , t01 , t11 ; Traverse the characters of the string S1 and S2 ; Count the pair (... | def differentBitwiseOR ( s1 , s2 ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE t00 = 0 NEW_LINE t10 = 0 NEW_LINE t01 = 0 NEW_LINE t11 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s1 [ i ] == '0' and s2 [ i ] == '0' ) : NEW_LINE INDENT t00 += 1 NEW_LINE DEDENT if ( s1 [ i ] == '1' and s2 [ i ] == '0' ) : NEW_L... |
Flip all 0 s in given Binary Strings K times with different neighbours | Function to modify the given string K number of times by flipping 0 s having different adjacent characters ; Size of the string ; Stores modified string after each iteration ; Iterate over the range [ 0 k ] ; Traverse the string S ; If '0' is pres... | def convertString ( S , k ) : NEW_LINE INDENT n = len ( S ) NEW_LINE temp = S NEW_LINE temp = list ( temp ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT if ( j == 0 and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = S [ j + 1 ] NEW_LINE DEDENT elif ( j == n - 1 and S [ j ]... |
Minimum number of removals required such that no subsequence of length 2 occurs more than once | Function to remove the minimum count of characters from the string such that no subsequence of length 2 repeats ; Initialize the final string ; Stores if any character occurs in the final string or not ; Store the index of ... | def RemoveCharacters ( s ) : NEW_LINE INDENT ans = " " NEW_LINE c = [ 0 for i in range ( 26 ) ] NEW_LINE pos = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( c [ ord ( s [ i ] ) - 97 ] == 0 ) : NEW_LINE INDENT c [ ord ( s [ i ] ) - 97 ] = 1 NEW_LINE pos = i NEW_LINE ans += s [ i ] NEW_LINE DEDENT DEDENT... |
Check if a numeric string can be split into substrings having difference between consecutive numbers equal to K | Function to check if a numeric string can be split into substrings such that the difference between the consecutive substrings is K ; Stores the size of the string ; Iterate over the range [ 1 , N ] and try... | def isPossible ( s , K ) : NEW_LINE INDENT valid = False NEW_LINE firstx = - 1 NEW_LINE n = len ( s ) NEW_LINE for i in range ( 1 , n // 2 + 1 , 1 ) : NEW_LINE INDENT x = int ( s [ 0 : i ] ) NEW_LINE firstx = x NEW_LINE test = str ( x ) NEW_LINE while ( len ( test ) < len ( s ) ) : NEW_LINE INDENT x -= K NEW_LINE test ... |
Convert given Binary string S to all 1 s by changing all 0 s to 1 s in range [ i + 1 , i + K ] if S [ i ] is 1 | Function to check whether all 0 s in the string can be changed into 1 s ; Store the count of 0 s converted for the last occurrence of 1 ; Declere a stack ; Traverse the string , S ; If stack is empty ; There... | def changeCharacters ( S , N , K ) : NEW_LINE INDENT flag = 1 NEW_LINE count = 0 NEW_LINE st = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if len ( st ) == 0 : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT count = 0 NEW_LINE st . append ( S [ i ] ) NEW_LINE DEDE... |
Check if all prefixes of a number is divisible by remaining count of digits | Function to check if all prefixes of a number is divisible by remaining count of digits or not ; Traverse and check divisibility for each updated number ; Update the original number ; Given Input ; Function Call | def prefixDivisble ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while n > 0 : NEW_LINE INDENT if n % i != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT n = n // 10 NEW_LINE i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT n = 52248 NEW_LINE if ( prefixDivisble ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT ... |
Length of the longest substring that contains even number of vowels | Function to find the length of the longest substring having even number of vowels ; Create two hashmaps ; Keep the track of frequencies of the vowels ; Stores the maximum length ; Traverse the given string S ; If it is a vowel , then update the frequ... | def longestSubstring ( s ) : NEW_LINE INDENT indexes = { } NEW_LINE chars = { } NEW_LINE chars [ ' a ' ] = 0 NEW_LINE chars [ ' e ' ] = 1 NEW_LINE chars [ ' i ' ] = 2 NEW_LINE chars [ ' o ' ] = 3 NEW_LINE chars [ ' u ' ] = 4 NEW_LINE evenOdd = "00000" NEW_LINE evenOdd = [ i for i in evenOdd ] NEW_LINE indexes [ " " . j... |
Minimum number whose binary form is not a subsequence of given binary string | Function to check if string str1 is a subsequence of string str2 ; Store index of str1 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 ; If matched , move ahead in str1 ; If all characters o... | def isSubsequence ( str1 , str2 , m , n ) : NEW_LINE INDENT j = 0 NEW_LINE i = 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( str1 [ j ] == str2 [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( j == m ) NEW_LINE DEDENT def findMinimumNumber ( s ) : NEW_LINE INDENT r = int ( ... |
Minimize cost to make all characters of a Binary String equal to '1' by reversing or flipping characters of substrings | Function to calculate minimum cost to convert all the characters of S to '1 ; Stores the result ; Stores the number of groups that have 0 as characters ; Traverse the S ; If current character is '0 ;... | ' NEW_LINE def MinimumCost ( S , A , B ) : NEW_LINE INDENT count = 0 NEW_LINE group = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count > 0 ) : NEW_LINE INDENT group += 1 NEW_LINE DEDENT count ... |
Count strings having sum of ASCII values of characters equal to a Prime or Armstrong Number | Function to check if a number is prime number ; Define a flag variable ; Check for factors of num ; If factor is found , set flag to True and break out of loop ; Check if flag is True ; Function to calculate order of the numbe... | def isPrime ( num ) : NEW_LINE INDENT flag = False NEW_LINE if num > 1 : NEW_LINE INDENT for i in range ( 2 , num ) : NEW_LINE INDENT if ( num % i ) == 0 : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if flag : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True N... |
Minimize cost of flipping or swaps to make a Binary String balanced | Function to find the minimum cost to convert the given into balanced string ; Stores count of 1 ' s β and β 0' s in the string ; Traverse the string ; Increment count1 ; Increment count 0 ; Stores absolute difference of counts of 0 ' s β and β 1' s ;... | def findMinimumCost ( s , N ) : NEW_LINE INDENT count_1 , count_0 = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT DEDENT k = abs ( count_0 - count_1 ) NEW_LINE if ( count_1 == N or count_0 ==... |
Minimum time required to complete all tasks with alteration of their order allowed | Python3 program for the above approach ; Function to find the minimum time required to complete the tasks if the order of tasks can be changed ; If there is no task , print 0 ; Store the maximum occurring character and its frequency ; ... | import sys NEW_LINE from collections import defaultdict NEW_LINE def findMinimumTime ( S , N , K ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT maxfreq = - sys . maxsize NEW_LINE um = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT um [ S [ i ] ] += 1... |
Check if all characters of a string can be made equal by increments or decrements | Function to check if it is possible to make all characters of string S same or not ; Length of string ; Stores the sum of ASCII value ; Traverse the string S ; Update the weightOfString ; If the sum is divisible by N then pr " Yes " ; O... | def canMakeEqual ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE weightOfString = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT weightOfString += ord ( S [ i ] ) - ord ( ' a ' ) + 1 NEW_LINE DEDENT if ( weightOfString % N == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ... |
Modify a string by circularly shifting each character to the right by respective frequencies | Function to replace the characters by its frequency of character in it ; Stores frequencies of characters in the string S ; Traverse the string S ; Increment the frequency of each character by 1 ; Traverse the string S ; Find... | def addFrequencyToCharacter ( S ) : NEW_LINE INDENT frequency = [ 0 for i in range ( 26 ) ] NEW_LINE N = len ( S ) NEW_LINE S = list ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT frequency [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT add = frequency [ ord ( S [... |
Minimize length of a string by removing pairs of consecutive increasing or decreasing digits | Function to find the minimum length of the string possible after removing pairs of consecutive digits ; Initialize the stack st ; Traverse the string S ; If the stack is empty ; Otherwise ; Get the top character of the stack ... | def minLength ( S ) : NEW_LINE INDENT st = [ ] NEW_LINE for ch in S : NEW_LINE INDENT if ( len ( st ) == 0 ) : NEW_LINE INDENT st . append ( ch ) NEW_LINE DEDENT else : NEW_LINE INDENT top = st [ - 1 ] NEW_LINE if ( abs ( ord ( ch ) - ord ( top ) ) == 1 ) : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT else : NEW_LINE I... |
Minimum time required to complete all tasks without altering their order | Function to find the minimum time required to complete tasks without changing their order ; Keeps track of the last time instant of each task ; Stores the required result ; Traverse the given string ; Check last time instant of task , if it exis... | def findMinimumTime ( tasks , K ) : NEW_LINE INDENT map = { } NEW_LINE curr_time = 0 NEW_LINE for c in tasks : NEW_LINE INDENT if ( c in map ) : NEW_LINE INDENT if ( curr_time - map <= K ) : NEW_LINE INDENT curr_time += K - ( curr_time - map ) + 1 NEW_LINE DEDENT DEDENT map = curr_time NEW_LINE curr_time += 1 NEW_LINE ... |
Check if a string is a subsequence of another string ( using Stacks ) | Function to check if target is a subsequence of string S ; Declare a stack ; Push the characters of target into the stack ; Traverse the string S in reverse ; If the stack is empty ; If S [ i ] is same as the top of the stack ; Pop the top of stack... | def checkforSubsequence ( S , target ) : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( len ( target ) ) : NEW_LINE INDENT s . append ( target [ i ] ) NEW_LINE DEDENT for i in range ( len ( S ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDE... |
Program to construct a DFA to check if a given integer is unsigned or not | Python3 program for the above approach ; Function to construct DFA as per the given conditions ; If at state 0 and a digit has occurred then set it to state 1 ; Similarly for all other states ; Function to build and connect the DFA states ; Con... | digits , sign = "0123456789" , " + - " NEW_LINE dot , ex = " . " , " eE " NEW_LINE dfa = [ [ 0 for i in range ( 5 ) ] for i in range ( 11 ) ] NEW_LINE def makeDFA ( ) : NEW_LINE INDENT global dfa NEW_LINE dfa [ 0 ] [ 0 ] = 1 NEW_LINE dfa [ 1 ] [ 0 ] = 1 NEW_LINE dfa [ 1 ] [ 2 ] = 3 NEW_LINE dfa [ 1 ] [ 3 ] = 2 NEW_LINE... |
Convert a Mobile Numeric Keypad sequence to equivalent sentence | Function to convert mobile numeric keypad sequence into its equivalent string ; Store the mobile keypad mappings ; Traverse the str1ing str1 ; If the current character is ' . ' , then continue to the next iteration ; Stores the number of continuous click... | def printSentence ( str1 ) : NEW_LINE INDENT nums = [ " " , " " , " ABC " , " DEF " , " GHI " , " JKL " , " MNO " , " PQRS " , " TUV " , " WXYZ " ] NEW_LINE i = 0 NEW_LINE while ( i < len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] == ' . ' ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT count = 0 NEW_LIN... |
Lexicographically largest string with sum of characters equal to N | Function to construct the lexicographically largest string having sum of characters as N ; Stores the resulting string ; Iterate until N is at least 26 ; Append ' z ' to the string ans ; Decrement N by 26 ; Append character at index ( N + ' a ' ) ; Re... | def getString ( N ) : NEW_LINE INDENT ans = " " NEW_LINE while ( N >= 26 ) : NEW_LINE INDENT ans += ' z ' NEW_LINE N -= 26 NEW_LINE DEDENT ans += chr ( N + ord ( ' a ' ) - 1 ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 30 NEW_LINE print ( getString ( N ) ) NEW_LINE DEDENT |
Length of all prefixes that are also the suffixes of given string | Function to find the length of all prefixes of the given that are also suffixes of the same string ; Stores the prefix string ; Traverse the S ; Add the current character to the prefix string ; Store the suffix string ; Check if both the strings are eq... | def countSamePrefixSuffix ( s , n ) : NEW_LINE INDENT prefix = " " NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT prefix += s [ i ] NEW_LINE suffix = s [ n - 1 - i : 2 * n - 2 - i ] NEW_LINE if ( prefix == suffix ) : NEW_LINE INDENT print ( len ( prefix ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ =... |
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | Function to count newly created pairs by swapping the first characters of any pairs of strings ; Stores the count all possible pair of strings ; Push all the strings into the Unordered Map ; Generate all ... | def countStringPairs ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE s = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT s [ a [ i ] ] = s . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT p = [ i for i in a [ i ] ] NEW_LINE q = [ j for j in... |
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times | Function to check if a valid parenthesis can be obtained by moving characters to either end at most K number of times ; Base Case 1 ; Count of ' ( ' and ') ; Base Case 2 ; Store the count of moves required to m... | def minimumMoves ( s , n , k ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT countOpen = s . count ( ' ( ' ) NEW_LINE countClose = s . count ( ' ) ' ) NEW_LINE if ( countOpen != countClose ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return N... |
Generate a random Binary String of length N | Python3 program for the above approach ; Function to find a random number between 0 or 1 ; Generate the random number ; Return the generated number ; Function to generate a random binary string of length N ; Stores the empty string ; Iterate over the range [ 0 , N - 1 ] ; S... | import random NEW_LINE def findRandom ( ) : NEW_LINE INDENT num = random . randint ( 0 , 1 ) NEW_LINE return num NEW_LINE DEDENT def generateBinaryString ( N ) : NEW_LINE INDENT S = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = findRandom ( ) NEW_LINE S += str ( x ) NEW_LINE DEDENT print ( S ) NEW_LINE DEDENT... |
Partition a string into palindromic strings of at least length 2 with every character present in a single string | Function to check if a string can be split into palindromic strings of at least length 2 by including every character exactly once ; Stores the frequency of each character ; Store the frequency of characte... | def checkPalindrome ( s ) : NEW_LINE INDENT a = [ 0 ] * 26 NEW_LINE o , e = 0 , 0 NEW_LINE for i in s : NEW_LINE INDENT a [ ord ( i ) - 97 ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT o += 1 NEW_LINE DEDENT elif ( a [ i ] % 2 == 0 and a [ i ] != 0 ) : NEW_LINE IND... |
Maximize time by replacing ' _ ' in a given 24 Hour format time | Function to find the maximum time possible by replacing each ' _ ' with any digit ; If the first character is '_ ; If s [ 1 ] is ' _ ' or s [ 1 ] is less than 4 ; Update s [ 0 ] as 2 ; Otherwise , update s [ 0 ] = 1 ; If s [ 1 ] is equal to '_ ; If s [ 0... | def maximumTime ( s ) : NEW_LINE INDENT s = list ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( s [ 0 ] == ' _ ' ) : NEW_LINE INDENT if ( ( s [ 1 ] == ' _ ' ) or ( s [ 1 ] >= '0' and s [ 1 ] < '4' ) ) : NEW_LINE INDENT s [ 0 ] = '2' NEW_LINE DEDENT else : NEW_LINE INDENT s [ 0 ] = '1' NEW_LINE DEDENT DEDENT DEDENT ' NEW_... |
How to create half of the string in uppercase and the other half in lowercase ? | | import math NEW_LINE string1 = ' geeks β for β geeks ' NEW_LINE string1_len = len ( string1 ) NEW_LINE half_string = math . ceil ( string1_len / 2 ) NEW_LINE part_a = ' ' NEW_LINE part_b = ' ' NEW_LINE part_a = string1 [ : half_string ] NEW_LINE new_part_a = part_a . upper ( ) NEW_LINE part_b = string1 [ half_string : ... |
Nearest power of 2 of frequencies of each digit of a given number | Python3 program for the above approach ; Function to find the nearest power of 2 for all frequencies in the Map freq ; Traverse the Map ; Calculate log of the current array element ; Find the nearest power of 2 for the current frequency ; Function to f... | from math import log2 , pow NEW_LINE def nearestPowerOfTwoUtil ( freq ) : NEW_LINE INDENT temp = { } NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT lg = int ( log2 ( value ) ) NEW_LINE a = int ( pow ( 2 , lg ) ) NEW_LINE b = int ( pow ( 2 , lg + 1 ) ) NEW_LINE if ( ( value - a ) < ( b - value ) ) : NEW_... |
Smallest string divisible by two given strings | Function to calculate GCD of two numbers ; Function to calculate LCM of two numbers ; Function to find the smallest string which is divisible by strings S and T ; Store the length of both strings ; Store LCM of n and m ; Temporary strings to store concatenated strings ; ... | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def lcm ( a , b ) : NEW_LINE INDENT return ( a // gcd ( a , b ) ) * b NEW_LINE DEDENT def findSmallestString ( s , t ) : NEW_LINE INDENT n , m = len ( s ) , len ( t ) NEW_LINE l = lcm ( ... |
Minimum substring flips required to convert a Binary String to another | Function to count the minimum number of reversals required to make the given binary strings s1 and s2 same ; Stores the minimum count of reversal of substrings required ; If the length of the strings are not the same then return - 1 ; Iterate over... | def canMakeSame ( s1 , s2 ) : NEW_LINE INDENT ans = - 1 NEW_LINE if ( len ( s1 ) != len ( s2 ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT N = len ( s1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT while ( i < len ( s1 ) and s1 [ i ] != s2 [ i ] ) : NEW_LINE INDE... |
Count points which are revisited while following the path specified by a given string | Function to find the number of times already visited position is revisited after starting traversal from { X , Y } ; Stores the x and y temporarily ; Stores the number of times an already visited position is revisited ; Initialize h... | def count ( S , X , Y ) : NEW_LINE INDENT N = len ( S ) NEW_LINE temp_x , temp_y = 0 , 0 NEW_LINE count = 0 NEW_LINE s = { } NEW_LINE s [ ( X , Y ) ] = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp_x = X NEW_LINE temp_y = Y NEW_LINE if ( S [ i ] == ' U ' ) : NEW_LINE INDENT X += 1 NEW_LINE DEDENT elif ( S [ i ... |
Sum of frequencies of characters of a string present in another string | Function to find sum of frequencies of characters of S1 present in S2 ; Insert all characters of string S1 in the set ; Traverse the string S2 ; Check if X is present in bset or not ; Increment count by 1 ; Finally , print the count ; Given string... | def countTotalFrequencies ( S1 , S2 ) : NEW_LINE INDENT bset = set ( S1 ) NEW_LINE count = 0 NEW_LINE for x in S2 : NEW_LINE INDENT if x in bset : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT S1 = " geEksFOR " NEW_LINE S2 = " GeEksforgeEKS " NEW_LINE countTotalFrequencies ( S1 , S2 ... |
Make a given Binary String non | Function to return the length of smallest subsequence required to be removed to make the given string non - decreasing ; Length of the string ; Count of zeros and ones ; Traverse the string ; Count minimum removals to obtain strings of the form "00000 . . . . " or "11111 . . . " ; Incre... | def min_length ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE total_zeros = 0 NEW_LINE total_ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT total_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT total_ones += 1 NEW_LINE DEDENT DEDENT ans = min ( total_zeros , tot... |
Print all words occurring in a sentence exactly K times | Function to print all the words occurring k times in a string ; Stores the words ; Traverse the list ; Check for count ; Print the word ; Remove from list ; Driver Code ; Given string ; Given value of K ; Function call to find all words occuring K times | def kFreqWords ( S , K ) : NEW_LINE INDENT l = list ( S . split ( " β " ) ) NEW_LINE for i in l : NEW_LINE INDENT if l . count ( i ) == K : NEW_LINE INDENT print ( i ) NEW_LINE l . remove ( i ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " banana β is β in β yellow β and β sun β ... |
Check if substrings from three given strings can be concatenated to form a palindrome | Function to check if substrings from three given strings can be concatenated to form a palindrome ; Mask for S1 and S2 ; Set ( i - ' a ' ) th bit in maskA ; Set ( i - ' a ' ) th bit in maskC ; If the bitwise AND is > 0 ; Driver Code | def make_palindrome ( S1 , S2 , S3 ) : NEW_LINE INDENT maskA , maskC = 0 , 0 NEW_LINE for i in S1 : NEW_LINE INDENT maskA |= ( 1 << ( ord ( i ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT for i in S3 : NEW_LINE INDENT maskC |= ( 1 << ( ord ( i ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT if ( ( maskA & maskC ) > 0 ) : NEW_LINE INDENT... |
Length of longest prefix anagram which are common in given two strings | Python3 program for the above approach ; Function to check if two arrays are identical or not ; Iterate over the range [ 0 , SIZE ] ; If frequency any character is not same in both the strings ; Otherwise ; Function to find the maximum length of t... | SIZE = 26 NEW_LINE def longHelper ( freq1 , freq2 ) : NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq1 [ i ] != freq2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def longCommomPrefixAnagram ( s1 , s2 , n1 , n2 ) : NEW_LINE INDENT freq1 = [ 0 ] * 26 NEW_LIN... |
Lexicographic rank of a Binary String | Function to find the rank of a string ; Store the length of the string ; Stores its equivalent decimal value ; Traverse the string ; Store the number of strings of length less than N occurring before the given string ; Store the decimal equivalent number of string bin ; Store the... | def findRank ( s ) : NEW_LINE INDENT N = len ( s ) ; NEW_LINE sb = " " ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT sb += str ( '0' ) ; NEW_LINE DEDENT else : NEW_LINE INDENT sb += str ( '1' ) ; NEW_LINE DEDENT DEDENT bin = str ( sb ) ; NEW_LINE X = pow ( 2 , N ) ; NEW_L... |
Find the GCD of an array made up of numeric strings | Recursive function to return gcd of A and B ; Base case ; Length of A is greater ; Calculate GCD ; Store the GCD of the length of the strings ; Driver Code ; Function call | def GCD ( lena , lenb ) : NEW_LINE INDENT if ( lena == 0 ) : NEW_LINE INDENT return lenb NEW_LINE DEDENT if ( lenb == 0 ) : NEW_LINE INDENT return lena NEW_LINE DEDENT if ( lena == lenb ) : NEW_LINE INDENT return lena NEW_LINE DEDENT if ( lena > lenb ) : NEW_LINE INDENT return GCD ( lena - lenb , lenb ) NEW_LINE DEDENT... |
Minimize cost to rearrange substrings to convert a string to a Balanced Bracket Sequence | Function to count minimum number of operations to convert the string to a balanced bracket sequence ; Initialize the integer array ; Traverse the string ; Decrement a [ i ] ; Increment a [ i ] ; Update the sum as current value of... | def countMinMoves ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE a = [ 0 for i in range ( n ) ] NEW_LINE j , ans , sum = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ' ) ' ) : NEW_LINE INDENT a [ i ] += sum - 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] += sum + 1 NEW_LINE DEDENT ... |
Check if a given string can be converted to a Balanced Bracket Sequence | Function to check if the can be balanced by replacing the ' $ ' with opening or closing brackets ; If string can never be balanced ; Declare 2 stacks to check if all ) can be balanced with ( or $ and vice - versa ; Store the count the occurence o... | def canBeBalanced ( sequence ) : NEW_LINE INDENT if ( len ( sequence ) % 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT stack_ , stack2_ = [ ] , [ ] NEW_LINE countOpen , countClosed = 0 , 0 NEW_LINE countSymbol = 0 NEW_LINE for i in range ( len ( sequence ) ) : NEW_LINE INDENT if ( sequence [ i ] == ' ) ' ) : NEW_L... |
Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | Function to find difference between maximum and minimum frequency of a character in given range ; Stores length of string ; Stores count of queries ; Iterate over the characters of the string ; St... | def maxDiffFreq ( queries , S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE Q = len ( queries ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT l = queries [ i ] [ 0 ] - 1 NEW_LINE r = queries [ i ] [ 1 ] - 1 NEW_LINE freq = [ 0 ] * 26 NEW_LINE for j in range ( l , r + 1 ) : NEW_LINE INDENT freq [ ord ( S [ j ] ) - ord ( ... |
Count strings from given array having all characters appearing in a given string | Function to count the number of strings from an array having all characters appearing in the string S ; Initialize a set to store all distinct characters of S ; Traverse over S ; Insert characters into the Set ; Stores the required count... | def countStrings ( S , list ) : NEW_LINE INDENT valid = { } NEW_LINE for x in S : NEW_LINE INDENT valid [ x ] = 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( len ( list ) ) : NEW_LINE INDENT j = 0 NEW_LINE while j < len ( list [ i ] ) : NEW_LINE INDENT if ( list [ i ] [ j ] in valid ) : NEW_LINE INDENT j += 1 NEW... |
Minimize a string by removing all occurrences of another string | Function to find the minimum length to which string str can be reduced to by removing all occurrences of string K ; Initialize stack of characters ; Push character into the stack ; If stack size >= K . size ( ) ; Create empty string to store characters o... | def minLength ( Str , N , K , M ) : NEW_LINE INDENT stackOfChar = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT stackOfChar . append ( Str [ i ] ) NEW_LINE if ( len ( stackOfChar ) >= M ) : NEW_LINE INDENT l = " " NEW_LINE for j in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( K [ j ] != stackOfChar [ - 1 ] ... |
Largest palindrome not exceeding N which can be expressed as product of two 3 | Function to find the largest palindrome not exceeding N which can be expressed as the product of two 3 - digit numbers ; Stores all palindromes ; Stores the product ; Check if X is palindrome ; Check n is less than N ; If true , append it i... | def palindrome_prod ( N ) : NEW_LINE INDENT palindrome_list = [ ] NEW_LINE for i in range ( 101 , 1000 ) : NEW_LINE INDENT for j in range ( 121 , 1000 , ( 1 if i % 11 == 0 else 11 ) ) : NEW_LINE INDENT n = i * j NEW_LINE x = str ( n ) NEW_LINE if x == x [ : : - 1 ] : NEW_LINE INDENT if n < N : NEW_LINE INDENT palindrom... |
Check if given strings can be made same by swapping two characters of same or different strings | Function to check if all strings can be made equal by swapping any pair of characters from the same or different strings ; Stores length of string ; Store frequency of each distinct character of the strings ; Traverse the ... | def isEqualStrings ( arr , N ) : NEW_LINE INDENT M = len ( arr [ 0 ] ) NEW_LINE cntFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT cntFreq [ ord ( arr [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 256 ) : NEW_LINE INDENT if ( cntFr... |
Minimize a binary string by repeatedly removing even length substrings of same characters | Recursive function to print stack elements from bottom to top without changing their order ; If stack is empty ; Pop top element of the stack ; Recursively call the function PrintStack ; Print the stack element from the bottom ;... | def PrintStack ( s ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT x = s [ - 1 ] ; NEW_LINE s . pop ( ) ; NEW_LINE PrintStack ( s ) ; NEW_LINE print ( x , end = " " ) ; NEW_LINE s . append ( x ) ; NEW_LINE DEDENT def minString ( s ) : NEW_LINE INDENT Stack = [ ] ; NEW_LINE Stack . a... |
Probability of collision between two trucks | Function to calculate total number of accidents ; Function to calculate count of all possible collision ; Size of string ; Stores the count of collisions ; Total number of truck in lane b ; Count total number of collisions while traversing the string a ; Function to calcula... | def count_of_accident ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if ( n > m ) : NEW_LINE INDENT return ( m * ( m + 1 ) ) / 2 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ) NEW_LINE DEDENT DEDENT def count_of_collision ( a , b ) : NEW_LINE INDENT n ... |
Count alphanumeric palindromes of length N | Function to calculate ( x ^ y ) mod p ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Return the final result ; Given N ; Base Case ; Check whether n is even or odd ; Function Call ; Function Call | def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE... |
Length of the longest substring with every character appearing even number of times | Function to find length of the longest substring with each element occurring even number of times ; Initialize unordered_map ; Stores the length of the longest required substring ; Traverse the string ; Stores the value of the digit p... | def lenOfLongestReqSubstr ( s , N ) : NEW_LINE INDENT ind = { } NEW_LINE mask = 0 NEW_LINE ind [ 0 ] = - 1 NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE mask ^= ( 1 << val ) NEW_LINE if ( mask in ind ) : NEW_LINE INDENT ans = max ( ans , i - ind [ mask ] )... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.