text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Check if a string is a scrambled form of another string | Declaring unordered map globally ; Python3 program to check if a given string is a scrambled form of another string ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Check for t...
map = { } NEW_LINE def isScramble ( S1 : str , S2 : str ) : NEW_LINE INDENT if len ( S1 ) != len ( S2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = len ( S1 ) NEW_LINE if not n : NEW_LINE INDENT return True NEW_LINE DEDENT if S1 == S2 : NEW_LINE INDENT return True NEW_LINE DEDENT if sorted ( S1 ) != sorted ( S2 ...
Print the longest palindromic prefix of a given string | Function to find the longest prefix which is palindrome ; Find the length of the given string ; For storing the length of longest Prefix Palindrome ; Loop to check the substring of all length from 1 to n which is palindrome ; String of length i ; To store the val...
def LongestPalindromicPrefix ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE max_len = 0 NEW_LINE for length in range ( 0 , n + 1 ) : NEW_LINE INDENT temp = string [ 0 : length ] NEW_LINE temp2 = temp NEW_LINE temp3 = temp2 [ : : - 1 ] NEW_LINE if temp == temp3 : NEW_LINE INDENT max_len = length NEW_LINE DEDEN...
Minimum operations to make product of adjacent element pair of prefix sum negative | Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the...
def minOperations ( a ) : NEW_LINE INDENT res = 100000000000 NEW_LINE N = len ( a ) NEW_LINE for r in range ( 0 , 2 ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( ( i + r ) % 2 ) : NEW_LINE INDENT if ( sum <= 0 ) : NEW_LINE INDENT ans += - s...
K | Python program to find the K - th lexicographical string of length N ; Initialize the array to store the base 26 representation of K with all zeroes , that is , the initial string consists of N a 's ; Start filling all the N slots for the base 26 representation of K ; Store the remainder ; Reduce K ; If K is greate...
def find_kth_string_of_n ( n , k ) : NEW_LINE INDENT d = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT d [ i ] = k % 26 NEW_LINE k //= 26 NEW_LINE DEDENT if k > 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += chr ( ...
Length of the smallest substring which contains all vowels | Python3 program to find the length of the smallest substring of which contains all vowels ; Map to store the frequency of vowels ; Store the indices which contains the vowels ; If all vowels are not present in the string ; If the frequency of the vowel at i -...
from collections import defaultdict NEW_LINE def findMinLength ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE counts = defaultdict ( int ) NEW_LINE indices = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' o ' or s [ i ] == ' i ' or s [ i ] == ' u ' ) : NEW_...
Longest Subsequence of a String containing only Consonants | Returns true if x is consonants . ; '' Function to check whether a character is consonants or not ; Function to find the longest subsequence which contain all consonants ; Driver code ; Function call
def isComsomamts ( x ) : NEW_LINE INDENT x = x . lower ( ) NEW_LINE return not ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' ) NEW_LINE DEDENT def longestConsonantsSubsequence ( s ) : NEW_LINE INDENT answer = ' ' NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if isComsomam...
Find the length of the longest subsequence with first K alphabets having same frequency | Python3 program to find the longest subsequence with first K alphabets having same frequency ; Function to return the length of the longest subsequence with first K alphabets having same frequency ; Map to store frequency of all c...
from collections import defaultdict NEW_LINE def lengthOfSubsequence ( st , K ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for ch in st : NEW_LINE INDENT mp [ ch ] += 1 NEW_LINE DEDENT minimum = mp [ ' A ' ] NEW_LINE for i in range ( 1 , K ) : NEW_LINE INDENT minimum = min ( minimum , mp [ chr ( i + ord ( ' A ...
Detecting negative cycle using Floyd Warshall | Number of vertices in the graph ; Define Infinite as a large enough value . This value will be used for vertices not connected to each other ; Returns true if graph has negative weight cycle else false . ; dist [ ] [ ] will be the output matrix that will finally have the ...
V = 4 NEW_LINE INF = 99999 NEW_LINE def negCyclefloydWarshall ( graph ) : NEW_LINE INDENT dist = [ [ 0 for i in range ( V + 1 ) ] for j in range ( V + 1 ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT dist [ i ] [ j ] = graph [ i ] [ j ] NEW_LINE DEDENT DEDENT for k in range (...
Digital Root of a given large integer using Recursion | Function to convert given sum into string ; Loop to extract digit one by one from the given sum and concatenate into the string ; Type casting for concatenation ; Return converted string ; Function to get individual digit sum from string ; Loop to get individual d...
def convertToString ( sum ) : NEW_LINE INDENT str1 = " " NEW_LINE while ( sum ) : NEW_LINE INDENT str1 = str1 + chr ( ( sum % 10 ) + ord ( '0' ) ) NEW_LINE sum = sum // 10 NEW_LINE DEDENT return str1 NEW_LINE DEDENT def GetIndividulaDigitSum ( str1 , len1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len1 ) : N...
Count the Number of matching characters in a pair of strings | Function to count the matching characters ; Traverse the string 1 char by char ; This will check if str1 [ i ] is present in str2 or not str2 . find ( str1 [ i ] ) returns - 1 if not found otherwise it returns the starting occurrence index of that character...
def count ( str1 , str2 ) : NEW_LINE INDENT c = 0 ; j = 0 ; NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if str1 [ i ] in str2 : NEW_LINE INDENT c += 1 ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT print ( " No . ▁ of ▁ matching ▁ characters ▁ are : ▁ " , c ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ "...
Check if count of Alphabets and count of Numbers are equal in the given String | Function to count the number of alphabets ; Counter to store the number of alphabets in the string ; Every character in the string is iterated ; To check if the character is an alphabet or not ; Function to count the number of numbers ; Co...
def countOfLetters ( string ) : NEW_LINE INDENT letter = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( ( string [ i ] >= ' A ' and string [ i ] <= ' Z ' ) or ( string [ i ] >= ' a ' and string [ i ] <= ' z ' ) ) : NEW_LINE INDENT letter += 1 ; NEW_LINE DEDENT DEDENT return letter ; NEW_LINE DEDE...
Check if there is a cycle with odd weight sum in an undirected graph | This function returns true if the current subpart of the forest is two colorable , else false . ; Assign first color to source ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS traversal ; Run while there are vertices in ...
def twoColorUtil ( G , src , N , colorArr ) : NEW_LINE INDENT colorArr [ src ] = 1 NEW_LINE q = [ src ] NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT u = q . pop ( 0 ) NEW_LINE for v in range ( 0 , len ( G [ u ] ) ) : NEW_LINE INDENT if colorArr [ G [ u ] [ v ] ] == - 1 : NEW_LINE INDENT colorArr [ G [ u ] [ v ] ] = 1...
Index of character depending on frequency count in string | Python3 implementation of the approach ; Function to perform the queries ; L [ i ] [ j ] stores the largest i such that ith character appears exactly jth times in str [ 0. . . i ] ; F [ i ] [ j ] stores the smallest i such that ith character appears exactly jt...
import numpy as np NEW_LINE MAX = 26 ; NEW_LINE def performQueries ( string , q , type_arr , ch , freq ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE L = np . zeros ( ( MAX , n ) ) ; NEW_LINE F = np . zeros ( ( MAX , n ) ) ; NEW_LINE cnt = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT k = ord ( strin...
Number of index pairs such that s [ i ] and s [ j ] are anagrams | Function to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; To store the count of sorted strings ; Traverse all strings and store in the map ; Sort the string ; If string exists in map , increment count Else create ...
def anagram_pairs ( s , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp_str = " " . join ( sorted ( s [ i ] ) ) NEW_LINE if temp_str in mp : NEW_LINE INDENT mp [ temp_str ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ temp_str ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE fo...
Insert a Character in a Rotated String | Function to insert the character ; To store last position where the insertion is done ; To store size of the string ; To store the modified string ; To store characters ; Add first character to the string ; Update the size ; Update the index of last insertion ; Insert all other ...
def insert ( arr : list , n : int , k : int ) -> chr : NEW_LINE INDENT ind = 0 NEW_LINE sz = 0 NEW_LINE s = " " NEW_LINE ch = arr [ 0 ] NEW_LINE s += ch NEW_LINE sz = 1 NEW_LINE ind = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ch = arr [ i ] NEW_LINE s1 = s [ 0 : ind + 1 ] NEW_LINE temp = k % sz NEW_LINE ro ...
Rearrange the given string such that all prime multiple indexes have same character | Python3 program to rearrange the given string such that all prime multiple indexes have same character ; To store answer ; Function to rearrange the given string such that all prime multiple indexes have the same character . ; Initial...
N = 100005 NEW_LINE ans = [ 0 ] * N ; NEW_LINE def Rearrange ( s , n ) : NEW_LINE INDENT sieve = [ 1 ] * ( N + 1 ) ; NEW_LINE sz = 0 ; NEW_LINE for i in range ( 2 , n // 2 + 1 ) : NEW_LINE INDENT if ( sieve [ i ] ) : NEW_LINE INDENT for j in range ( 1 , n // i + 1 ) : NEW_LINE INDENT if ( sieve [ i * j ] ) : NEW_LINE I...
Check loop in array according to given constraints | A simple Graph DFS based recursive function to check if there is cycle in graph with vertex v as root of DFS . Refer below article for details . https : www . geeksforgeeks . org / detect - cycle - in - a - graph / ; There is a cycle if an adjacent is visited and pre...
def isCycleRec ( v , adj , visited , recur ) : NEW_LINE INDENT visited [ v ] = True NEW_LINE recur [ v ] = True NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( visited [ adj [ v ] [ i ] ] == False ) : NEW_LINE INDENT if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) : NEW_LINE INDENT re...
Queries to find the last non | Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character u...
MAX = 256 NEW_LINE freq = [ [ 0 for i in range ( 256 ) ] for j in range ( 1000 ) ] NEW_LINE def preCalculate ( string , n ) : NEW_LINE INDENT freq [ ord ( string [ 0 ] ) ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT charToUpdate = chr...
Queries to answer the X | Function to pre - process the sub - strings in sorted order ; Generate all substrings ; Iterate to find all sub - strings ; Store the sub - string in the vector ; Sort the substrings lexicographically ; Driver code ; To store all the sub - strings ; Perform queries
def pre_process ( substrings , s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT dup = " " ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT dup += s [ j ] ; NEW_LINE substrings . append ( dup ) ; NEW_LINE DEDENT DEDENT substrings . sort ( ) ; NEW_LINE return substrings ; NEW_LIN...
Smallest subsequence having GCD equal to GCD of given array | Python3 program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of...
import math NEW_LINE def printSmallSub ( arr , N ) : NEW_LINE INDENT gcdArr = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT gcdArr = math . gcd ( gcdArr , arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] == gcdArr ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LIN...
Minimum cost to modify a string | Function to return the minimum cost ; Initialize result ; To store the frequency of characters of the string ; Update the frequencies of the characters of the string ; Loop to check all windows from a - z where window size is K ; Starting index of window ; Ending index of window ; Chec...
def minCost ( str1 , K ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = 999999999 NEW_LINE count = 0 NEW_LINE cnt = [ 0 for i in range ( 27 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ ord ( str1 [ i ] ) - ord ( ' a ' ) + 1 ] += 1 NEW_LINE DEDENT for i in range ( 1 , 26 - K + 1 , 1 ) : NEW_LINE INDENT a...
Generate all binary strings of length n with sub | Utility function to print the given binary string ; This function will be called recursively to generate the next bit for given binary string according to its current state ; Base - case : if the generated binary string meets the required length and the pattern "01" ap...
def printBinStr ( string , length ) : NEW_LINE INDENT for i in range ( 0 , length ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def generateBinStr ( string , length , currlen , occur , nextbit ) : NEW_LINE INDENT if currlen == length : NEW_LINE INDENT if occur == 2 and...
Print last character of each word in a string | Function to print the last character of each word in the given string ; Now , last word is also followed by a space ; If current character is a space ; Then previous character must be the last character of some word ; Driver code
def printLastChar ( string ) : NEW_LINE INDENT string = string + " ▁ " NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if string [ i ] == ' ▁ ' : NEW_LINE INDENT print ( string [ i - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT string = " Geeks ▁ for ▁ Geeks " NEW_LINE printLastChar ( string ) NEW_LIN...
Maximum length of balanced string after swapping and removal of characters | Function to return the length of the longest balanced sub - string ; To store the count of parentheses ; Traversing the string ; Check type of parentheses and incrementing count for it ; Sum all pair of balanced parentheses ; Driven code
def maxBalancedStr ( s ) : NEW_LINE INDENT open1 = 0 NEW_LINE close1 = 0 NEW_LINE open2 = 0 NEW_LINE close2 = 0 NEW_LINE open3 = 0 NEW_LINE close3 = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : open1 += 1 continue if s [ i ] == ' ) ' : NEW_LINE INDENT close1 += 1 NEW_LINE continue...
Bitwise OR of N binary strings | Function to return the bitwise OR of all the binary strings ; Get max size and reverse each string Since we have to perform OR operation on bits from right to left Reversing the string will make it easier to perform operation from left to right ; Add 0 s to the end of strings if needed ...
def strBitwiseOR ( arr , n ) : NEW_LINE INDENT res = " " NEW_LINE max_size = - ( 2 ** 32 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_size = max ( max_size , len ( arr [ i ] ) ) NEW_LINE arr [ i ] = arr [ i ] [ : : - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT s = " " NEW_LINE for j in range ( m...
Minimum cost to make two strings same | Function to return the minimum cost to make the configuration of both the strings same ; Iterate and find the cost ; Find the minimum cost ; Driver Code
def findCost ( s1 , s2 , a , b , c , d , n ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( s1 [ i ] == '1' and s2 [ i ] == '2' ) or ( s2 [ i ] == '1' and s1 [ i ] == '2' ) ) : NEW_LINE INDEN...
Count the number of common divisors of the given strings | Function that returns true if sub - string s [ 0. . . k ] is repeated a number of times to generate String s ; Function to return the count of common divisors ; If the length of the sub - string divides length of both the strings ; If prefixes match in both the...
def check ( s , k ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != s [ i % k ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countCommonDivisors ( a , b ) : NEW_LINE INDENT ct = 0 NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE for i...
Level order traversal line by line | Set 3 ( Using One Queue ) | Python3 program to print levels line by line ; A Binary Tree Node ; Function to do level order traversal line by line ; Create an empty queue for level order traversal ; Pushing root node into the queue . ; Pushing delimiter into the queue . ; Condition t...
from collections import deque as queue NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def levelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DED...
Convert given string so that it holds only distinct characters | Function to return the index of the character that has 0 occurrence starting from index i ; If current character has 0 occurrence ; If no character has 0 occurrence ; Function to return the modified string which consists of distinct characters ; String ca...
def nextZero ( i , occurrences ) : NEW_LINE INDENT while i < 26 : NEW_LINE INDENT if occurrences [ i ] == 0 : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def getModifiedString ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if n > 26 : NEW_LINE INDENT return " - 1" NEW_...
Replace all occurrences of a string with space | Function to extract the secret message ; Replacing all occurrences of Sub in Str by empty spaces ; Removing unwanted spaces in the start and end of the string ; Driver code
def extractSecretMessage ( Str , Sub ) : NEW_LINE INDENT Str = Str . replace ( Sub , " ▁ " ) NEW_LINE return Str . strip ( ) NEW_LINE DEDENT Str = " LIELIEILIEAMLIECOOL " NEW_LINE Sub = " LIE " NEW_LINE print ( extractSecretMessage ( Str , Sub ) ) NEW_LINE
Sub | Function to return the count of sub - strings starting from startIndex that are also the prefixes of string ; Function to return the count of all possible sub - strings of string that are also the prefixes of string ; If current character is equal to the starting character of str ; Driver Code ; Function Call
def subStringsStartingHere ( string , n , startIndex ) : NEW_LINE INDENT count = 0 NEW_LINE i = startIndex + 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT if string . startswith ( string [ startIndex : i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT...
Binary Search a String | Returns index of x if it is present in arr [ ] , else return - 1 ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; Driver Code
def binarySearch ( arr , x ) : NEW_LINE INDENT l = 0 NEW_LINE r = len ( arr ) NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = l + ( ( r - l ) // 2 ) NEW_LINE res = ( x == arr [ m ] ) NEW_LINE if ( res == 0 ) : NEW_LINE INDENT return m - 1 NEW_LINE DEDENT if ( res > 0 ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else :...
Count characters in a string whose ASCII values are prime | Python3 implementation of above approach ; Function to find prime characters in the string ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a Boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is N...
from math import sqrt NEW_LINE max_val = 257 NEW_LINE def PrimeCharacters ( s ) : NEW_LINE INDENT prime = [ True ] * ( max_val + 1 ) NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( max_val ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i...
Length of largest subsequence consisting of a pair of alternating digits | Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of th...
def largestSubsequence ( s ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT lenn = 0 NEW_LINE prev1 = chr ( j + ord ( '0' ) ) NEW_LINE for k in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ k ] == chr ( i + ord ( '0' )...
Students with maximum average score of three subjects | Function to find the list of students having maximum average score ; Variables to store maximum average score ; List to store names of students having maximum average score ; Traversing the file data ; finding average score of a student ; Clear the list and add na...
def getStudentsList ( file ) : NEW_LINE INDENT maxAvgScore = 0 NEW_LINE names = [ ] NEW_LINE for i in range ( 0 , len ( file ) , 4 ) : NEW_LINE INDENT avgScore = ( int ( file [ i + 1 ] ) + int ( file [ i + 2 ] ) + int ( file [ i + 3 ] ) ) // 3 NEW_LINE if avgScore > maxAvgScore : NEW_LINE INDENT maxAvgScore = avgScore ...
Number of sub | Python3 program to find the number of sub - strings of s1 which are anagram of any sub - string of s2 ; This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of string pat [ ] in string txt [ ] ; countP [ ] : Store count ...
ALL_CHARS = 256 NEW_LINE def compare ( arr1 , arr2 ) : NEW_LINE INDENT for i in range ( ALL_CHARS ) : NEW_LINE INDENT if arr1 [ i ] != arr2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE...
Sum of the alphabetical values of the characters of a string | Function to find string score ; Driver code
def strScore ( str , s , n ) : NEW_LINE INDENT score = 0 NEW_LINE index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == s ) : NEW_LINE INDENT for j in range ( len ( s ) ) : NEW_LINE INDENT score += ( ord ( s [ j ] ) - ord ( ' a ' ) + 1 ) NEW_LINE DEDENT index = i + 1 NEW_LINE break NEW_LINE DEDENT...
Minimum swaps to group similar characters side by side ? | checks whether a string has similar characters side by side ; If similar chars side by side , continue ; If we have found a char equal to current char and does not exist side to it , return false ; counts min swap operations to convert a string that has similar...
from sys import maxsize NEW_LINE def sameCharAdj ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE st = set ( ) NEW_LINE st . add ( string [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if string [ i ] == string [ i - 1 ] : NEW_LINE INDENT continue NEW_LINE DEDENT if string [ i ] in st : NEW_LINE IN...
Union | Naive implementation of find ; Naive implementation of union ( )
def find ( parent , i ) : NEW_LINE INDENT if ( parent [ i ] == - 1 ) : NEW_LINE INDENT return i NEW_LINE DEDENT return find ( parent , parent [ i ] ) NEW_LINE DEDENT def Union ( parent , x , y ) : NEW_LINE INDENT xset = find ( parent , x ) NEW_LINE yset = find ( parent , y ) NEW_LINE parent [ xset ] = yset NEW_LINE DED...
Get K | Function to return the K - th letter from new String . ; finding size = length of new string S ; get the K - th letter ; Driver Code
def K_thletter ( S , K ) : NEW_LINE INDENT N = len ( S ) NEW_LINE size = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT if S [ i ] . isdigit ( ) : NEW_LINE INDENT size = size * int ( S [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT size += 1 NEW_LINE DEDENT DEDENT for i in range ( N - 1 ...
Minimum number of Parentheses to be added to make it valid | Function to return required minimum number ; maintain balance of string ; It is guaranteed bal >= - 1 ; Driver code ; Function to print required answer
def minParentheses ( p ) : NEW_LINE INDENT bal = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , len ( p ) ) : NEW_LINE INDENT if ( p [ i ] == ' ( ' ) : NEW_LINE INDENT bal += 1 NEW_LINE DEDENT else : NEW_LINE INDENT bal += - 1 NEW_LINE DEDENT if ( bal == - 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE bal += 1 NEW_LINE DED...
Check if suffix and prefix of a string are palindromes | Function to check whether the string is a palindrome ; Reverse the string and assign it to new variable for comparison ; check if both are same ; Function to check whether the string has prefix and suffix substrings of length greater than 1 which are palindromes ...
def isPalindrome ( r ) : NEW_LINE INDENT p = r [ : : - 1 ] NEW_LINE return r == p NEW_LINE DEDENT def CheckStr ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE i = 0 NEW_LINE for i in range ( 2 , l + 1 ) : NEW_LINE INDENT if isPalindrome ( s [ 0 : i ] ) == True : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if i == ( l +...
Count of ways to generate a Matrix with product of each row and column as 1 or | Function to return the number of possible ways ; Check if product can be - 1 ; driver code
def Solve ( N , M ) : NEW_LINE INDENT temp = ( N - 1 ) * ( M - 1 ) NEW_LINE ans = pow ( 2 , temp ) NEW_LINE if ( ( N + M ) % 2 != 0 ) : NEW_LINE INDENT print ( ans ) NEW_LINE else : NEW_LINE print ( 2 * ans ) NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 3 , 3 NEW_LINE Solve ( N , M ) NEW_LINE DEDE...
Rotations of a Binary String with Odd Value | function to calculate total odd equivalent ; Driver code
def oddEquivalent ( s , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "1011011" NEW_LINE n = len ( s ) NEW_LINE print ...
Minimum operation require to make first and last character same | Python3 program to find minimum operation require to make first and last character same ; Return the minimum operation require to make string first and last character same . ; Store indexes of first occurrences of characters . ; Initialize result ; Trave...
MAX = 256 NEW_LINE def minimumOperation ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE first_occ = [ - 1 ] * MAX NEW_LINE res = float ( ' inf ' ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT x = s [ i ] NEW_LINE if first_occ [ ord ( x ) ] == - 1 : NEW_LINE INDENT first_occ [ ord ( x ) ] = i NEW_LINE DEDENT else ...
Lexicographically smallest and largest substring of size k | Python 3 program to find lexicographically largest and smallest substrings of size k . ; Initialize min and max as first substring of size k ; Consider all remaining substrings . We consider every substring ending with index i . ; Print result . ; Driver Code
def getSmallestAndLargest ( s , k ) : NEW_LINE INDENT currStr = s [ : k ] NEW_LINE lexMin = currStr NEW_LINE lexMax = currStr NEW_LINE for i in range ( k , len ( s ) ) : NEW_LINE INDENT currStr = currStr [ 1 : k ] + s [ i ] NEW_LINE if ( lexMax < currStr ) : NEW_LINE INDENT lexMax = currStr NEW_LINE DEDENT if ( lexMin ...
Program to print the initials of a name with the surname | Python program to print the initials of a name with the surname ; to remove any leading or trailing spaces ; to store extracted words ; forming the word ; when space is encountered it means the name is completed and thereby extracted ; printing the first letter...
def printInitials ( string : str ) : NEW_LINE INDENT length = len ( string ) NEW_LINE string . strip ( ) NEW_LINE t = " " NEW_LINE for i in range ( length ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE if ch != ' ▁ ' : NEW_LINE INDENT t += ch NEW_LINE DEDENT else : NEW_LINE INDENT print ( t [ 0 ] . upper ( ) + " . ▁ " ...
Count of strings that can be formed from another string using each character at | Python3 program to print the number of times str2 can be formed from str1 using the characters of str1 only once ; Function to find the number of str2 that can be formed using characters of str1 ; iterate and mark the frequencies of all c...
import sys NEW_LINE def findNumberOfTimes ( str1 , str2 ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE l1 = len ( str1 ) NEW_LINE freq2 = [ 0 ] * 26 NEW_LINE l2 = len ( str2 ) NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( " a " ) ] += 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LI...
String transformation using XOR and OR | function to check if conversion is possible or not ; if lengths are different ; iterate to check if both strings have 1 ; to check if there is even one 1 in string s1 ; to check if there is even one 1 in string s2 ; if both string do not have a '1' . ; Driver code
def solve ( s1 , s2 ) : NEW_LINE INDENT flag1 = 0 NEW_LINE flag2 = 0 NEW_LINE if ( len ( s1 ) != len ( s2 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT l = len ( s1 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT if ( s1 [ i ] == '1' ) : NEW_LINE INDENT flag1 = 1 ; NEW_LINE DEDENT if ( s2 [ i ] == '1' ) : NE...
Smallest alphabet greater than a given character | Returns the smallest character from the given set of letters that is greater than K ; Take the first element as l and the rightmost element as r ; if this while condition does not satisfy simply return the first element . ; Return the smallest element ; Driver Code ; F...
def nextGreatestAlphabet ( alphabets , K ) : NEW_LINE INDENT n = len ( alphabets ) NEW_LINE if ( K >= alphabets [ n - 1 ] ) : NEW_LINE return alphabets [ 0 ] NEW_LINE l = 0 NEW_LINE r = len ( alphabets ) - 1 NEW_LINE ans = - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = int ( ( l + r ) / 2 ) NEW_LINE if ( alphabe...
Longest substring of 0 s in a string formed by k concatenations | Function to calculate maximum length of substring containing only zero ; loop to calculate longest substring in string containing 0 's ; if all elements in string a are '0 ; Else , find prefix and suffix containing only zeroes ; Calculate length of the p...
def subzero ( str , k ) : NEW_LINE INDENT ans = 0 NEW_LINE curr = 0 NEW_LINE n = len ( str ) NEW_LINE for i in str : NEW_LINE INDENT if ( i == '0' ) : NEW_LINE INDENT curr += 1 NEW_LINE DEDENT else : NEW_LINE INDENT curr = 0 NEW_LINE DEDENT ans = max ( ans , curr ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( ans == n...
Find the largest number smaller than integer N with maximum number of set bits | Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code
def largestNum ( n ) : NEW_LINE INDENT num = 0 ; NEW_LINE max_setBits = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT setBits = bin ( i ) . count ( '1' ) ; NEW_LINE if ( setBits >= max_setBits ) : NEW_LINE INDENT num = i ; NEW_LINE max_setBits = setBits ; NEW_LINE DEDENT DEDENT return num ; NEW_LINE DEDENT if...
Number of substrings of a string | Python3 program to count number of substrings of a string ; driver code
def countNonEmptySubstr ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE return int ( n * ( n + 1 ) / 2 ) ; NEW_LINE DEDENT s = " abcde " ; NEW_LINE print ( countNonEmptySubstr ( s ) ) ; NEW_LINE
Count substrings with each character occurring at most k times | Python 3 program to count number of substrings in which each character has count less than or equal to k . ; variable to store count of substrings . ; array to store count of each character . ; increment character count ; check only the count of current c...
def findSubstrings ( s , k ) : NEW_LINE INDENT ans = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT cnt [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( cnt [ ord ( s [ j ] ) - ord ( ' a ' ) ] <= k ) : NEW_LINE INDENT a...
Check if characters of one string can be swapped to form other | Python3 program to check if characters of one string can be swapped to form other ; if length is not same print no ; Count frequencies of character in first string . ; iterate through the second string decrement counts of characters in second string ; Sin...
MAX = 26 NEW_LINE def targetstring ( str1 , str2 ) : NEW_LINE INDENT l1 = len ( str1 ) NEW_LINE l2 = len ( str2 ) NEW_LINE if ( l1 != l2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT map = [ 0 ] * MAX NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT map [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for...
Find the Number which contain the digit d | Returns true if d is present as digit in number x . ; Breal loop if d is present as digit ; If loop broke ; function to display the values ; Check all numbers one by one ; checking for digit ; Driver code
def isDigitPresent ( x , d ) : NEW_LINE INDENT while ( x > 0 ) : NEW_LINE INDENT if ( x % 10 == d ) : NEW_LINE INDENT break NEW_LINE DEDENT x = x / 10 NEW_LINE DEDENT return ( x > 0 ) NEW_LINE DEDENT def printNumbers ( n , d ) : NEW_LINE INDENT for i in range ( 0 , n + 1 ) : NEW_LINE INDENT if ( i == d or isDigitPresen...
Find one extra character in a string | Python3 program to find extra character in one string ; store string values in map ; store second string in map with frequency ; store first string in map with frequency ; if the frequency is 1 then this character is which is added extra ; Driver Code ; given string ; find Extra C...
def findExtraCharacter ( strA , strB ) : NEW_LINE INDENT m1 = { } NEW_LINE for i in strB : NEW_LINE INDENT if i in m1 : NEW_LINE INDENT m1 [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m1 [ i ] = 1 NEW_LINE DEDENT DEDENT for i in strA : NEW_LINE INDENT m1 [ i ] -= 1 NEW_LINE DEDENT for h1 in m1 : NEW_LINE INDENT if...
Find one extra character in a string | Python 3 program to find extra character in one string ; result store the result ; traverse string A till end and xor with res ; xor with res ; traverse string B till end and xor with res ; xor with res ; print result at the end ; given string
def findExtraCharcter ( strA , strB ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , len ( strA ) ) : NEW_LINE INDENT res = res ^ ( ord ) ( strA [ i ] ) NEW_LINE DEDENT for i in range ( 0 , len ( strB ) ) : NEW_LINE INDENT res = res ^ ( ord ) ( strB [ i ] ) NEW_LINE DEDENT return ( ( chr ) ( res ) ) ; NEW_LINE...
Find one extra character in a string | Python Program to find extra character in one string ; Determine string with extra character ; Add Character codes of both the strings ; Add last character code of large string ; Minus the character code of smaller string from the character code of large string The result will be ...
def findExtraCharacter ( s1 , s2 ) : NEW_LINE INDENT smallStr = " " NEW_LINE largeStr = " " NEW_LINE if ( len ( s1 ) > len ( s2 ) ) : NEW_LINE INDENT smallStr = s2 NEW_LINE largeStr = s1 NEW_LINE DEDENT else : NEW_LINE INDENT smallStr = s1 NEW_LINE largeStr = s2 NEW_LINE DEDENT smallStrCodeTotal = 0 NEW_LINE largeStrCo...
Function to copy string ( Iterative and Recursive ) | Function to copy one string to other ; Driver code
def copy_str ( x , y ) : NEW_LINE INDENT if len ( y ) == 0 : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT c = copy_str ( x , ( y ) [ 1 : - 1 ] ) NEW_LINE return c NEW_LINE DEDENT DEDENT x = input ( ) NEW_LINE y = input ( ) NEW_LINE print ( copy_str ( x , y ) ) NEW_LINE
Evaluate an array expression with numbers , + and | Function to find the sum of given array ; if string is empty ; stoi function to convert string into integer ; stoi function to convert string into integer ; Find operator ; If operator is equal to ' + ' , add value in sum variable else subtract ; Driver Function
def calculateSum ( arr , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT s = arr [ 0 ] NEW_LINE value = int ( s ) NEW_LINE sum = value NEW_LINE for i in range ( 2 , n , 2 ) : NEW_LINE INDENT s = arr [ i ] NEW_LINE value = int ( s ) NEW_LINE operation = arr [ i - 1 ] [ 0 ] NEW_LINE if ( op...
String with maximum number of unique characters | Function to find string with maximum number of unique characters . ; Index of string with maximum unique characters ; Iterate through all strings ; Array indicating any alphabet included or not included ; count number of unique alphabets in each string ; keep track of m...
def LargestString ( na ) : NEW_LINE INDENT N = len ( na ) NEW_LINE c = [ 0 ] * N NEW_LINE m = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT character = [ False ] * 26 NEW_LINE for k in range ( len ( na [ j ] ) ) : NEW_LINE INDENT x = ord ( na [ j ] [ k ] ) - ord ( ' A ' ) NEW_LINE if ( ( na [ j ] [ k ] != ' ▁ ' ) a...
Program for length of the longest word in a sentence | Python program to find the number of characters in the longest word in the sentence . ; Driver Code
def longestWordLength ( string ) : NEW_LINE INDENT length = 0 NEW_LINE for word in string . split ( ) : NEW_LINE INDENT if ( len ( word ) > length ) : NEW_LINE INDENT length = len ( word ) NEW_LINE DEDENT DEDENT return length NEW_LINE DEDENT string = " I ▁ am ▁ an ▁ intern ▁ at ▁ geeksforgeeks " NEW_LINE print ( longes...
Morse Code Implementation | function to encode a alphabet as Morse code ; refer to the Morse table image attached in the article ; for space ; character by character print Morse code ; Driver Code
def morseEncode ( x ) : NEW_LINE INDENT if x is ' a ' : NEW_LINE INDENT return " . - " NEW_LINE DEDENT elif x is ' b ' : NEW_LINE INDENT return " - . . . " NEW_LINE DEDENT elif x is ' c ' : NEW_LINE INDENT return " - . - . " NEW_LINE DEDENT elif x is ' d ' : NEW_LINE INDENT return " - . . " NEW_LINE DEDENT elif x is ' ...
Polybius Square Cipher | function to display polybius cipher text ; convert each character to its encrypted code ; finding row of the table ; finding column of the table ; if character is 'k ; if character is greater than 'j ; Driver 's Code ; print the cipher of " geeksforgeeks "
def polybiusCipher ( s ) : NEW_LINE INDENT for char in s : NEW_LINE INDENT row = int ( ( ord ( char ) - ord ( ' a ' ) ) / 5 ) + 1 NEW_LINE col = ( ( ord ( char ) - ord ( ' a ' ) ) % 5 ) + 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if char == ' k ' : NEW_LINE INDENT row = row - 1 NEW_LINE col = 5 - col + 1 NEW_LINE DEDE...
Minimum removal to make palindrome permutation | function to find minimum removal of characters ; hash to store frequency of each character to set hash array to zeros ; count frequency of each character ; count the odd frequency characters ; if count is 0 , return 0 otherwise return count ; Driver 's Code
def minRemoval ( strr ) : NEW_LINE INDENT hash = [ 0 ] * 26 NEW_LINE for char in strr : NEW_LINE INDENT hash [ ord ( char ) - ord ( ' a ' ) ] = hash [ ord ( char ) - ord ( ' a ' ) ] + 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if hash [ i ] % 2 : NEW_LINE INDENT count = count + 1 NEW_L...
Union | Python3 program to implement Union - Find with union by rank and path compression . ; Arr to represent parent of index i ; Size to represent the number of nodes in subgxrph rooted at index i ; set parent of every node to itself and size of node to one ; Each time we follow a path , find function compresses it f...
MAX_VERTEX = 101 NEW_LINE Arr = [ None ] * MAX_VERTEX NEW_LINE size = [ None ] * MAX_VERTEX NEW_LINE def initialize ( n ) : NEW_LINE INDENT global Arr , size NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT Arr [ i ] = i NEW_LINE size [ i ] = 1 NEW_LINE DEDENT DEDENT def find ( i ) : NEW_LINE INDENT global Arr , siz...
Queries for frequencies of characters in substrings | Python3 program to find occurrence of character in substring l to r ; To store count of all character ; To pre - process string from 0 to size of string ; Store occurrence of character i ; Store occurrence o all character upto i ; To return occurrence of character i...
MAX_LEN , MAX_CHAR = 1005 , 26 NEW_LINE cnt = [ [ 0 for i in range ( MAX_CHAR ) ] for j in range ( MAX_LEN ) ] NEW_LINE def preProcess ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cnt [ i ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : N...
Longest Uncommon Subsequence | Python program to find longest uncommon subsequence using naive method ; function to calculate length of longest uncommon subsequence ; Case 1 : If strings are equal ; for case 2 and case 3 ; input strings
import math NEW_LINE def findLUSlength ( a , b ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max ( len ( a ) , len ( b ) ) NEW_LINE DEDENT a = " abcdabcd " NEW_LINE b = " abcabc " NEW_LINE print ( findLUSlength ( a , b ) ) NEW_LINE
Interchanging first and second halves of strings | Function to concatenate two different halves of given strings ; Creating new strings by exchanging the first half of a and b . Please refer below for details of substr . https : www . geeksforgeeks . org / stdsubstr - in - ccpp / ; Driver function ;
def swapTwoHalves ( a , b ) : NEW_LINE INDENT la = len ( a ) NEW_LINE lb = len ( b ) NEW_LINE c = a [ 0 : la // 2 ] + b [ lb // 2 : lb ] NEW_LINE d = b [ 0 : lb // 2 ] + a [ la // 2 : la ] NEW_LINE print ( c , " " , d ) NEW_LINE DEDENT a = " remuneration " NEW_LINE b = " day " NEW_LINE / * Calling function * / NEW_LI...
Magical Indices in an array | Function to count number of magical indices . ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Initialize the arrays . ; Check if current node is already traversed or not . If node is not traversed yet then parent val...
def solve ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE parent = [ None ] * ( n + 1 ) NEW_LINE vis = [ None ] * ( n + 1 ) NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT parent [ i ] = - 1 NEW_LINE vis [ i ] = 0 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT j = i NEW_LINE if ( parent [ j ] == - 1 ) ...
Longest path between any pair of vertices | visited [ ] array to make nodes visited src is starting node for DFS traversal prev_len is sum of cable length till current node max_len is pointer which stores the maximum length of cable value after DFS traversal ; Mark the src node visited ; curr_len is for length of cable...
def DFS ( graph , src , prev_len , max_len , visited ) : NEW_LINE INDENT visited [ src ] = 1 NEW_LINE curr_len = 0 NEW_LINE adjacent = None NEW_LINE for i in range ( len ( graph [ src ] ) ) : NEW_LINE INDENT adjacent = graph [ src ] [ i ] NEW_LINE if ( not visited [ adjacent [ 0 ] ] ) : NEW_LINE INDENT curr_len = prev_...
Level order traversal with direction change after every two levels | A Binary Tree Node ; Function to prthe level order of given binary tree . Direction of printing level order traversal of binary tree changes after every two levels ; For null root ; Maintain a queue for normal level order traversal ; Maintain a stack ...
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def modifiedLevelOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT i...
Minimum cost to connect all cities | Function to find out minimum valued node among the nodes which are not yet included in MST ; Loop through all the values of the nodes which are not yet included in MST and find the minimum valued one . ; Function to find out the MST and the cost of the MST . ; Array to store the par...
def minnode ( n , keyval , mstset ) : NEW_LINE INDENT mini = 999999999999 NEW_LINE mini_index = None NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( mstset [ i ] == False and keyval [ i ] < mini ) : NEW_LINE INDENT mini = keyval [ i ] NEW_LINE mini_index = i NEW_LINE DEDENT DEDENT return mini_index NEW_LINE DEDENT...
Minimum Product Spanning Tree | A Python3 program for getting minimum product spanning tree The program is for adjacency matrix representation of the graph ; Number of vertices in the graph ; A utility function to find the vertex with minimum key value , from the set of vertices not yet included in MST ; Initialize min...
import math NEW_LINE V = 5 NEW_LINE def minKey ( key , mstSet ) : NEW_LINE INDENT min = 10000000 NEW_LINE min_index = 0 NEW_LINE for v in range ( V ) : NEW_LINE INDENT if ( mstSet [ v ] == False and key [ v ] < min ) : NEW_LINE INDENT min = key [ v ] NEW_LINE min_index = v NEW_LINE DEDENT DEDENT return min_index NEW_LI...
Insertion in a Binary Tree in level order | A binary tree node has key , pointer to left child and a pointer to right child ; Inorder traversal of a binary tree ; function to insert element in binary tree ; Do level order traversal until we find an empty place . ; Driver code
class newNode ( ) : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( temp ) : NEW_LINE INDENT if ( not temp ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( temp . left ) NEW_LINE print ( te...
Tug of War | function that tries every possible solution by calling itself recursively ; checks whether the it is going out of bound ; checks that the numbers of elements left are not less than the number of elements required to form the solution ; consider the cases when current element is not included in the solution...
def TOWUtil ( arr , n , curr_elements , no_of_selected_elements , soln , min_diff , Sum , curr_sum , curr_position ) : NEW_LINE INDENT if ( curr_position == n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ( int ( n / 2 ) - no_of_selected_elements ) > ( n - curr_position ) ) : NEW_LINE INDENT return NEW_LINE DEDENT TO...
The Knight 's tour problem | Backtracking | Python3 program to solve Knight Tour problem using Backtracking Chessboard Size ; A utility function to check if i , j are valid indexes for N * N chessboard ; A utility function to print Chessboard matrix ; This function solves the Knight Tour problem using Backtracking . Th...
n = 8 NEW_LINE def isSafe ( x , y , board ) : NEW_LINE INDENT if ( x >= 0 and y >= 0 and x < n and y < n and board [ x ] [ y ] == - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def printSolution ( n , board ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n )...
Rat in a Maze | Backtracking | Maze size ; A utility function to print solution matrix sol ; A utility function to check if x , y is valid index for N * N Maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It...
N = 4 NEW_LINE def printSolution ( sol ) : NEW_LINE INDENT for i in sol : NEW_LINE INDENT for j in i : NEW_LINE INDENT print ( str ( j ) + " ▁ " , end = " " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT DEDENT def isSafe ( maze , x , y ) : NEW_LINE INDENT if x >= 0 and x < N and y >= 0 and y < N and maze [ x ] [ y ] ...
m Coloring Problem | Backtracking | A utility function to prsolution ; check if the colored graph is safe or not ; check for every edge ; This function solves the m Coloring problem using recursion . It returns false if the m colours cannot be assigned , otherwise , return true and prints assignments of colours to all ...
def printSolution ( color ) : NEW_LINE INDENT print ( " Solution ▁ Exists : " " ▁ Following ▁ are ▁ the ▁ assigned ▁ colors ▁ " ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT print ( color [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def isSafe ( graph , color ) : NEW_LINE INDENT for i in range ( 4 ) : NEW_LINE INDE...
m Coloring Problem | Backtracking | Python3 program for the above approach ; A node class which stores the color and the edges connected to the node ; Create a visited array of n nodes , initialized to zero ; maxColors used till now are 1 as all nodes are painted color 1 ; Do a full BFS traversal from all unvisited sta...
from queue import Queue NEW_LINE class node : NEW_LINE INDENT color = 1 NEW_LINE edges = set ( ) NEW_LINE DEDENT def canPaint ( nodes , n , m ) : NEW_LINE INDENT visited = [ 0 for _ in range ( n + 1 ) ] NEW_LINE maxColors = 1 NEW_LINE for _ in range ( 1 , n + 1 ) : NEW_LINE INDENT if visited [ _ ] : NEW_LINE INDENT con...
Maximize pair decrements required to reduce all array elements except one to 0 | Function to count maximum number of steps to make ( N - 1 ) array elements to 0 ; Stores maximum count of steps to make ( N - 1 ) elements equal to 0 ; Stores array elements ; Traverse the array ; Insert arr [ i ] into PQ ; Extract top 2 e...
def cntMaxOperationToMakeN_1_0 ( arr , N ) : NEW_LINE INDENT cntOp = 0 NEW_LINE PQ = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT PQ . append ( arr [ i ] ) NEW_LINE DEDENT PQ = sorted ( PQ ) NEW_LINE while ( len ( PQ ) > 1 ) : NEW_LINE INDENT X = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE Y = PQ [ - 1 ] NEW_LIN...
Flip all K | Function to flip all K - bits of an unsigned number N ; Stores ( 2 ^ K ) - 1 ; Update N ; Print the answer ; Driver Code
def flippingBits ( N , K ) : NEW_LINE INDENT X = ( 1 << ( K - 1 ) ) - 1 NEW_LINE N = X - N NEW_LINE print ( N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K = 1 , 8 NEW_LINE flippingBits ( N , K ) NEW_LINE DEDENT
Generate a matrix having even sum of all diagonals in each 2 x 2 submatrices | Function to construct a matrix such that the sum elements in both diagonals of every 2 * 2 matrices is even ; Stores odd numbers ; Stores even numbers ; Store matrix elements such that sum of elements in both diagonals of every 2 * 2 submatr...
def generateMatrix ( N ) : NEW_LINE INDENT odd = 1 ; NEW_LINE even = 2 ; NEW_LINE mat = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( ( i + j ) % 2 == 0 ) : NEW_LINE INDENT mat [ i ] [ j ] = odd ;...
Queries to calculate sum by alternating signs of array elements in a given range | Function to build the segment tree ; If current node is a leaf node of the segment tree ; Update tree [ index ] ; Update tree [ index ] ; Divide the segment tree ; Update on L segment tree ; Update on R segment tree ; Find the sum from L...
def build ( tree , arr , start , end , index ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT if ( start % 2 == 0 ) : NEW_LINE INDENT tree [ index ] = arr [ start ] NEW_LINE DEDENT else : NEW_LINE INDENT tree [ index ] = - arr [ start ] NEW_LINE DEDENT return NEW_LINE DEDENT mid = start + ( end - start ) // 2 ...
Split an array into minimum number of non | Function to split the array into minimum count of subarrays such that each subarray is either non - increasing or non - decreasing ; Initialize variable to keep track of current sequence ; Stores the required result ; Traverse the array , arr [ ] ; If current sequence is neit...
def minimumSubarrays ( arr , n ) : NEW_LINE INDENT current = ' N ' NEW_LINE answer = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( current == ' N ' ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT current = ' D ' NEW_LINE DEDENT elif ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT cu...
Convert a Matrix into another Matrix of given dimensions | Function to construct a matrix of size A * B from the given matrix elements ; Initialize a new matrix ; Traverse the matrix , mat [ ] [ ] ; Update idx ; Print the resultant matrix ; Driver Code
def ConstMatrix ( mat , N , M , A , B ) : NEW_LINE INDENT if ( N * M != A * B ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT idx = 0 ; NEW_LINE res = [ [ 0 for i in range ( B ) ] for i in range ( A ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT res [ idx // B ] [ idx % B ] = ...
Modify given array by reducing each element by its next smaller element | Function to print the final array after reducing each array element by its next smaller element ; Initialize stack ; To store the corresponding element ; If stack is not empty ; If top element is smaller than the current element ; Keep popping un...
def printFinalPrices ( arr ) : NEW_LINE INDENT minStk = [ ] NEW_LINE reduce = [ 0 ] * len ( arr ) NEW_LINE for i in range ( len ( arr ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if minStk : NEW_LINE INDENT if minStk [ - 1 ] <= arr [ i ] : NEW_LINE INDENT reduce [ i ] = minStk [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT wh...
Generate array having differences between count of occurrences of every array element on its left and right | Function to construct array of differences of counts on the left and right of the given array ; Initialize left and right frequency arrays ; Construct left cumulative frequency table ; Construct right cumulativ...
def constructArray ( A , N ) : NEW_LINE INDENT left = [ 0 ] * ( N + 1 ) NEW_LINE right = [ 0 ] * ( N + 1 ) NEW_LINE X = [ 0 ] * ( N + 1 ) NEW_LINE Y = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT X [ i ] = left [ A [ i ] ] NEW_LINE left [ A [ i ] ] += 1 NEW_LINE DEDENT for i in range ( N - 1 , ...
Mean of distinct odd fibonacci nodes in a Linked List | Structure of a singly Linked List ; Stores data value of a Node ; Stores pointer to next Node ; Function to add a node at the beginning of the singly Linked List ; Create a new Node ; Insert the data into the Node ; Insert pointer to the next Node ; Update head_re...
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data ; NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node ; NEW_LINE...
Generate an alternate odd | Function to prthe required sequence ; Print ith odd number ; Driver Code
def findNumbers ( n ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i <= n ) : NEW_LINE INDENT print ( 2 * i * i + 4 * i + 1 + i % 2 , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT n = 6 NEW_LINE findNumbers ( n ) NEW_LINE
Program to calculate gross salary of a person | Function to calculate the salary of the person ; Condition to compute the allowance for the person ; Calculate gross salary ; Driver code ; Function call
def computeSalary ( basic , grade ) : NEW_LINE INDENT hra = 0.2 * basic NEW_LINE da = 0.5 * basic NEW_LINE pf = 0.11 * basic NEW_LINE if grade == ' A ' : NEW_LINE INDENT allowance = 1700.0 NEW_LINE DEDENT elif grade == ' B ' : NEW_LINE INDENT allowance = 1500.0 NEW_LINE DEDENT else : NEW_LINE INDENT allowance = 1300.0 ...
Rearrange and update array elements as specified by the given queries | Python3 program to implement the above approach ; Function to perform the given operations ; Dequeue to store the array elements ; Insert all element of the array into the dequeue ; Stores the size of the queue ; Traverse each query ; Query for lef...
from collections import deque NEW_LINE def Queries ( arr , N , Q ) : NEW_LINE INDENT dq = deque ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT dq . append ( arr [ i ] ) NEW_LINE DEDENT sz = len ( Q ) NEW_LINE for i in range ( sz ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT front = dq [ 0 ] NEW_L...
Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal | Python3 program to implement the above approach ; Function ot find the length of the smallest subarray ; Stores ( prefix Sum , index ) as ( key , value ) mappings ; Iterate till N ; Update the prefixSum ; Update t...
import sys NEW_LINE def smallSubarray ( arr , n , total_sum ) : NEW_LINE INDENT m = { } NEW_LINE length = sys . maxsize NEW_LINE prefixSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefixSum += arr [ i ] NEW_LINE if ( prefixSum == total_sum ) : NEW_LINE INDENT length = min ( length , i + 1 ) NEW_LINE DEDENT m...
Balanced Ternary Number System | Python3 program to convert positive decimals into balanced ternary system ; Driver Code
def balancedTernary ( n ) : NEW_LINE INDENT output = " " NEW_LINE while ( n > 0 ) : NEW_LINE INDENT rem = n % 3 NEW_LINE n = n // 3 NEW_LINE if ( rem == 2 ) : NEW_LINE INDENT rem = - 1 NEW_LINE n += 1 NEW_LINE DEDENT if ( rem == 0 ) : NEW_LINE INDENT output = '0' + output NEW_LINE DEDENT else : NEW_LINE INDENT if ( rem...
Spt function or Smallest Parts Function of a given number | Python3 implementation to find the Spt Function to given number ; Variable to store spt function of a number ; Function to add value of frequency of minimum element among all representations of n ; Find the value of frequency of minimum element ; Calculate spt...
import sys NEW_LINE spt = 0 NEW_LINE def printVector ( arr ) : NEW_LINE INDENT global spt NEW_LINE min_i = sys . maxsize NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT min_i = min ( min_i , arr [ i ] ) NEW_LINE DEDENT freq = arr . count ( min_i ) NEW_LINE spt += freq NEW_LINE DEDENT def findWays ( arr , i , ...
Find initial integral solution of Linear Diophantine equation if finite solution exists | Python3 program for the above approach ; Function to implement the extended euclid algorithm ; Base Case ; Recursively find the gcd ; Function to prlet the solutions of the given equations ax + by = c ; Condition for infinite solu...
import math NEW_LINE x , y = 0 , 0 NEW_LINE def gcd_extend ( a , b ) : NEW_LINE INDENT global x , y NEW_LINE if ( b == 0 ) : NEW_LINE INDENT x = 1 NEW_LINE y = 0 NEW_LINE return a NEW_LINE DEDENT else : NEW_LINE INDENT g = gcd_extend ( b , a % b ) NEW_LINE x1 , y1 = x , y NEW_LINE x = y1 NEW_LINE y = x1 - math . floor ...
Count of pairs whose bitwise AND is a power of 2 | Function to check if x is power of 2 ; Returns true if x is a power of 2 ; Function to return the number of valid pairs ; Iterate for all possible pairs ; Bitwise and value of the pair is passed ; Return the final count ; ; Given array ; Function Call
def check ( x ) : NEW_LINE INDENT return x and ( not ( x & ( x - 1 ) ) ) NEW_LINE DEDENT def count ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if check ( arr [ i ] & arr [ j ] ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT D...
Check if the Matrix follows the given constraints or not | Python3 implementation of the above approach ; Function checks if n is prime or not ; Corner case ; Check from 2 to sqrt ( n ) ; Function returns sum of all elements of matrix ; Stores the sum of the matrix ; Function to check if all a [ i ] [ j ] with prime ( ...
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def takeSum ( a , n , m ) : NEW...
Count of all possible pairs of array elements with same parity | Function to return the answer ; Generate all possible pairs ; Increment the count if both even or both odd ; Driver Code
def countPairs ( A , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 0 and A [ j ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ j ] % 2 != 0 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LI...