text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Count pairs with given sum | Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to sum ; Initialize result ; Consider all possible pairs and check their sums ; Driver function | def getPairsCount ( arr , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ i ] + arr [ j ] == sum : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 5 , 7 , - 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE print ( " Count β of β pairs β is " , getPairsCount ( arr , n , sum ) ) NEW_LINE |
Check whether a binary tree is a full binary tree or not | Iterative Approach | node class ; put in the data ; function to check whether a binary tree is a full binary tree or not ; if tree is empty ; queue used for level order traversal ; append ' root ' to ' q ' ; traverse all the nodes of the binary tree level by level until queue is empty ; get the pointer to ' node ' at front of queue ; if it is a leaf node then continue ; if either of the child is not None and the other one is None , then binary tree is not a full binary tee ; append left and right childs of ' node ' on to the queue ' q ' ; binary tree is a full binary tee ; Driver Code | class getNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isFullBinaryTree ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return True NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( not len ( q ) ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( node . left == None and node . right == None ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( node . left == None or node . right == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT q . append ( node . left ) NEW_LINE q . append ( node . right ) NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 1 ) NEW_LINE root . left = getNode ( 2 ) NEW_LINE root . right = getNode ( 3 ) NEW_LINE root . left . left = getNode ( 4 ) NEW_LINE root . left . right = getNode ( 5 ) NEW_LINE if ( isFullBinaryTree ( root ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Analysis of Algorithms | Big | ''Function to find whether a key exists in an array or not using linear search ; '' Traverse the given array, a[] ; '' Check if a[i] is equal to key ; ''Given Input ; ''Function Call | def linearSearch ( a , n , key ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] == key ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT arr = 2 , 3 , 4 , 10 , 40 NEW_LINE x = 10 NEW_LINE n = len ( arr ) NEW_LINE if ( linearSearch ( arr , n , x ) ) : NEW_LINE INDENT print ( " Element β is β present β in β array " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β is β not β present β in β array " ) NEW_LINE DEDENT |
Count pairs with given sum | Python 3 implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to 'sum ; Store counts of all elements in map m ; initializing value to 0 , if key not found ; Iterate through each element and increment the count ( Notice that every pair is counted twice ) ; if ( arr [ i ] , arr [ i ] ) pair satisfies the condition , then we need to ensure that the count is decreased by one such that the ( arr [ i ] , arr [ i ] ) pair is not considered ; return the half of twice_count ; Driver function | import sys NEW_LINE def getPairsCount ( arr , n , sum ) : NEW_LINE INDENT m = [ 0 ] * 1000 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT twice_count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT twice_count += m [ sum - arr [ i ] ] NEW_LINE if ( sum - arr [ i ] == arr [ i ] ) : NEW_LINE INDENT twice_count -= 1 NEW_LINE DEDENT DEDENT return int ( twice_count / 2 ) NEW_LINE DEDENT arr = [ 1 , 5 , 7 , - 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE print ( " Count β of β pairs β is " , getPairsCount ( arr , n , sum ) ) NEW_LINE |
Count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; generating pairs from both the arrays ; if sum of pair is equal to ' x ' increment count ; required count of pairs ; Driver Program | def countPairs ( arr1 , arr2 , m , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if arr1 [ i ] + arr2 [ j ] == x : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr1 = [ 1 , 3 , 5 , 7 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 8 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE x = 10 NEW_LINE print ( " Count β = β " , countPairs ( arr1 , arr2 , m , n , x ) ) NEW_LINE |
Count pairs from two sorted arrays whose sum is equal to a given value x | function to search ' value ' in the given array ' arr [ ] ' it uses binary search technique as ' arr [ ] ' is sorted ; value found ; value not found ; function to count all pairs from both the sorted arrays whose sum is equal to a given value ; for each arr1 [ i ] ; check if the ' value ' is present in 'arr2[] ; required count of pairs ; Driver Code | def isPresent ( arr , low , high , value ) : NEW_LINE INDENT while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( arr [ mid ] == value ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( arr [ mid ] > value ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def countPairs ( arr1 , arr2 , m , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT value = x - arr1 [ i ] NEW_LINE if ( isPresent ( arr2 , 0 , n - 1 , value ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 1 , 3 , 5 , 7 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 8 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE x = 10 NEW_LINE print ( " Count β = β " , countPairs ( arr1 , arr2 , m , n , x ) ) NEW_LINE DEDENT |
Count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; insert all the elements of 1 st array in the hash table ( unordered_set ' us ' ) ; or each element of 'arr2[] ; find ( x - arr2 [ j ] ) in 'us ; required count of pairs ; Driver code | def countPairs ( arr1 , arr2 , m , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE us = set ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT us . add ( arr1 [ i ] ) NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT if x - arr2 [ j ] in us : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr1 = [ 1 , 3 , 5 , 7 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 8 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE x = 10 NEW_LINE print ( " Count β = " , countPairs ( arr1 , arr2 , m , n , x ) ) NEW_LINE |
Count pairs from two sorted arrays whose sum is equal to a given value x | function to count all pairs from both the sorted arrays whose sum is equal to a given value ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if this sum is equal to ' x ' , then increment ' l ' , decrement ' r ' and increment 'count ; if this sum is less than x , then increment l ; else decrement 'r ; required count of pairs ; Driver Code | def countPairs ( arr1 , arr2 , m , n , x ) : NEW_LINE INDENT count , l , r = 0 , 0 , n - 1 NEW_LINE while ( l < m and r >= 0 ) : NEW_LINE INDENT if ( ( arr1 [ l ] + arr2 [ r ] ) == x ) : NEW_LINE INDENT l += 1 NEW_LINE r -= 1 NEW_LINE count += 1 NEW_LINE DEDENT elif ( ( arr1 [ l ] + arr2 [ r ] ) < x ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 3 , 5 , 7 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 8 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE x = 10 NEW_LINE print ( " Count β = " , countPairs ( arr1 , arr2 , m , n , x ) ) NEW_LINE DEDENT |
Count pairs from two linked lists whose sum is equal to a given value | A Linked list node ; function to count all pairs from both the linked lists whose sum is equal to a given value ; traverse the 1 st linked list ; for each node of 1 st list traverse the 2 nd list ; if sum of pair is equal to ' x ' increment count ; required count of pairs ; Driver program to test above | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def countPairs ( head1 , head2 , x ) : NEW_LINE INDENT count = 0 NEW_LINE p1 = head1 NEW_LINE while ( p1 != None ) : NEW_LINE INDENT p2 = head2 NEW_LINE while ( p2 != None ) : NEW_LINE INDENT if ( ( p1 . data + p2 . data ) == x ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT p2 = p2 . next NEW_LINE DEDENT p1 = p1 . next NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = None NEW_LINE head2 = None NEW_LINE head1 = push ( head1 , 7 ) NEW_LINE head1 = push ( head1 , 5 ) NEW_LINE head1 = push ( head1 , 1 ) NEW_LINE head1 = push ( head1 , 3 ) NEW_LINE head2 = push ( head2 , 3 ) NEW_LINE head2 = push ( head2 , 5 ) NEW_LINE head2 = push ( head2 , 2 ) NEW_LINE head2 = push ( head2 , 8 ) NEW_LINE x = 10 NEW_LINE print ( " Count β = β " , countPairs ( head1 , head2 , x ) ) NEW_LINE DEDENT |
Count quadruples from four sorted arrays whose sum is equal to a given value x | count pairs from the two sorted array whose sum is equal to the given ' value ' ; traverse ' arr1 [ ] ' from left to right traverse ' arr2 [ ] ' from right to left ; if the ' sum ' is equal to ' value ' , then increment ' l ' , decrement ' r ' and increment ' count ' ; if the ' sum ' is greater than ' value ' , then decrement r ; else increment l ; required count of pairs print ( count ) ; function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; generate all pairs from arr1 [ ] and arr2 [ ] ; calculate the sum of elements in the pair so generated ; count pairs in the 3 rd and 4 th array having value ' x - p _ sum ' and then accumulate it to ' count ' ; required count of quadruples ; four sorted arrays each of size ' n ' | def countPairs ( arr1 , arr2 , n , value ) : NEW_LINE INDENT count = 0 NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l < n and r >= 0 ) : NEW_LINE INDENT sum = arr1 [ l ] + arr2 [ r ] NEW_LINE if ( sum == value ) : NEW_LINE INDENT l += 1 NEW_LINE r -= 1 NEW_LINE count += 1 NEW_LINE DEDENT elif ( sum > value ) : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT p_sum = arr1 [ i ] + arr2 [ j ] NEW_LINE count += int ( countPairs ( arr3 , arr4 , n , x - p_sum ) ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr1 = [ 1 , 4 , 5 , 6 ] NEW_LINE arr2 = [ 2 , 3 , 7 , 8 ] NEW_LINE arr3 = [ 1 , 4 , 6 , 10 ] NEW_LINE arr4 = [ 2 , 4 , 7 , 8 ] NEW_LINE n = len ( arr1 ) NEW_LINE x = 30 NEW_LINE print ( " Count β = β " , countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ) NEW_LINE |
Count quadruples from four sorted arrays whose sum is equal to a given value x | function to count all quadruples from four sorted arrays whose sum is equal to a given value x ; unordered_map ' um ' implemented as hash table for < sum , frequency > tuples ; count frequency of each sum obtained from the pairs of arr1 [ ] and arr2 [ ] and store them in 'um ; generate pair from arr3 [ ] and arr4 [ ] ; calculate the sum of elements in the pair so generated ; if ' x - p _ sum ' is present in ' um ' then add frequency of ' x - p _ sum ' to ' count ' ; required count of quadruples ; four sorted arrays each of size n | def countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( arr1 [ i ] + arr2 [ j ] ) in m : NEW_LINE INDENT m [ arr1 [ i ] + arr2 [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr1 [ i ] + arr2 [ j ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT for k in range ( n ) : NEW_LINE INDENT for l in range ( n ) : NEW_LINE INDENT p_sum = arr3 [ k ] + arr4 [ l ] NEW_LINE if ( x - p_sum ) in m : NEW_LINE INDENT count += m [ x - p_sum ] NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr1 = [ 1 , 4 , 5 , 6 ] NEW_LINE arr2 = [ 2 , 3 , 7 , 8 ] NEW_LINE arr3 = [ 1 , 4 , 6 , 10 ] NEW_LINE arr4 = [ 2 , 4 , 7 , 8 ] NEW_LINE n = len ( arr1 ) NEW_LINE x = 30 NEW_LINE print ( " Count β = " , countQuadruples ( arr1 , arr2 , arr3 , arr4 , n , x ) ) NEW_LINE |
How to learn Pattern printing easily ? | Driver code | if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE print ( " Value β of β N : β " , N ) ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT min = i if i < j else j ; NEW_LINE print ( N - min + 1 , end = " " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT |
Number of subarrays having sum exactly equal to k | Python3 program for the above approach ; Calculate all subarrays ; Calculate required sum ; Check if sum is equal to required sum | arr = [ 10 , 2 , - 2 , - 20 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE k = - 10 NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT summ = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT summ += arr [ j ] NEW_LINE if summ == k : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT print ( res ) NEW_LINE |
Number of subarrays having sum exactly equal to k | Python3 program to find the number of subarrays with sum exactly equal to k . ; Function to find number of subarrays with sum exactly equal to k . ; Dictionary to store number of subarrays starting from index zero having particular value of sum . ; Sum of elements so far . ; Add current element to sum so far . ; If currsum is equal to desired sum , then a new subarray is found . So increase count of subarrays . ; currsum exceeds given sum by currsum - sum . Find number of subarrays having this sum and exclude those subarrays from currsum by increasing count by same amount . ; Add currsum value to count of different values of sum . ; Driver Code | from collections import defaultdict NEW_LINE def findSubarraySum ( arr , n , Sum ) : NEW_LINE INDENT prevSum = defaultdict ( lambda : 0 ) NEW_LINE res = 0 NEW_LINE currsum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT currsum += arr [ i ] NEW_LINE if currsum == Sum : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( currsum - Sum ) in prevSum : NEW_LINE INDENT res += prevSum [ currsum - Sum ] NEW_LINE DEDENT prevSum [ currsum ] += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 2 , - 2 , - 20 , 10 ] NEW_LINE Sum = - 10 NEW_LINE n = len ( arr ) NEW_LINE print ( findSubarraySum ( arr , n , Sum ) ) NEW_LINE DEDENT |
Count pairs whose products exist in array | Returns count of pairs whose product exists in arr [ ] ; find product in an array ; if product found increment counter ; return Count of all pair whose product exist in array ; Driver program | def countPairs ( arr , n ) : NEW_LINE INDENT result = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT product = arr [ i ] * arr [ j ] ; NEW_LINE for k in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ k ] == product ) : NEW_LINE INDENT result = result + 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return result ; NEW_LINE DEDENT arr = [ 6 , 2 , 4 , 12 , 5 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countPairs ( arr , n ) ) ; NEW_LINE |
Count pairs whose products exist in array | Returns count of pairs whose product exists in arr [ ] ; Create an empty hash - set that store all array element ; Insert all array element into set ; Generate all pairs and check is exist in ' Hash ' or not ; if product exists in set then we increment count by 1 ; return count of pairs whose product exist in array ; Driver Code | def countPairs ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE Hash = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT Hash . add ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT product = arr [ i ] * arr [ j ] NEW_LINE if product in ( Hash ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 2 , 4 , 12 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT |
Master Theorem For Subtract and Conquer Recurrences | ''Python3 code for the above approach ; ''Driver code | def fib ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE DEDENT n = 9 NEW_LINE print ( fib ( n ) ) NEW_LINE |
Tail Recursion | ''A tail recursive function to calculate factorial ; ''Driver program to test above function | def fact ( n , a = 1 ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return fact ( n - 1 , n * a ) NEW_LINE DEDENT print ( fact ( 5 ) ) NEW_LINE |
Minimum and maximum count of elements at D distance from arr [ i ] in either direction | ''Function to find the minimum and maximum number of points included in a range of distance D ; '' Stores the minimum and maximum number of points that lies over the distance of D ; '' Iterate the array ; '' Count of elements included to left of point at index i ; '' Update the minimum number of points ; '' Update the maximum number of points ; '' Count of elements included to right of point at index i ; '' Update the minimum number of points ; '' Update the maximum number of points ; '' Return the array ; ''Function to perform the Binary Search to the left of arr[i] over the given range ; '' Base Case ; '' Binary Search for index to left ; '' update index ; '' Return the number of elements by subtracting indices ; ''Function to perform the Binary Search to the right of arr[i] over the given range ; '' Base Case ; '' Binary Search for index to right ; '' Update the index ; '' Return the number of elements by subtracting indices ; ''Driver Code ; ''Function Call | def minMaxRange ( arr , D , N ) : NEW_LINE INDENT Max = 1 NEW_LINE Min = N NEW_LINE for i in range ( N ) : NEW_LINE INDENT dist = leftSearch ( arr , arr [ i ] - D , i ) NEW_LINE Min = min ( Min , dist ) NEW_LINE Max = max ( Max , dist ) NEW_LINE dist = rightSearch ( arr , arr [ i ] + D , i ) NEW_LINE Min = min ( Min , dist ) NEW_LINE Max = max ( Max , dist ) NEW_LINE DEDENT return [ Min , Max ] NEW_LINE DEDENT def leftSearch ( arr , val , i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT left = 0 NEW_LINE right = i - 1 NEW_LINE ind = - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE if ( arr [ mid ] < val ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE ind = mid NEW_LINE DEDENT DEDENT return i - ind + 1 if ind != - 1 else 1 NEW_LINE DEDENT def rightSearch ( arr , val , i ) : NEW_LINE INDENT if ( i == len ( arr ) - 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT left = i + 1 NEW_LINE right = len ( arr ) - 1 NEW_LINE ind = - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE if ( arr [ mid ] > val ) : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = mid + 1 NEW_LINE ind = mid NEW_LINE DEDENT DEDENT return ind - i + 1 if ind != - 1 else 1 NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 9 , 14 ] NEW_LINE N = len ( arr ) NEW_LINE D = 4 NEW_LINE minMax = minMaxRange ( arr , D , N ) NEW_LINE print ( f " { minMax [ 0 ] } β { minMax [ 1 ] } " ) NEW_LINE |
Given two unsorted arrays , find all pairs whose sum is x | Function to print all pairs in both arrays whose sum is equal to given value x ; Driver code | def findPairs ( arr1 , arr2 , n , m , x ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT if ( arr1 [ i ] + arr2 [ j ] == x ) : NEW_LINE INDENT print ( arr1 [ i ] , arr2 [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT arr1 = [ 1 , 2 , 3 , 7 , 5 , 4 ] NEW_LINE arr2 = [ 0 , 7 , 4 , 3 , 2 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE x = 8 NEW_LINE findPairs ( arr1 , arr2 , n , m , x ) NEW_LINE |
Smallest possible integer K such that ceil of each Array element when divided by K is at most M | ''python program for the above approach ; ''Function to check if the sum of ceil values of the arr[] for the K value is at most M or not ; '' Stores the sum of ceil values ; '' Update the sum ; '' Return true if sum is less than or equal to M, false otherwise ; ''Function to find the smallest possible integer K such that ceil(arr[0]/K) + ceil(arr[1]/K) +....+ ceil(arr[N-1]/K) is less than or equal to M ; '' Stores the low value ; '' Stores the high value ; '' Stores the middle value ; '' Update the mid value ; '' Check if the mid value is K ; '' Update the low value ; '' Update the high value ; '' Check if low is K or high is K and return it ; ''Driver Code | import math NEW_LINE def isvalid ( arr , K , N , M ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += math . ceil ( arr [ i ] * 1.0 / K ) NEW_LINE DEDENT return sum <= M NEW_LINE DEDENT def smallestValueForK ( arr , N , M ) : NEW_LINE INDENT low = 1 NEW_LINE high = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT high = max ( high , arr [ i ] ) NEW_LINE DEDENT mid = 0 NEW_LINE while ( high - low > 1 ) : NEW_LINE INDENT mid = ( high + low ) // 2 NEW_LINE if ( not isvalid ( arr , mid , N , M ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT if ( isvalid ( arr , low , N , M ) ) : NEW_LINE INDENT return low NEW_LINE DEDENT else : NEW_LINE INDENT return high NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 3 , 2 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE M = 5 NEW_LINE print ( smallestValueForK ( arr , N , M ) ) NEW_LINE DEDENT |
Given two unsorted arrays , find all pairs whose sum is x | Function to find all pairs in both arrays whose sum is equal to given value x ; Insert all elements of first array in a hash ; Subtract sum from second array elements one by one and check it 's present in array first or not ; Driver code | def findPairs ( arr1 , arr2 , n , m , x ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s . add ( arr1 [ i ] ) NEW_LINE DEDENT for j in range ( 0 , m ) : NEW_LINE INDENT if ( ( x - arr2 [ j ] ) in s ) : NEW_LINE INDENT print ( ( x - arr2 [ j ] ) , ' ' , arr2 [ j ] ) NEW_LINE DEDENT DEDENT DEDENT arr1 = [ 1 , 0 , - 4 , 7 , 6 , 4 ] NEW_LINE arr2 = [ 0 , 2 , 4 , - 3 , 2 , 1 ] NEW_LINE x = 8 NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE findPairs ( arr1 , arr2 , n , m , x ) NEW_LINE |
Check if a given Binary Tree is height balanced like a Red | Helper function that allocates a new node with the given data and None left and right poers . ; Returns returns tree if the Binary tree is balanced like a Red - Black tree . This function also sets value in maxh and minh ( passed by reference ) . maxh and minh are set as maximum and minimum heights of root . ; Base case ; To store max and min heights of left subtree ; To store max and min heights of right subtree ; Check if left subtree is balanced , also set lmxh and lmnh ; Check if right subtree is balanced , also set rmxh and rmnh ; Set the max and min heights of this node for the parent call ; See if this node is balanced ; A wrapper over isBalancedUtil ( ) ; Driver Code | class newNode : 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 isBalancedUtil ( root , maxh , minh ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT maxh = minh = 0 NEW_LINE return True NEW_LINE DEDENT lmxh = 0 NEW_LINE lmnh = 0 NEW_LINE rmxh , rmnh = 0 , 0 NEW_LINE if ( isBalancedUtil ( root . left , lmxh , lmnh ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( isBalancedUtil ( root . right , rmxh , rmnh ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT maxh = max ( lmxh , rmxh ) + 1 NEW_LINE minh = min ( lmnh , rmnh ) + 1 NEW_LINE if ( maxh <= 2 * minh ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isBalanced ( root ) : NEW_LINE INDENT maxh , minh = 0 , 0 NEW_LINE return isBalancedUtil ( root , maxh , minh ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 5 ) NEW_LINE root . right = newNode ( 100 ) NEW_LINE root . right . left = newNode ( 50 ) NEW_LINE root . right . right = newNode ( 150 ) NEW_LINE root . right . left . left = newNode ( 40 ) NEW_LINE if ( isBalanced ( root ) ) : NEW_LINE INDENT print ( " Balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Balanced " ) NEW_LINE DEDENT DEDENT |
Maximum Fixed Point ( Value equal to index ) in a given Array | ''Python implementation of the above approach Function to find the maximum index i such that arr[i] is equal to i ; '' Traversing the array from backwards ; '' If arr[i] is equal to i ; '' If there is no such index ; Given Input ; ''Function Call | def findLargestIndex ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == i ) : NEW_LINE INDENT print ( i ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT arr = [ - 10 , - 5 , 0 , 3 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE findLargestIndex ( arr , n ) NEW_LINE |
Cumulative frequency of count of each element in an unsorted array | Function to print the cumulative frequency according to the order given ; Insert elements and their frequencies in hash map . ; traverse in the array ; add the frequencies ; if the element has not been visited previously ; mark the hash 0 as the element 's cumulative frequency has been printed ; Driver Code | def countFreq ( a , n ) : NEW_LINE INDENT hm = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hm [ a [ i ] ] = hm . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT cumul = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT cumul += hm [ a [ i ] ] NEW_LINE if ( hm [ a [ i ] ] > 0 ) : NEW_LINE INDENT print ( a [ i ] , " - > " , cumul ) NEW_LINE DEDENT hm [ a [ i ] ] = 0 NEW_LINE DEDENT DEDENT a = [ 1 , 3 , 2 , 4 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE countFreq ( a , n ) NEW_LINE |
Find pairs in array whose sums already exist in array | Function to find pair whose sum exists in arr [ ] ; Driver code | def findPair ( arr , n ) : NEW_LINE INDENT found = False NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] == arr [ k ] ) : NEW_LINE INDENT print ( arr [ i ] , arr [ j ] ) NEW_LINE found = True NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT print ( " Not β exist " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 4 , 8 , 13 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE findPair ( arr , n ) NEW_LINE DEDENT |
Maximum number of mangoes that can be bought | ''Function to check if mid number of mangoes can be bought ; '' Store the coins ; '' If watermelons needed are greater than given watermelons ; '' Store remaining watermelons if vl watermelons are used to buy mangoes ; '' Store the value of coins if these watermelon get sold ; '' Increment coins by ex ; '' Number of mangoes that can be buyed if only x coins needed for one mango ; '' If the condition is satisfied, return true ; '' Otherwise return false ; ''Function to find the maximum number of mangoes that can be bought by selling watermelons ; '' Initialize the boundary values ; '' Store the required result ; '' Binary Search ; '' Store the mid value ; '' Check if it is possible to buy mid number of mangoes ; '' Otherwise, update r to mid -1 ; '' Return the result ; ''Driver Code ; '' Given Input ; '' Function Call | def check ( n , m , x , y , vl ) : NEW_LINE INDENT temp = m NEW_LINE if ( vl > n ) : NEW_LINE INDENT return False NEW_LINE DEDENT ex = n - vl NEW_LINE ex *= y NEW_LINE temp += ex NEW_LINE cr = temp // x NEW_LINE if ( cr >= vl ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def maximizeMangoes ( n , m , x , y ) : NEW_LINE INDENT l = 0 NEW_LINE r = n NEW_LINE ans = 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = l + ( r - l ) // 2 NEW_LINE if ( check ( n , m , x , y , mid ) ) : NEW_LINE INDENT ans = mid NEW_LINE l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT W = 4 NEW_LINE C = 8 NEW_LINE x = 4 NEW_LINE y = 4 NEW_LINE print ( maximizeMangoes ( W , C , x , y ) ) NEW_LINE DEDENT |
Kth Smallest Element in a sorted array formed by reversing subarrays from a random index | ''Function to find the Kth element in a sorted and rotated array at random point ; '' Set the boundaries for binary search ; '' Apply binary search to find R ; '' Initialize the middle element ; '' Check in the right side of mid ; '' Else check in the left side ; '' Random point either l or h ; '' Return the kth smallest element ; ''Driver Code ; '' Given Input ; '' Function Call | def findkthElement ( arr , n , K ) : NEW_LINE INDENT l = 0 NEW_LINE h = n - 1 NEW_LINE while l + 1 < h : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE if arr [ l ] >= arr [ mid ] : NEW_LINE INDENT l = mid NEW_LINE DEDENT else : NEW_LINE INDENT h = mid NEW_LINE DEDENT DEDENT if arr [ l ] < arr [ h ] : NEW_LINE INDENT r = l NEW_LINE DEDENT else : NEW_LINE INDENT r = h NEW_LINE DEDENT if K <= r + 1 : NEW_LINE INDENT return arr [ r + 1 - K ] NEW_LINE DEDENT else : NEW_LINE INDENT return arr [ n - ( K - ( r + 1 ) ) ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( findkthElement ( arr , n , K ) ) NEW_LINE DEDENT |
Find all pairs ( a , b ) in an array such that a % b = k | Function to find pair such that ( a % b = k ) ; Consider each and every pair ; Print if their modulo equals to k ; Driver Code | def printPairs ( arr , n , k ) : NEW_LINE INDENT isPairFound = True NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i != j and arr [ i ] % arr [ j ] == k ) : NEW_LINE INDENT print ( " ( " , arr [ i ] , " , β " , arr [ j ] , " ) " , sep = " " , end = " β " ) NEW_LINE isPairFound = True NEW_LINE DEDENT DEDENT DEDENT return isPairFound NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE if ( printPairs ( arr , n , k ) == False ) : NEW_LINE INDENT print ( " No β such β pair β exists " ) NEW_LINE DEDENT |
Find all pairs ( a , b ) in an array such that a % b = k | Utiltity function to find the divisors of n and store in vector v [ ] ; Vector is used to store the divisors ; If n is a square number , push only one occurrence ; Function to find pairs such that ( a % b = k ) ; Store all the elements in the map to use map as hash for finding elements in O ( 1 ) time . ; Print all the pairs with ( a , b ) as ( k , numbers greater than k ) as k % ( num ( > k ) ) = k i . e . 2 % 4 = 2 ; Now check for the current element as ' a ' how many b exists such that a % b = k ; find all the divisors of ( arr [ i ] - k ) ; Check for each divisor i . e . arr [ i ] % b = k or not , if yes then prthat pair . ; Clear vector ; Driver Code | import math as mt NEW_LINE def findDivisors ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , mt . floor ( n ** ( .5 ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n / i == i ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( i ) NEW_LINE v . append ( n // i ) NEW_LINE DEDENT DEDENT DEDENT return v NEW_LINE DEDENT def printPairs ( arr , n , k ) : NEW_LINE INDENT occ = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT occ [ arr [ i ] ] = True NEW_LINE DEDENT isPairFound = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( occ [ k ] and k < arr [ i ] ) : NEW_LINE INDENT print ( " ( " , k , " , " , arr [ i ] , " ) " , end = " β " ) NEW_LINE isPairFound = True NEW_LINE DEDENT if ( arr [ i ] >= k ) : NEW_LINE INDENT v = findDivisors ( arr [ i ] - k ) NEW_LINE for j in range ( len ( v ) ) : NEW_LINE INDENT if ( arr [ i ] % v [ j ] == k and arr [ i ] != v [ j ] and occ [ v [ j ] ] ) : NEW_LINE INDENT print ( " ( " , arr [ i ] , " , " , v [ j ] , " ) " , end = " β " ) NEW_LINE isPairFound = True NEW_LINE DEDENT DEDENT DEDENT DEDENT return isPairFound NEW_LINE DEDENT arr = [ 3 , 1 , 2 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE if ( printPairs ( arr , n , k ) == False ) : NEW_LINE INDENT print ( " No β such β pair β exists " ) NEW_LINE DEDENT |
Convert an array to reduced form | Set 1 ( Simple and Hashing ) | Python3 program to convert an array in reduced form ; Create a temp array and copy contents of arr [ ] to temp ; Sort temp array ; create a map ; One by one insert elements of sorted temp [ ] and assign them values from 0 to n - 1 ; Convert array by taking positions from umap ; Driver Code | def convert ( arr , n ) : NEW_LINE INDENT temp = [ arr [ i ] for i in range ( n ) ] NEW_LINE temp . sort ( ) NEW_LINE umap = { } NEW_LINE val = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT umap [ temp [ i ] ] = val NEW_LINE val += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = umap [ arr [ i ] ] NEW_LINE DEDENT DEDENT def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 20 , 15 , 12 , 11 , 50 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given β Array β is β " ) NEW_LINE printArr ( arr , n ) NEW_LINE convert ( arr , n ) NEW_LINE print ( " Converted Array is " ) NEW_LINE printArr ( arr , n ) NEW_LINE DEDENT |
Return maximum occurring character in an input string | Python program to return the maximum occurring character in the input string ; Create array to keep the count of individual characters Initialize the count array to zero ; Construct character count array from the input string . ; Initialize max count ; Initialize result ; Traversing through the string and maintaining the count of each character ; Driver program to test the above function | ASCII_SIZE = 256 NEW_LINE def getMaxOccuringChar ( str ) : NEW_LINE INDENT count = [ 0 ] * ASCII_SIZE NEW_LINE for i in str : NEW_LINE INDENT count [ ord ( i ) ] += 1 ; NEW_LINE DEDENT max = - 1 NEW_LINE c = ' ' NEW_LINE for i in str : NEW_LINE INDENT if max < count [ ord ( i ) ] : NEW_LINE INDENT max = count [ ord ( i ) ] NEW_LINE c = i NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT str = " sample β string " NEW_LINE print " Max β occurring β character β is β " + getMaxOccuringChar ( str ) NEW_LINE |
Check if a Binary Tree ( not BST ) has duplicate values | Helper function that allocates a new node with the given data and None left and right poers . ; If tree is empty , there are no duplicates . ; If current node 's data is already present. ; Insert current node ; Recursively check in left and right subtrees . ; To check if tree has duplicates ; Driver Code | class newNode : 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 checkDupUtil ( root , s ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if root . data in s : NEW_LINE INDENT return True NEW_LINE DEDENT s . add ( root . data ) NEW_LINE return checkDupUtil ( root . left , s ) or checkDupUtil ( root . right , s ) NEW_LINE DEDENT def checkDup ( root ) : NEW_LINE INDENT s = set ( ) NEW_LINE return checkDupUtil ( root , s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE if ( checkDup ( root ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Expression Tree | An expression tree node ; A utility function to check if ' c ' is an operator ; A utility function to do inorder traversal ; Returns root of constructed tree for given postfix expression ; Traverse through every character of input expression ; if operand , simply push into stack ; Operator ; Pop two top nodes ; make them children ; Add this subexpression to stack ; Only element will be the root of expression tree ; Driver program to test above | class Et : NEW_LINE INDENT def __init__ ( self , value ) : NEW_LINE INDENT self . value = value NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isOperator ( c ) : NEW_LINE INDENT if ( c == ' + ' or c == ' - ' or c == ' * ' or c == ' / ' or c == ' ^ ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def inorder ( t ) : NEW_LINE INDENT if t is not None : NEW_LINE INDENT inorder ( t . left ) NEW_LINE print t . value , NEW_LINE inorder ( t . right ) NEW_LINE DEDENT DEDENT def constructTree ( postfix ) : NEW_LINE INDENT stack = [ ] NEW_LINE for char in postfix : NEW_LINE INDENT if not isOperator ( char ) : NEW_LINE INDENT t = Et ( char ) NEW_LINE stack . append ( t ) NEW_LINE DEDENT else : NEW_LINE INDENT t = Et ( char ) NEW_LINE t1 = stack . pop ( ) NEW_LINE t2 = stack . pop ( ) NEW_LINE t . right = t1 NEW_LINE t . left = t2 NEW_LINE stack . append ( t ) NEW_LINE DEDENT DEDENT t = stack . pop ( ) NEW_LINE return t NEW_LINE DEDENT postfix = " ab + ef * g * - " NEW_LINE r = constructTree ( postfix ) NEW_LINE print " Infix β expression β is " NEW_LINE inorder ( r ) NEW_LINE |
Queries to count sum of rows and columns of a Matrix present in given ranges | ''Python3 program for the above approach ; ''Function to preprocess the matrix to execute the queries ; '' Stores the sum of each row ; '' Stores the sum of each col ; '' Traverse the matrix and calculate sum of each row and column ; '' Insert all row sums in sum_list ; '' Insert all column sums in sum_list ; '' Sort the array in ascending order ; '' Traverse the array queries[][] ; '' Search the leftmost index of L ; '' Search the rightmost index of R ; ''Function to search for the leftmost index of given number ; '' Initialize low, high and ans ; '' Stores mid ; '' If A[mid] >= num ; ''Function to search for the rightmost index of given number ; '' Initialise low, high and ans ; '' Stores mid ; '' If A[mid] <= num ; '' Update ans ; '' Update mid ; '' Update high ; ''Driver Code ; '' Given dimensions of matrix ; '' Given matrix ; '' Given number of queries ; '' Given queries ; '' Function call to count the number row-sums and column-sums present in the given ranges | from collections import deque NEW_LINE from bisect import bisect_left , bisect_right NEW_LINE def totalCount ( A , N , M , queries , Q ) : NEW_LINE INDENT row_sum = [ 0 ] * N NEW_LINE col_sum = [ 0 ] * M NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT row_sum [ i ] += A [ i ] [ j ] NEW_LINE col_sum [ j ] += A [ i ] [ j ] NEW_LINE DEDENT DEDENT sum_list = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum_list . append ( row_sum [ i ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT sum_list . append ( col_sum [ i ] ) NEW_LINE DEDENT sum_list = sorted ( sum_list ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT L = queries [ i ] [ 0 ] NEW_LINE R = queries [ i ] [ 1 ] NEW_LINE l = left_search ( sum_list , L ) NEW_LINE r = right_search ( sum_list , R ) NEW_LINE print ( r - l + 1 , end = " β " ) NEW_LINE DEDENT DEDENT def left_search ( A , num ) : NEW_LINE INDENT low , high = 0 , len ( A ) - 1 NEW_LINE ans = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( A [ mid ] >= num ) : NEW_LINE INDENT ans = mid NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def right_search ( A , num ) : NEW_LINE INDENT low , high = 0 , len ( A ) - 1 NEW_LINE ans = high NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( A [ mid ] <= num ) : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 3 , 2 NEW_LINE A = [ [ 13 , 3 ] , [ 9 , 4 ] , [ 6 , 10 ] ] NEW_LINE Q = 2 NEW_LINE queries = [ [ 10 , 20 ] , [ 25 , 35 ] ] NEW_LINE totalCount ( A , N , M , queries , Q ) NEW_LINE DEDENT |
Smallest element repeated exactly β k β times ( not limited to small range ) | Python program to find the smallest element with frequency exactly k . ; Map is used to store the count of elements present in the array ; Traverse the map and find minimum element with frequency k . ; Driver code | from collections import defaultdict NEW_LINE import sys NEW_LINE def smallestKFreq ( arr , n , k ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT res = sys . maxsize NEW_LINE res1 = sys . maxsize NEW_LINE for key , values in mp . items ( ) : NEW_LINE INDENT if values == k : NEW_LINE INDENT res = min ( res , key ) NEW_LINE DEDENT DEDENT return res if res != res1 else - 1 NEW_LINE DEDENT arr = [ 2 , 2 , 1 , 3 , 1 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( smallestKFreq ( arr , n , k ) ) NEW_LINE |
Maximize profit that can be earned by selling an item among N buyers | ; ''Function to find the maximum profit earned by selling an item among N buyers ; '' Stores the maximum profit ; '' Stores the price of the item ; '' Traverse the array ; '' Count of buyers with budget >= arr[i] ; '' Increment count ; '' Update the maximum profit ; '' Return the maximum possible price ; ''Driver code | import sys NEW_LINE def maximumProfit ( arr , n ) : NEW_LINE INDENT ans = - sys . maxsize - 1 NEW_LINE price = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ i ] <= arr [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( ans < count * arr [ i ] ) : NEW_LINE INDENT price = arr [ i ] NEW_LINE ans = count * arr [ i ] NEW_LINE DEDENT DEDENT return price ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 22 , 87 , 9 , 50 , 56 , 43 ] NEW_LINE print ( maximumProfit ( arr , 6 ) ) NEW_LINE DEDENT |
Lexicographically smallest permutation of the array possible by at most one swap | ''Function to print the elements of the array arr[] ; '' Traverse the array arr[] ; ''Function to convert given array to lexicographically smallest permutation possible by swapping at most one pair ; '' Stores the index of the first element which is not at its correct position ; '' Checks if any such array element exists or not ; '' Traverse the given array ; '' If element is found at i ; '' If the first array is not in correct position ; '' Store the index of the first elements ; '' Store the index of the first element ; '' Swap the pairs ; '' Print the array ; ''Given array ; ''Store the size of the array | def printt ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def makeLexicographically ( arr , N ) : NEW_LINE INDENT index = 0 NEW_LINE temp = 0 NEW_LINE check = 0 NEW_LINE condition = 0 NEW_LINE element = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( element == arr [ i ] ) : NEW_LINE INDENT check = i NEW_LINE break NEW_LINE DEDENT elif ( arr [ i ] != i + 1 and check == 0 ) : NEW_LINE INDENT index = i NEW_LINE check = 1 NEW_LINE condition = - 1 NEW_LINE element = i + 1 NEW_LINE DEDENT DEDENT if ( condition == - 1 ) : NEW_LINE INDENT temp = arr [ index ] NEW_LINE arr [ index ] = arr [ check ] NEW_LINE arr [ check ] = temp NEW_LINE DEDENT printt ( arr , N ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE makeLexicographically ( arr , N ) NEW_LINE |
Check if uppercase characters in a string are used correctly or not | ''Function to check if the character c is in lowercase or not ; ''Function to check if the character c is in uppercase or not ; ''Utility function to check if uppercase characters are used correctly or not ; '' Length of string ; '' If the first character is in lowercase ; '' Otherwise ; '' Check if all characters are in uppercase or not ; '' If all characters are in uppercase ; '' Check if all characters except the first are in lowercase ; ''Function to check if uppercase characters are used correctly or not ; '' Stores whether the use of uppercase characters are correct or not ; '' If correct ; '' Otherwise ; ''Driver Code ; '' Given string ; '' Function call to check if use of uppercase characters is correct or not | def isLower ( c ) : NEW_LINE INDENT return ord ( c ) >= ord ( ' a ' ) and ord ( c ) <= ord ( ' z ' ) NEW_LINE DEDENT def isUpper ( c ) : NEW_LINE INDENT return ord ( c ) >= ord ( ' A ' ) and ord ( c ) <= ord ( ' Z ' ) NEW_LINE DEDENT def detectUppercaseUseUtil ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE i = 0 NEW_LINE if ( isLower ( S [ 0 ] ) ) : NEW_LINE INDENT i = 1 NEW_LINE while ( S [ i ] and isLower ( S [ i ] ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT return True if ( i == N ) else False NEW_LINE DEDENT else : NEW_LINE INDENT i = 1 NEW_LINE while ( S [ i ] and isUpper ( S [ i ] ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( i == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( i > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( S [ i ] and isLower ( S [ i ] ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT return True if ( i == N ) else False NEW_LINE DEDENT DEDENT def detectUppercaseUse ( S ) : NEW_LINE INDENT check = detectUppercaseUseUtil ( S ) NEW_LINE if ( check ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " GeeKs " NEW_LINE detectUppercaseUse ( S ) NEW_LINE DEDENT |
Queries to count array elements from a given range having a single set bit | ''Check if N has only one set bit ; ''Function to build segment tree ; '' If se is leaf node ; '' Update the node ; '' Stores mid value of segment [ss, se] ; '' Recursive call for left Subtree ; '' Recursive call for right Subtree ; '' Update the Current Node ; ''Function to update a value at Xth index ; '' If ss is equal to X ; '' Update the Xth node ; '' Update the tree ; '' Stores the mid of segment [ss, se] ; '' Update current node ; ''Count of numbers having one set bit ; '' If L > se or R < ss Invalid Range ; '' If [ss, se] lies inside the [L, R] ; '' Stores the mid of segment [ss, se] ; '' Return the sum after recursively traversing left and right subtree ; ''Function to solve queries ; '' Initialise Segment tree ; '' Build segment tree ; '' Perform queries ; ''Input ; ''Function call to solve queries | def check ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( ( N & ( N - 1 ) ) == 0 ) NEW_LINE DEDENT def build_seg_tree ( ss , se , si , tree , arr ) : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT tree [ si ] = check ( arr [ ss ] ) NEW_LINE return NEW_LINE DEDENT mid = ( ss + se ) // 2 NEW_LINE build_seg_tree ( ss , mid , 2 * si + 1 , tree , arr ) NEW_LINE build_seg_tree ( mid + 1 , se , 2 * si + 2 , tree , arr ) NEW_LINE tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] NEW_LINE DEDENT def update ( ss , se , si , X , V , tree , arr ) : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT if ( ss == X ) : NEW_LINE INDENT arr [ X ] = V NEW_LINE tree [ si ] = check ( V ) NEW_LINE DEDENT return NEW_LINE DEDENT mid = ( ss + se ) // 2 NEW_LINE if ( X <= mid ) : NEW_LINE INDENT update ( ss , mid , 2 * si + 1 , X , V , tree , arr ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( mid + 1 , se , 2 * si + 2 , X , V , tree , arr ) NEW_LINE DEDENT tree [ si ] = tree [ 2 * si + 1 ] + tree [ 2 * si + 2 ] NEW_LINE DEDENT def query ( l , r , ss , se , si , tree ) : NEW_LINE INDENT if ( r < ss or l > se ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l <= ss and r >= se ) : NEW_LINE INDENT return tree [ si ] NEW_LINE DEDENT mid = ( ss + se ) // 2 NEW_LINE return ( query ( l , r , ss , mid , 2 * si + 1 , tree ) + query ( l , r , mid + 1 , se , 2 * si + 2 , tree ) ) NEW_LINE DEDENT def Query ( arr , N , Q ) : NEW_LINE INDENT tree = [ 0 ] * ( 4 * N ) NEW_LINE build_seg_tree ( 0 , N - 1 , 0 , tree , arr ) NEW_LINE for i in range ( len ( Q ) ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT print ( query ( Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , 0 , N - 1 , 0 , tree ) , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( 0 , N - 1 , 0 , Q [ i ] [ 1 ] , Q [ i ] [ 2 ] , tree , arr ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 12 , 11 , 16 , 2 , 32 ] NEW_LINE Q = [ [ 1 , 0 , 2 ] , [ 2 , 4 , 24 ] , [ 1 , 1 , 4 ] ] NEW_LINE N = len ( arr ) NEW_LINE Query ( arr , N , Q ) NEW_LINE |
Find the smallest value of N such that sum of first N natural numbers is Γ’ β°Β₯ X | ''Function to check if sum of first N natural numbers is >= X ; ''Finds minimum value of N such that sum of first N natural number >= X ; '' Binary Search ; ' ' β Checks β if β sum β of β first β ' mid ' natural numbers is greater than equal to X ; '' Update res ; '' Update high ; '' Update low ; ''Driver Code ; '' Input ; '' Finds minimum value of N such that sum of first N natural number >= X | def isGreaterEqual ( N , X ) : NEW_LINE INDENT return ( N * ( N + 1 ) // 2 ) >= X ; NEW_LINE DEDENT def minimumPossible ( X ) : NEW_LINE INDENT low = 1 NEW_LINE high = X NEW_LINE res = - 1 ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 ; NEW_LINE if ( isGreaterEqual ( mid , X ) ) : NEW_LINE INDENT res = mid ; NEW_LINE high = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 14 ; NEW_LINE print ( minimumPossible ( X ) ) ; NEW_LINE DEDENT |
Minimum moves required to come out of a grid safely | ''Stores size of the grid ; ''Function to check valid cells of the grid ; ''Checks for the border sides ; ''Function to find shortest distance between two cells of the grid ; '' Rows of the grid ; '' Column of the grid ; '' Stores possible move of the person ; '' Store possible cells visited by the person ; '' Store possible cells which are burning ; '' Traverse the grid ; '' If current cell is burning ; '' If person is in the current cell ; '' Stores shortest distance between two cells ; '' Check if a cell is visited by the person or not ; '' While pQ is not empty ; '' Update depth ; '' Popped all the cells from pQ and mark all adjacent cells of as visited ; '' Front element of the queue pQ ; '' Remove front element of the queue pQ ; '' If current cell is burning ; '' Find all adjacent cells ; '' Stores row number of adjacent cell ; '' Stores column number of adjacent cell ; '' Checks if current cell is valid ; '' Mark the cell as visited ; '' Enqueue the cell ; '' Checks the escape condition ; '' Burn all the adjacent cells of burning cells ; '' Front element of the queue fQ ; '' Delete front element of the queue fQ ; '' Find adjacent cells of burning cell ; '' Stores row number of adjacent cell ; '' Stores column number of adjacent cell ; '' Checks if current cell is valid ; '' Burn all the adjacent cells of current cell ; ''Driver Code ; '' Given grid | m = 0 NEW_LINE n = 0 NEW_LINE def valid ( x , y ) : NEW_LINE INDENT global n NEW_LINE global m NEW_LINE return ( x >= 0 and x < m and y >= 0 and y < n ) NEW_LINE DEDENT def border ( x , y ) : NEW_LINE INDENT global n NEW_LINE global m NEW_LINE return ( x == 0 or x == m - 1 or y == 0 or y == n - 1 ) NEW_LINE DEDENT def minStep ( mat ) : NEW_LINE INDENT global n NEW_LINE global m NEW_LINE m = len ( mat ) NEW_LINE n = len ( mat [ 0 ] ) NEW_LINE dx = [ 1 , - 1 , 0 , 0 ] NEW_LINE dy = [ 0 , 0 , 1 , - 1 ] NEW_LINE pQ = [ ] NEW_LINE fQ = [ ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 2 ) : NEW_LINE INDENT fQ . append ( [ i , j ] ) NEW_LINE DEDENT elif ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT if ( border ( i , j ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT pQ . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT DEDENT depth = 0 NEW_LINE visited = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE while ( len ( pQ ) > 0 ) : NEW_LINE INDENT depth += 1 NEW_LINE i = len ( pQ ) NEW_LINE while ( i > 0 ) : NEW_LINE INDENT pos = pQ [ 0 ] NEW_LINE pQ . remove ( pQ [ 0 ] ) NEW_LINE if ( mat [ pos [ 0 ] ] [ pos [ 1 ] ] == 2 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( 4 ) : NEW_LINE INDENT x = pos [ 0 ] + dx [ j ] NEW_LINE y = pos [ 1 ] + dy [ j ] NEW_LINE if ( valid ( x , y ) and mat [ x ] [ y ] != 2 and visited [ x ] [ y ] == 0 ) : NEW_LINE INDENT visited [ x ] [ y ] = 1 NEW_LINE pQ . append ( [ x , y ] ) NEW_LINE if ( border ( x , y ) ) : NEW_LINE INDENT return depth NEW_LINE DEDENT DEDENT DEDENT i -= 1 NEW_LINE DEDENT i = len ( fQ ) NEW_LINE while ( i > 0 ) : NEW_LINE INDENT pos = fQ [ 0 ] NEW_LINE fQ . remove ( fQ [ 0 ] ) NEW_LINE for j in range ( 4 ) : NEW_LINE INDENT x = pos [ 0 ] + dx [ j ] NEW_LINE y = pos [ 1 ] + dy [ j ] NEW_LINE if ( valid ( x , y ) and mat [ x ] [ y ] != 2 ) : NEW_LINE INDENT mat [ x ] [ y ] = 2 NEW_LINE fQ . append ( [ x , y ] ) NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 0 , 0 , 0 , 0 ] , [ 2 , 0 , 0 , 0 ] , [ 2 , 1 , 0 , 0 ] , [ 2 , 2 , 0 , 0 ] ] NEW_LINE print ( minStep ( grid ) ) NEW_LINE DEDENT |
Find sum of non | Find the sum of all non - repeated elements in an array ; sort all elements of array ; Driver code | def findSum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = arr [ 0 ] NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] ) : NEW_LINE INDENT sum = sum + arr [ i + 1 ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSum ( arr , n ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Length of the longest subsequence such that XOR of adjacent elements is equal to K | ''Function to find maximum length of subsequence having XOR of adjacent elements equal to K ; '' Store maximum length of subsequence ; '' Stores the dp-states ; '' Base case ; '' Iterate over the range [1, N-1] ; '' Iterate over the range [0, i - 1] ; '' If arr[i]^arr[j] == K ; '' Update the dp[i] ; '' Update the maximum subsequence length ; '' If length of longest subsequence is less than 2 then return 0 ; ''Driver Code ; '' Input ; '' Prthe length of longest subsequence | def xorSubsequence ( a , n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( ( a [ i ] ^ a [ j ] ) == k ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ j ] + 1 ) ; NEW_LINE DEDENT DEDENT ans = max ( ans , dp [ i ] ) ; NEW_LINE dp [ i ] = max ( 1 , dp [ i ] ) ; NEW_LINE DEDENT return ans if ans >= 2 else 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 3 , 5 ] ; NEW_LINE K = 1 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( xorSubsequence ( arr , N , K ) ) ; NEW_LINE DEDENT |
Check if a Binary Tree contains duplicate subtrees of size 2 or more | Python3 program to find if there is a duplicate sub - tree of size 2 or more Separator node ; Structure for a binary tree node ; This function returns empty if tree contains a duplicate subtree of size 2 or more . ; If current node is None , return marker ; If left subtree has a duplicate subtree . ; Do same for right subtree ; Serialize current subtree ; If current subtree already exists in hash table . [ Note that size of a serialized tree with single node is 3 as it has two marker nodes . ; Driver code | MARKER = ' $ ' NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT subtrees = { } NEW_LINE def dupSubUtil ( root ) : NEW_LINE INDENT global subtrees NEW_LINE s = " " NEW_LINE if ( root == None ) : NEW_LINE INDENT return s + MARKER NEW_LINE DEDENT lStr = dupSubUtil ( root . left ) NEW_LINE if ( s in lStr ) : NEW_LINE return s NEW_LINE rStr = dupSubUtil ( root . right ) NEW_LINE if ( s in rStr ) : NEW_LINE return s NEW_LINE s = s + root . key + lStr + rStr NEW_LINE if ( len ( s ) > 3 and s in subtrees ) : NEW_LINE return " " NEW_LINE subtrees [ s ] = 1 NEW_LINE return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( ' A ' ) NEW_LINE root . left = Node ( ' B ' ) NEW_LINE root . right = Node ( ' C ' ) NEW_LINE root . left . left = Node ( ' D ' ) NEW_LINE root . left . right = Node ( ' E ' ) NEW_LINE root . right . right = Node ( ' B ' ) NEW_LINE root . right . right . right = Node ( ' E ' ) NEW_LINE root . right . right . left = Node ( ' D ' ) NEW_LINE str = dupSubUtil ( root ) NEW_LINE if " " in str : NEW_LINE INDENT print ( " β Yes β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β No β " ) NEW_LINE DEDENT DEDENT |
Count pairs of similar rectangles possible from a given array | ''Python 3 Program for the hashmap Approach ; ''Get the count of all pairs of similar rectangles ; '' Initialize the result value and map to store the ratio to the rectangles ; '' Calculate the rectangular ratio and save them ; '' Calculate pairs of similar rectangles from its common ratio ; ''Driver code | from collections import defaultdict NEW_LINE def getCount ( rows , columns , sides ) : NEW_LINE INDENT ans = 0 NEW_LINE umap = defaultdict ( int ) NEW_LINE for i in range ( rows ) : NEW_LINE INDENT ratio = sides [ i ] [ 0 ] / sides [ i ] [ 1 ] NEW_LINE umap [ ratio ] += 1 NEW_LINE DEDENT for x in umap : NEW_LINE INDENT value = umap [ x ] NEW_LINE if ( value > 1 ) : NEW_LINE INDENT ans += ( value * ( value - 1 ) ) / 2 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sides = [ [ 4 , 8 ] , [ 10 , 20 ] , [ 15 , 30 ] , [ 3 , 6 ] ] NEW_LINE rows = 4 NEW_LINE columns = 2 NEW_LINE print ( int ( getCount ( rows , columns , sides ) ) ) NEW_LINE DEDENT |
Non | Python3 program to find first non - repeating element . ; Driver code | def firstNonRepeating ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < n ) : NEW_LINE INDENT if ( i != j and arr [ i ] == arr [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 9 , 4 , 9 , 6 , 7 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( firstNonRepeating ( arr , n ) ) NEW_LINE |
Non | Efficient Python3 program to find first non - repeating element . ; Insert all array elements in hash table ; Traverse array again and return first element with count 1. ; Driver Code | from collections import defaultdict NEW_LINE def firstNonRepeating ( arr , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if mp [ arr [ i ] ] == 1 : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 9 , 4 , 9 , 6 , 7 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( firstNonRepeating ( arr , n ) ) NEW_LINE |
Non | Efficient Python program to print all non - repeating elements . ; Insert all array elements in hash table ; Traverse through map only and ; Driver code | def firstNonRepeating ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in mp : NEW_LINE INDENT mp [ arr [ i ] ] = 0 NEW_LINE DEDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for x in mp : NEW_LINE INDENT if ( mp [ x ] == 1 ) : NEW_LINE INDENT print ( x , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 9 , 4 , 9 , 6 , 7 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE firstNonRepeating ( arr , n ) NEW_LINE |
Minimum substring removals required to make all remaining characters of a string same | ''Python3 program to implement the above approach ; ''Function to count minimum operations required to make all characters equal by repeatedly removing substring ; '' Remove consecutive duplicate characters from str ; '' Stores length of the string ; '' Stores frequency of each distinct characters of the string str ; '' Iterate over all the characters of the string str ; '' Update frequency of str[i] ; '' Decrementing the frequency of the string str[0] ; '' Decrementing the frequency of the ord(string ord(str[N - 1] ; '' Stores the required count ; '' Iterate over all characters of the string str ; '' Update ans ; ''Driver Code ; '' Given string | import re , sys NEW_LINE def minOperationNeeded ( s ) : NEW_LINE INDENT d = { } NEW_LINE str = re . sub ( r " ( . ) \1 β + β " , ' ' , s ) NEW_LINE N = len ( str ) NEW_LINE res = [ 0 for i in range ( 256 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT res [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT res [ ord ( str [ 0 ] ) ] -= 1 NEW_LINE res [ ord ( str [ N - 1 ] ) ] -= 1 NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans = min ( ans , res [ ord ( str [ i ] ) ] ) NEW_LINE DEDENT print ( ( ans + 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " ABCDABCDABCDA " NEW_LINE minOperationNeeded ( str ) NEW_LINE DEDENT |
Print all root to leaf paths of an N | ''Structure of an N ary tree node ; ''Function to print the root to leaf path of the given N-ary Tree ; '' Print elements in the vector ; ''Utility function to print all root to leaf paths of an Nary Tree ; '' If root is null ; ' ' β Insert β current β node ' s data into the vector ; '' If current node is a leaf node ; '' Print the path ; '' Pop the leaf node and return ; '' Recur for all children of the current node ; '' Recursive Function Call ; ''Function to print root to leaf path ; '' If root is null, return ; '' Utility function call ; ''Driver Code ; '' Given N-Ary tree ; '' Function Call | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def printPath ( vec ) : NEW_LINE INDENT for ele in vec : NEW_LINE INDENT print ( ele , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def printAllRootToLeafPaths ( root ) : NEW_LINE INDENT global vec NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT vec . append ( root . data ) NEW_LINE if ( len ( root . child ) == 0 ) : NEW_LINE INDENT printPath ( vec ) NEW_LINE vec . pop ( ) NEW_LINE return NEW_LINE DEDENT for i in range ( len ( root . child ) ) : NEW_LINE INDENT printAllRootToLeafPaths ( root . child [ i ] ) NEW_LINE DEDENT vec . pop ( ) NEW_LINE DEDENT def printRootToLeafPaths ( root ) : NEW_LINE INDENT global vec NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT printAllRootToLeafPaths ( root ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT vec = [ ] NEW_LINE root = Node ( 1 ) NEW_LINE root . child . append ( Node ( 2 ) ) NEW_LINE root . child . append ( Node ( 3 ) ) NEW_LINE root . child [ 0 ] . child . append ( Node ( 4 ) ) NEW_LINE root . child [ 1 ] . child . append ( Node ( 5 ) ) NEW_LINE root . child [ 1 ] . child . append ( Node ( 6 ) ) NEW_LINE root . child [ 1 ] . child [ 1 ] . child . append ( Node ( 7 ) ) NEW_LINE root . child [ 1 ] . child [ 1 ] . child . append ( Node ( 8 ) ) NEW_LINE printRootToLeafPaths ( root ) NEW_LINE DEDENT |
Pairs of Positive Negative values in an array | Print pair with negative and positive value ; For each element of array . ; Try to find the negative value of arr [ i ] from i + 1 to n ; If absolute values are equal print pair . ; If size of vector is 0 , therefore there is no element with positive negative value , print "0" ; Sort the vector ; Print the pair with negative positive value . ; Driver Code | def printPairs ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) == abs ( arr [ j ] ) ) : NEW_LINE INDENT v . append ( abs ( arr [ i ] ) ) NEW_LINE DEDENT DEDENT DEDENT if ( len ( v ) == 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT v . sort ( ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT print ( - v [ i ] , " " , v [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 ] NEW_LINE n = len ( arr ) NEW_LINE printPairs ( arr , n ) NEW_LINE DEDENT |
Check if an array can be divided into pairs whose sum is divisible by k | Python3 program to check if arr [ 0. . n - 1 ] can be divided in pairs such that every pair is divisible by k . ; Returns true if arr [ 0. . n - 1 ] can be divided into pairs with sum divisible by k . ; An odd length array cannot be divided into pairs ; Create a frequency array to count occurrences of all remainders when divided by k . ; Count occurrences of all remainders ; Traverse input array and use freq [ ] to decide if given array can be divided in pairs ; Remainder of current element ; If remainder with current element divides k into two halves . ; Then there must be even occurrences of such remainder ; If remainder is 0 , then there must be two elements with 0 remainde ; Then there must be even occurrences of such remainder ; Else number of occurrences of remainder must be equal to number of occurrences of k - remainder ; Driver code ; Function call | from collections import defaultdict NEW_LINE def canPairs ( arr , n , k ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT freq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT freq [ ( ( arr [ i ] % k ) + k ) % k ] += 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT rem = ( ( arr [ i ] % k ) + k ) % k NEW_LINE if ( 2 * rem == k ) : NEW_LINE INDENT if ( freq [ rem ] % 2 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT elif ( rem == 0 ) : NEW_LINE INDENT if ( freq [ rem ] & 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT elif ( freq [ rem ] != freq [ k - rem ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT arr = [ 92 , 75 , 65 , 48 , 45 , 35 ] NEW_LINE k = 10 NEW_LINE n = len ( arr ) NEW_LINE if ( canPairs ( arr , n , k ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT |
Subarray with no pair sum divisible by K | function to find the subarray with no pair sum divisible by k ; hash table to store the remainders obtained on dividing by K ; s : starting index of the current subarray , e : ending index of the current subarray , maxs : starting index of the maximum size subarray so far , maxe : ending index of the maximum size subarray so far ; insert the first element in the set ; Removing starting elements of current subarray while there is an element in set which makes a pair with mod [ i ] such that the pair sum is divisible . ; include the current element in the current subarray the ending index of the current subarray increments by one ; compare the size of the current subarray with the maximum size so far ; Driver Code | def subarrayDivisibleByK ( arr , n , k ) : NEW_LINE INDENT mp = [ 0 ] * 1000 NEW_LINE s = 0 ; e = 0 ; maxs = 0 ; maxe = 0 ; NEW_LINE mp [ arr [ 0 ] % k ] = mp [ arr [ 0 ] % k ] + 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT mod = arr [ i ] % k NEW_LINE while ( mp [ k - mod ] != 0 or ( mod == 0 and mp [ mod ] != 0 ) ) : NEW_LINE INDENT mp [ arr [ s ] % k ] = mp [ arr [ s ] % k ] - 1 NEW_LINE s = s + 1 NEW_LINE DEDENT mp [ mod ] = mp [ mod ] + 1 NEW_LINE e = e + 1 NEW_LINE if ( ( e - s ) > ( maxe - maxs ) ) : NEW_LINE INDENT maxe = e NEW_LINE maxs = s NEW_LINE DEDENT DEDENT print ( " The β maximum β size β is β { } β and β the β " . format ( ( maxe - maxs + 1 ) ) ) for i in range ( maxs , maxe + 1 ) : NEW_LINE INDENT print ( " { } β " . format ( arr [ i ] ) , end = " " ) NEW_LINE DEDENT DEDENT k = 3 NEW_LINE arr = [ 5 , 10 , 15 , 20 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE subarrayDivisibleByK ( arr , n , k ) NEW_LINE |
Find three element from different three arrays such that a + b + c = sum | Function to check if there is an element from each array such that sum of the three elements is equal to given sum . ; Driver Code | def findTriplet ( a1 , a2 , a3 , n1 , n2 , n3 , sum ) : NEW_LINE INDENT for i in range ( 0 , n1 ) : NEW_LINE INDENT for j in range ( 0 , n2 ) : NEW_LINE INDENT for k in range ( 0 , n3 ) : NEW_LINE INDENT if ( a1 [ i ] + a2 [ j ] + a3 [ k ] == sum ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT a1 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE a2 = [ 2 , 3 , 6 , 1 , 2 ] NEW_LINE a3 = [ 3 , 2 , 4 , 5 , 6 ] NEW_LINE sum = 9 NEW_LINE n1 = len ( a1 ) NEW_LINE n2 = len ( a2 ) NEW_LINE n3 = len ( a3 ) NEW_LINE print ( " Yes " ) if findTriplet ( a1 , a2 , a3 , n1 , n2 , n3 , sum ) else print ( " No " ) NEW_LINE |
Find three element from different three arrays such that a + b + c = sum | Function to check if there is an element from each array such that sum of the three elements is equal to given sum . ; Store elements of first array in hash ; sum last two arrays element one by one ; Consider current pair and find if there is an element in a1 [ ] such that these three form a required triplet ; Driver code | def findTriplet ( a1 , a2 , a3 , n1 , n2 , n3 , sum ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT s . add ( a1 [ i ] ) NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT for j in range ( n3 ) : NEW_LINE INDENT if sum - a2 [ i ] - a3 [ j ] in s : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT a1 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE a2 = [ 2 , 3 , 6 , 1 , 2 ] NEW_LINE a3 = [ 3 , 24 , 5 , 6 ] NEW_LINE n1 = len ( a1 ) NEW_LINE n2 = len ( a2 ) NEW_LINE n3 = len ( a3 ) NEW_LINE sum = 9 NEW_LINE if findTriplet ( a1 , a2 , a3 , n1 , n2 , n3 , sum ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Count quadruplets with sum K from given array | ''Function to return the number of quadruplets having given sum ; '' Initialize answer ; '' All possible first elements ; '' All possible second element ; '' Use map to find the fourth element ; '' All possible third elements ; '' Calculate number of valid 4th elements ; '' Update the twice_count ; '' Unordered pairs ; '' Return answer ; ''Driver Code ; '' Given array arr[] ; '' Given sum S ; '' Function Call | def countSum ( a , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 , 1 ) : NEW_LINE INDENT req = sum - a [ i ] - a [ j ] NEW_LINE m = { } NEW_LINE for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT m [ a [ k ] ] = m . get ( a [ k ] , 0 ) + 1 NEW_LINE DEDENT twice_count = 0 NEW_LINE for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT twice_count += m . get ( req - a [ k ] , 0 ) NEW_LINE if ( req - a [ k ] == a [ k ] ) : NEW_LINE INDENT twice_count -= 1 NEW_LINE DEDENT DEDENT count += twice_count // 2 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 3 , 1 , 2 , 4 ] NEW_LINE S = 13 NEW_LINE N = len ( arr ) NEW_LINE print ( countSum ( arr , N , S ) ) NEW_LINE DEDENT |
Find four elements a , b , c and d in an array such that a + b = c + d | function to find a , b , c , d such that ( a + b ) = ( c + d ) ; Create an empty hashmap to store mapping from sum to pair indexes ; Traverse through all possible pairs of arr [ ] ; Sum already present in hash ; driver program | def find_pair_of_sum ( arr : list , n : int ) : NEW_LINE INDENT map = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = arr [ i ] + arr [ j ] NEW_LINE if sum in map : NEW_LINE INDENT print ( f " { map [ sum ] } β and β ( { arr [ i ] } , β { arr [ j ] } ) " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT map [ sum ] = ( arr [ i ] , arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 4 , 7 , 1 , 2 , 9 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE find_pair_of_sum ( arr , n ) NEW_LINE DEDENT |
Check if all subarrays contains at least one unique element | ''Function to check if all subarrays have at least one unique element ; '' Generate all subarray ; ' ' β Store β frequency β of β β subarray ' s elements ; '' Traverse the array over the range [i, N] ; '' Update frequency of current subarray in map ; '' Increment count ; '' Decrement count ; '' If all subarrays have at least 1 unique element ; ''Driver Code ; '' Given array arr[] ; '' Function Call | def check ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT hm = { } NEW_LINE count = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT hm [ arr [ j ] ] = hm . get ( arr [ j ] , 0 ) + 1 NEW_LINE if ( hm [ arr [ j ] ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( hm [ arr [ j ] ] == 2 ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count == 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( check ( arr , N ) ) NEW_LINE DEDENT |
Count all disjoint pairs having absolute difference at least K from a given array | ''Function to count distinct pairs with absolute difference atleast K ; '' Track the element that have been paired ; '' Stores count of distinct pairs ; '' Pick all elements one by one ; '' If already visited ; '' If already visited ; '' If difference is at least K ; '' Mark element as visited and increment the count ; '' Print the final count ; ''Driver Code ; '' Given arr[] ; '' Size of array ; '' Given difference K ; '' Function Call | def countPairsWithDiffK ( arr , N , K ) : NEW_LINE INDENT vis = [ 0 ] * N NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( vis [ i ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( vis [ j ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( abs ( arr [ i ] - arr [ j ] ) >= K ) : NEW_LINE INDENT count += 1 NEW_LINE vis [ i ] = 1 NEW_LINE vis [ j ] = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE countPairsWithDiffK ( arr , N , K ) NEW_LINE DEDENT |
Check if two trees are Mirror | A binary tree node ; Given two trees , return true if they are mirror of each other ; Base case : Both empty ; If only one is empty ; Both non - empty , compare them recursively . Note that in recursive calls , we pass left of one tree and right of other tree ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def areMirror ( a , b ) : NEW_LINE INDENT if a is None and b is None : NEW_LINE INDENT return True NEW_LINE DEDENT if a is None or b is None : NEW_LINE INDENT return False NEW_LINE DEDENT return ( a . data == b . data and areMirror ( a . left , b . right ) and areMirror ( a . right , b . left ) ) NEW_LINE DEDENT root1 = Node ( 1 ) NEW_LINE root2 = Node ( 1 ) NEW_LINE root1 . left = Node ( 2 ) NEW_LINE root1 . right = Node ( 3 ) NEW_LINE root1 . left . left = Node ( 4 ) NEW_LINE root1 . left . right = Node ( 5 ) NEW_LINE root2 . left = Node ( 3 ) NEW_LINE root2 . right = Node ( 2 ) NEW_LINE root2 . right . left = Node ( 5 ) NEW_LINE root2 . right . right = Node ( 4 ) NEW_LINE if areMirror ( root1 , root2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find the length of largest subarray with 0 sum | Returns the maximum length ; NOTE : Dictonary in python in implemented as Hash Maps Create an empty hash map ( dictionary ) ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add the current element to the sum ; NOTE : ' in ' operation in dictionary to search key takes O ( 1 ) . Look if current sum is seen before ; else put this sum in dictionary ; test array | def maxLen ( arr ) : NEW_LINE INDENT hash_map = { } NEW_LINE curr_sum = 0 NEW_LINE max_len = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE if arr [ i ] is 0 and max_len is 0 : NEW_LINE INDENT max_len = 1 NEW_LINE DEDENT if curr_sum is 0 : NEW_LINE INDENT max_len = i + 1 NEW_LINE DEDENT if curr_sum in hash_map : NEW_LINE INDENT max_len = max ( max_len , i - hash_map [ curr_sum ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hash_map [ curr_sum ] = i NEW_LINE DEDENT DEDENT return max_len NEW_LINE DEDENT arr = [ 15 , - 2 , 2 , - 8 , 1 , 7 , 10 , 13 ] NEW_LINE print " Length β of β the β longest β 0 β sum β subarray β is β % β d " % maxLen ( arr ) NEW_LINE |
Print alternate elements of an array | ''Function to print Alternate elements of the given array ; '' Print elements at odd positions ; '' Print elements of array ; ''Driver Code | def printAlter ( arr , N ) : NEW_LINE INDENT for currIndex in range ( 0 , N , 2 ) : NEW_LINE INDENT print ( arr [ currIndex ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE printAlter ( arr , N ) NEW_LINE DEDENT |
Longest Increasing consecutive subsequence | python program to find length of the longest increasing subsequence whose adjacent element differ by 1 ; function that returns the length of the longest increasing subsequence whose adjacent element differ by 1 ; create hashmap to save latest consequent number as " key " and its length as " value " ; stores the length of the longest subsequence that ends with a [ i ] ; iterate for all element ; if a [ i ] - 1 is present before i - th index ; last index of a [ i ] - 1 ; Driver Code | from collections import defaultdict NEW_LINE import sys NEW_LINE def longestSubsequence ( a , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE dp = [ 0 for i in range ( n ) ] NEW_LINE maximum = - sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] - 1 in mp : NEW_LINE INDENT lastIndex = mp [ a [ i ] - 1 ] - 1 NEW_LINE dp [ i ] = 1 + dp [ lastIndex ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT mp [ a [ i ] ] = i + 1 NEW_LINE maximum = max ( maximum , dp [ i ] ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT a = [ 3 , 10 , 3 , 11 , 4 , 5 , 6 , 7 , 8 , 12 ] NEW_LINE n = len ( a ) NEW_LINE print ( longestSubsequence ( a , n ) ) NEW_LINE |
Longest subsequence such that difference between adjacents is one | Set 2 | Python3 implementation to find longest subsequence such that difference between adjacents is one ; function to find longest subsequence such that difference between adjacents is one ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last element of that subsequence ; to store the longest length subsequence ; traverse the array elements ; / initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' um ' and its length of subsequence is greater than 'len ; f ' arr [ i ] + 1' is in ' um ' and its length of subsequence is greater than ' len ' ; update arr [ i ] subsequence length in ' um ' ; update longest length ; required longest length subsequence ; Driver code | from collections import defaultdict NEW_LINE def longLenSub ( arr , n ) : NEW_LINE INDENT um = defaultdict ( lambda : 0 ) NEW_LINE longLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT len1 = 0 NEW_LINE if ( arr [ i - 1 ] in um and len1 < um [ arr [ i ] - 1 ] ) : NEW_LINE INDENT len1 = um [ arr [ i ] - 1 ] NEW_LINE DEDENT if ( arr [ i ] + 1 in um and len1 < um [ arr [ i ] + 1 ] ) : NEW_LINE INDENT len1 = um [ arr [ i ] + 1 ] NEW_LINE DEDENT um [ arr [ i ] ] = len1 + 1 NEW_LINE if longLen < um [ arr [ i ] ] : NEW_LINE INDENT longLen = um [ arr [ i ] ] NEW_LINE DEDENT DEDENT return longLen NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Longest β length β subsequence β = " , longLenSub ( arr , n ) ) NEW_LINE |
Count nodes having highest value in the path from root to itself in a Binary Tree | ''Python 3 program for the above approach ; ''Stores the ct of nodes which are maximum in the path from root to the current node ; ''Binary Tree Node ; ''Function that performs Inorder Traversal on the Binary Tree ; '' If root does not exist ; '' Check if the node satisfies the condition ; '' Update the maximum value and recursively traverse left and right subtree ; ''Function that counts the good nodes in the given Binary Tree ; '' Perform inorder Traversal ; '' Return the final count ; ''Driver code ; '' A Binary Tree 3 / / 2 5 / / 4 6 ; '' Function call ; '' Print the count of good nodes | import sys NEW_LINE ct = 0 NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def find ( root , mx ) : NEW_LINE INDENT global ct NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . val >= mx ) : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT find ( root . left , max ( mx , root . val ) ) NEW_LINE find ( root . right , max ( mx , root . val ) ) NEW_LINE DEDENT def NodesMaxInPath ( root ) : NEW_LINE INDENT global ct NEW_LINE find ( root , - sys . maxsize - 1 ) NEW_LINE return ct NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 3 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE answer = NodesMaxInPath ( root ) NEW_LINE print ( answer ) NEW_LINE DEDENT |
Longest Consecutive Subsequence | Returns length of the longest contiguous subsequence ; Sort the array ; Insert repeated elements only once in the vector ; Find the maximum length by traversing the array ; Check if the current element is equal to previous element + 1 ; Update the maximum ; Driver code | def findLongestConseqSubseq ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE count = 0 NEW_LINE arr . sort ( ) NEW_LINE v = [ ] NEW_LINE v . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT if ( i > 0 and v [ i ] == v [ i - 1 ] + 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 1 NEW_LINE DEDENT ans = max ( ans , count ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Length β of β the β Longest β contiguous β subsequence β is " , findLongestConseqSubseq ( arr , n ) ) NEW_LINE |
Count smaller primes on the right of each array element | ''Python3 program for the above approach ; ''Function to check if a number is prime or not ; ''Function to update a Binary Tree ; ''Function to find the sum of all the elements which are less than or equal to index ; ''Function to find the number of smaller primes on the right for every array element ; '' Iterate the array in backwards ; '' Calculating the required number of primes ; '' If current array element is prime ; '' Update the Fenwick tree ; ''Driver Code ; '' Function call | maxn = int ( 1e6 ) + 5 NEW_LINE BITree = [ 0 ] * ( maxn ) NEW_LINE def is_prime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def update_bitree ( index , value ) : NEW_LINE INDENT while ( index <= maxn ) : NEW_LINE INDENT BITree [ index ] += value NEW_LINE index += ( index & ( - index ) ) NEW_LINE DEDENT DEDENT def sum_bitree ( index ) : NEW_LINE INDENT s = 0 NEW_LINE while ( index > 0 ) : NEW_LINE INDENT s += BITree [ index ] NEW_LINE index -= ( index & ( - index ) ) NEW_LINE DEDENT return s NEW_LINE DEDENT def countSmallerPrimes ( ar , N ) : NEW_LINE INDENT ans = [ 0 ] * ( N ) NEW_LINE global BITree NEW_LINE for i in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT ans [ i ] = sum_bitree ( ar [ i ] ) NEW_LINE if ( is_prime ( ar [ i ] ) ) : NEW_LINE INDENT update_bitree ( ar [ i ] , 1 ) NEW_LINE DEDENT DEDENT ans [ 0 ] = 2 NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ 5 , 5 , 17 , 9 , 12 , 15 , 11 , 7 , 39 , 3 ] NEW_LINE N = len ( ar ) NEW_LINE countSmallerPrimes ( ar , N ) NEW_LINE DEDENT |
Longest Consecutive Subsequence | Python program to find longest contiguous subsequence ; Hash all the array elements ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; Then check for next elements in the sequence ; update optimal length if this length is more ; Driver code | from sets import Set NEW_LINE def findLongestConseqSubseq ( arr , n ) : NEW_LINE INDENT s = Set ( ) NEW_LINE ans = 0 NEW_LINE for ele in arr : NEW_LINE INDENT s . add ( ele ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] - 1 ) not in s : NEW_LINE INDENT j = arr [ i ] NEW_LINE while ( j in s ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT ans = max ( ans , j - arr [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE arr = [ 1 , 9 , 3 , 10 , 4 , 20 , 2 ] NEW_LINE print " Length β of β the β Longest β contiguous β subsequence β is β " , NEW_LINE print findLongestConseqSubseq ( arr , n ) NEW_LINE DEDENT |
Largest increasing subsequence of consecutive integers | Python3 implementation of longest continuous increasing subsequence Function for LIS ; Initialize result ; iterate through array and find end index of LIS and its Size ; print LIS size ; print LIS after setting start element ; Driver Code | def findLIS ( A , n ) : NEW_LINE INDENT hash = dict ( ) NEW_LINE LIS_size , LIS_index = 1 , 0 NEW_LINE hash [ A [ 0 ] ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if A [ i ] - 1 not in hash : NEW_LINE INDENT hash [ A [ i ] - 1 ] = 0 NEW_LINE DEDENT hash [ A [ i ] ] = hash [ A [ i ] - 1 ] + 1 NEW_LINE if LIS_size < hash [ A [ i ] ] : NEW_LINE INDENT LIS_size = hash [ A [ i ] ] NEW_LINE LIS_index = A [ i ] NEW_LINE DEDENT DEDENT print ( " LIS _ size β = " , LIS_size ) NEW_LINE print ( " LIS β : β " , end = " " ) NEW_LINE start = LIS_index - LIS_size + 1 NEW_LINE while start <= LIS_index : NEW_LINE INDENT print ( start , end = " β " ) NEW_LINE start += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 2 , 5 , 3 , 7 , 4 , 8 , 5 , 13 , 6 ] NEW_LINE n = len ( A ) NEW_LINE findLIS ( A , n ) NEW_LINE DEDENT |
Count subsets having distinct even numbers | function to count the required subsets ; inserting even numbers in the set ' us ' single copy of each number is retained ; counting distinct even numbers ; total count of required subsets ; Driver program | def countSubSets ( arr , n ) : NEW_LINE INDENT us = set ( ) NEW_LINE even_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] % 2 == 0 : NEW_LINE INDENT us . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT even_count = len ( us ) NEW_LINE return pow ( 2 , even_count ) - 1 NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 9 , 2 , 6 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Numbers β of β subset = " , countSubSets ( arr , n ) ) NEW_LINE |
Count distinct elements in every window of size k | Simple Python3 program to count distinct elements in every window of size k ; Counts distinct elements in window of size k ; Traverse the window ; Check if element arr [ i ] exists in arr [ 0. . i - 1 ] ; Counts distinct elements in all windows of size k ; Traverse through every window ; Driver Code | import math as mt NEW_LINE def countWindowDistinct ( win , k ) : NEW_LINE INDENT dist_count = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT j = 0 NEW_LINE while j < i : NEW_LINE INDENT if ( win [ i ] == win [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT if ( j == i ) : NEW_LINE INDENT dist_count += 1 NEW_LINE DEDENT DEDENT return dist_count NEW_LINE DEDENT def countDistinct ( arr , n , k ) : NEW_LINE INDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT print ( countWindowDistinct ( arr [ i : k + i ] , k ) ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 1 , 3 , 4 , 2 , 3 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE countDistinct ( arr , n , k ) NEW_LINE |
Iterative method to check if two trees are mirror of each other | Utility function to create and return a new node for a binary tree ; function to check whether the two binary trees are mirrors of each other or not ; iterative inorder traversal of 1 st tree and reverse inoder traversal of 2 nd tree ; if the corresponding nodes in the two traversal have different data values , then they are not mirrors of each other . ; if at any point one root becomes None and the other root is not None , then they are not mirrors . This condition verifies that structures of tree are mirrors of each other . ; we have visited the node and its left subtree . Now , it ' s β right β subtree ' s turn ; we have visited the node and its right subtree . Now , it ' s β left β subtree ' s turn ; both the trees have been completely traversed ; tress are mirrors of each other ; Driver Code ; 1 st binary tree formation 1 ; / \ ; 3 2 ; / \ ; 5 4 ; 2 nd binary tree formation 1 ; / \ ; 2 3 ; / \ ; 4 5 ; function cal | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def areMirrors ( root1 , root2 ) : NEW_LINE INDENT st1 = [ ] NEW_LINE st2 = [ ] NEW_LINE while ( 1 ) : NEW_LINE INDENT while ( root1 and root2 ) : NEW_LINE INDENT if ( root1 . data != root2 . data ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT st1 . append ( root1 ) NEW_LINE st2 . append ( root2 ) NEW_LINE root1 = root1 . left NEW_LINE root2 = root2 . right NEW_LINE DEDENT if ( not ( root1 == None and root2 == None ) ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT if ( not len ( st1 ) == 0 and not len ( st2 ) == 0 ) : NEW_LINE INDENT root1 = st1 [ - 1 ] NEW_LINE root2 = st2 [ - 1 ] NEW_LINE st1 . pop ( - 1 ) NEW_LINE st2 . pop ( - 1 ) NEW_LINE root1 = root1 . right NEW_LINE root2 = root2 . left NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 1 ) NEW_LINE root1 . left = newNode ( 3 ) NEW_LINE root1 . right = newNode ( 2 ) NEW_LINE root1 . right . left = newNode ( 5 ) NEW_LINE root1 . right . right = newNode ( 4 ) NEW_LINE root2 = newNode ( 1 ) NEW_LINE root2 . left = newNode ( 2 ) NEW_LINE root2 . right = newNode ( 3 ) NEW_LINE root2 . left . left = newNode ( 4 ) NEW_LINE root2 . left . right = newNode ( 5 ) NEW_LINE print ( areMirrors ( root1 , root2 ) ) NEW_LINE DEDENT |
Maximum score assigned to a subsequence of numerically consecutive and distinct array elements | ''Function to find the maximum score possible ; '' Base Case ; '' If previously occurred subproblem occurred ; '' Check if lastpicked element differs by 1 from the current element ; '' Calculate score by including the current element ; '' Calculate score by excluding the current element ; '' Return maximum score from the two possibilities ; ''Function to print maximum score ; '' DP array to store results ; '' Function call ; ''Driver Code ; '' Given arrays ; '' Function Call | def maximumSum ( a , b , n , index , lastpicked , dp ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ lastpicked + 1 ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ lastpicked + 1 ] NEW_LINE DEDENT option1 , option2 = 0 , 0 NEW_LINE if ( lastpicked == - 1 or a [ lastpicked ] != a [ index ] ) : NEW_LINE INDENT option1 = ( b [ index ] + maximumSum ( a , b , n , index + 1 , index , dp ) ) NEW_LINE DEDENT option2 = maximumSum ( a , b , n , index + 1 , lastpicked , dp ) NEW_LINE dp [ index ] [ lastpicked + 1 ] = max ( option1 , option2 ) NEW_LINE return dp [ index ] [ lastpicked + 1 ] NEW_LINE DEDENT def maximumPoints ( arr , brr , n ) : NEW_LINE INDENT index = 0 NEW_LINE lastPicked = - 1 NEW_LINE dp = [ [ - 1 for x in range ( n + 5 ) ] for y in range ( n + 5 ) ] NEW_LINE print ( maximumSum ( arr , brr , n , index , lastPicked , dp ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 3 , 1 ] NEW_LINE brr = [ - 1 , 2 , 10 , 20 , - 10 , - 9 ] NEW_LINE N = len ( arr ) NEW_LINE maximumPoints ( arr , brr , N ) NEW_LINE DEDENT |
Maximum possible sum of a window in an array such that elements of same window in other array are unique | Function to return maximum sum of window in B [ ] according to given constraints . ; Map is used to store elements and their counts . ; Initialize result ; calculating the maximum possible sum for each subarray containing unique elements . ; Remove all duplicate instances of A [ i ] in current window . ; Add current instance of A [ i ] to map and to current sum . ; Update result if current sum is more . ; Driver code | def returnMaxSum ( A , B , n ) : NEW_LINE INDENT mp = set ( ) NEW_LINE result = 0 NEW_LINE curr_sum = curr_begin = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT while A [ i ] in mp : NEW_LINE INDENT mp . remove ( A [ curr_begin ] ) NEW_LINE curr_sum -= B [ curr_begin ] NEW_LINE curr_begin += 1 NEW_LINE DEDENT mp . add ( A [ i ] ) NEW_LINE curr_sum += B [ i ] NEW_LINE result = max ( result , curr_sum ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 0 , 1 , 2 , 3 , 0 , 1 , 4 ] NEW_LINE B = [ 9 , 8 , 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( A ) NEW_LINE print ( returnMaxSum ( A , B , n ) ) NEW_LINE DEDENT |
Length of second longest sequence of consecutive 1 s in a binary array | ''Function to find maximum and second maximum length ; '' Initialise maximum length ; '' Initialise second maximum length ; '' Initialise count ; '' Iterate over the array ; '' If sequence ends ; '' Reset count ; '' Otherwise ; '' Increase length of current sequence ; '' Update maximum ; '' Traverse the given array ; '' If sequence continues ; '' Increase length of current sequence ; '' Update second max ; '' Reset count when 0 is found ; '' Print the result ; ''Driver Code ; '' Given array ; '' Function Call | def FindMax ( arr , N ) : NEW_LINE INDENT maxi = - 1 NEW_LINE maxi2 = - 1 NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE maxi = max ( maxi , count ) NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count > maxi2 and count < maxi ) : NEW_LINE INDENT maxi2 = count NEW_LINE DEDENT DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT count = 0 NEW_LINE DEDENT DEDENT maxi = max ( maxi , 0 ) NEW_LINE maxi2 = max ( maxi2 , 0 ) NEW_LINE print ( maxi2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 0 , 0 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE FindMax ( arr , N ) NEW_LINE DEDENT |
Minimum distance between any special pair in the given array | ''Python3 program for the above approach ; ''Function that finds the minimum difference between two vectors ; '' Find lower bound of the index ; '' Find two adjacent indices to take difference ; '' Return the result ; ''Function to find the minimum distance between index of special pairs ; '' Stores the index of each element in the array arr[] ; Store the indexes ; Get the unique values in list ; '' Take adjacent difference of same values ; '' Left index array ; '' Right index array ; '' Find the minimum gap between the two adjacent different values ; ''Driver Code ; '' Given array ; '' Function call | import sys NEW_LINE def mindist ( left , right ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( len ( left ) ) : NEW_LINE INDENT num = left [ i ] NEW_LINE index = right . index ( min ( [ i for i in right if num >= i ] ) ) NEW_LINE if ( index == 0 ) : NEW_LINE INDENT res = min ( res , abs ( num - right [ index ] ) ) NEW_LINE DEDENT elif ( index == len ( right ) ) : NEW_LINE INDENT res = min ( res , min ( abs ( num - right [ index - 1 ] ) , abs ( num - right [ index ] ) ) ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def specialPairs ( nums ) : NEW_LINE INDENT m = { } NEW_LINE vals = [ ] NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT m [ nums [ i ] ] = i NEW_LINE DEDENT for p in m : NEW_LINE INDENT vals . append ( p ) NEW_LINE DEDENT res = sys . maxsize NEW_LINE for i in range ( 1 , len ( vals ) ) : NEW_LINE INDENT vec = [ m [ vals [ i ] ] ] NEW_LINE for i in range ( 1 , len ( vec ) ) : NEW_LINE INDENT res = min ( res , abs ( vec [ i ] - vec [ i - 1 ] ) ) NEW_LINE DEDENT if ( i ) : NEW_LINE INDENT a = vals [ i ] NEW_LINE left = [ m [ a ] ] NEW_LINE b = vals [ i - 1 ] NEW_LINE right = [ m [ b ] ] NEW_LINE res = min ( res , mindist ( left , right ) ) + 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , - 10 , 5 , - 5 , 1 ] NEW_LINE print ( specialPairs ( arr ) ) NEW_LINE DEDENT |
Substring of length K having maximum frequency in the given string | ''Python3 program for the above approach ; ''Function that generates substring of length K that occurs maximum times ; '' Store the frequency of substrings ; '' Deque to maintain substrings window size K ; '' Update the frequency of the first subin the Map E="".join(list(D ; '' Remove the first character of the previous K length substring ; '' Traverse the string ; '' Insert the current character as last character of current substring ; '' Pop the first character of previous K length substring ; '' Find the subthat occurs maximum number of times print(M) ; '' Print the substring ; ''Driver Code ; '' Given string ; '' Given K size of substring ; '' Function call | from collections import deque , Counter , defaultdict NEW_LINE import sys NEW_LINE def maximumOccurringString ( s , K ) : NEW_LINE INDENT M = { } NEW_LINE D = deque ( ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT D . append ( s [ i ] ) NEW_LINE DEDENT M [ str ( " " . join ( list ( D ) ) ) ] = M . get ( str ( " " . join ( list ( D ) ) ) , 0 ) + 1 NEW_LINE D . popleft ( ) NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT D . append ( s [ j ] ) NEW_LINE M [ str ( " " . join ( list ( D ) ) ) ] = M . get ( str ( " " . join ( list ( D ) ) ) , 0 ) + 1 NEW_LINE D . popleft ( ) NEW_LINE DEDENT maxi = - sys . maxsize - 1 NEW_LINE ans = deque ( ) NEW_LINE for it in M : NEW_LINE INDENT if ( M [ it ] >= maxi ) : NEW_LINE INDENT maxi = M [ it ] NEW_LINE ans = it NEW_LINE DEDENT DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " bbbbbaaaaabbabababa " NEW_LINE K = 5 NEW_LINE maximumOccurringString ( s , K ) NEW_LINE DEDENT |
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree | ''Python3 program of the above approach ; ''Stores the nodes to be deleted ; ''Structure of a Tree node ; ''Function to find the min value of node for each level ; '' Count is used to diffentiate each level of the tree ; ''Function to check whether the nodes in the level below it are smaller by performing post order traversal ; '' Traverse the left subtree ; '' Traverse right subtree ; '' Check from minimum values computed at each level ; ''Function to print count of nodes from all lower levels having values less than the the nodes in the current level ; '' Stores the number of levels ; '' Stores the required count of nodes for each level ; ''Driver Code ; '' 4 / \ 3 5 / \ / \ 10 2 3 1 | from collections import deque NEW_LINE from sys import maxsize as INT_MAX NEW_LINE mp = dict ( ) NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def calculateMin ( root : Node , levelMin : list ) -> None : NEW_LINE INDENT qt = deque ( ) NEW_LINE qt . append ( root ) NEW_LINE count = 1 NEW_LINE min_v = INT_MAX NEW_LINE while ( qt ) : NEW_LINE INDENT temp = qt . popleft ( ) NEW_LINE min_v = min ( min_v , temp . key ) NEW_LINE if ( temp . left ) : NEW_LINE INDENT qt . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT qt . append ( temp . right ) NEW_LINE DEDENT count -= 1 NEW_LINE if ( count == 0 ) : NEW_LINE INDENT levelMin . append ( min_v ) NEW_LINE min_v = INT_MAX NEW_LINE count = len ( qt ) NEW_LINE DEDENT DEDENT DEDENT def findNodes ( root : Node , levelMin : list , levelResult : list , level : int ) -> None : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT findNodes ( root . left , levelMin , levelResult , level + 1 ) NEW_LINE findNodes ( root . right , levelMin , levelResult , level + 1 ) NEW_LINE for i in range ( level ) : NEW_LINE INDENT if ( root . key <= levelMin [ i ] ) : NEW_LINE INDENT levelResult [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def printNodes ( root : Node ) -> None : NEW_LINE INDENT levelMin = [ ] NEW_LINE calculateMin ( root , levelMin ) NEW_LINE numLevels = len ( levelMin ) NEW_LINE levelResult = [ 0 ] * numLevels NEW_LINE findNodes ( root , levelMin , levelResult , 0 ) NEW_LINE for i in range ( numLevels ) : NEW_LINE INDENT print ( levelResult [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 4 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 1 ) NEW_LINE root . left . left = Node ( 10 ) NEW_LINE root . left . right = Node ( 2 ) NEW_LINE printNodes ( root ) NEW_LINE DEDENT |
Design a data structure that supports insert , delete , search and getRandom in constant time | Python program to design a DS that supports following operations in Theta ( n ) time : a ) Insertb ) Deletec ) Searchd ) getRandom ; Class to represent the required data structure ; Constructor ( creates a list and a hash ) ; A resizable array ; A hash where keys are lists elements and values are indexes of the list ; A Theta ( 1 ) function to add an element to MyDS data structure ; If element is already present , then nothing has to be done ; Else put element at the end of the list ; Also put it into hash ; A Theta ( 1 ) function to remove an element from MyDS data structure ; Check if element is present ; If present , then remove element from hash ; Swap element with last element so that removal from the list can be done in O ( 1 ) time ; Remove last element ( This is O ( 1 ) ) ; Update hash table for new index of last element ; Returns a random element from MyDS ; Find a random index from 0 to size - 1 ; Return element at randomly picked index ; Returns index of element if element is present , otherwise none ; Driver Code | import random NEW_LINE class MyDS : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . arr = [ ] NEW_LINE self . hashd = { } NEW_LINE DEDENT def add ( self , x ) : NEW_LINE INDENT if x in self . hashd : NEW_LINE INDENT return NEW_LINE DEDENT s = len ( self . arr ) NEW_LINE self . arr . append ( x ) NEW_LINE self . hashd [ x ] = s NEW_LINE DEDENT def remove ( self , x ) : NEW_LINE INDENT index = self . hashd . get ( x , None ) NEW_LINE if index == None : NEW_LINE INDENT return NEW_LINE DEDENT del self . hashd [ x ] NEW_LINE size = len ( self . arr ) NEW_LINE last = self . arr [ size - 1 ] NEW_LINE self . arr [ index ] , self . arr [ size - 1 ] = self . arr [ size - 1 ] , self . arr [ index ] NEW_LINE del self . arr [ - 1 ] NEW_LINE self . hashd [ last ] = index NEW_LINE DEDENT def getRandom ( self ) : NEW_LINE INDENT index = random . randrange ( 0 , len ( self . arr ) ) NEW_LINE return self . arr [ index ] NEW_LINE DEDENT def search ( self , x ) : NEW_LINE INDENT return self . hashd . get ( x , None ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT ds = MyDS ( ) NEW_LINE ds . add ( 10 ) NEW_LINE ds . add ( 20 ) NEW_LINE ds . add ( 30 ) NEW_LINE ds . add ( 40 ) NEW_LINE print ( ds . search ( 30 ) ) NEW_LINE ds . remove ( 20 ) NEW_LINE ds . add ( 50 ) NEW_LINE print ( ds . search ( 50 ) ) NEW_LINE print ( ds . getRandom ( ) ) NEW_LINE DEDENT |
Count subarrays which contains both the maximum and minimum array element | ''Function to count subarray containing both maximum and minimum array elements ; '' If the length of the array is less than 2 ; '' Find the index of maximum element ; '' Find the index of minimum element ; '' If i > j, then swap the value of i and j ; '' Return the answer ; ''Function to return max_element index ; ''Function to return min_element index ; ''Driver Code ; '' Function call | def countSubArray ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT i = max_element ( arr ) ; NEW_LINE j = min_element ( arr ) ; NEW_LINE if ( i > j ) : NEW_LINE INDENT tmp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = tmp ; NEW_LINE DEDENT return ( i + 1 ) * ( n - j ) ; NEW_LINE DEDENT def max_element ( arr ) : NEW_LINE INDENT idx = 0 ; NEW_LINE max = arr [ 0 ] ; NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE idx = i ; NEW_LINE DEDENT DEDENT return idx ; NEW_LINE DEDENT def min_element ( arr ) : NEW_LINE INDENT idx = 0 ; NEW_LINE min = arr [ 0 ] ; NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] ; NEW_LINE idx = i ; NEW_LINE DEDENT DEDENT return idx ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countSubArray ( arr , n ) ) ; NEW_LINE DEDENT |
Count pairs of leaf nodes in a Binary Tree which are at most K distance apart | ''Structure of a Node ; ''Stores the count of required pairs ; ''Function to perform dfs to find pair of leaf nodes at most K distance apart ; '' Return empty array if node is None ; '' If node is a leaf node and return res ; '' Traverse to the left ; '' Traverse to the right ; '' Update the distance between left and right leaf node ; '' Count all pair of leaf nodes which are at most K distance apart ; '' Return res to parent node ; ''Driver Code ; '' 1 / \ 2 3 / 4 ; '' Given distance K ; '' Function call | class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT result = 0 NEW_LINE def dfs ( root , distance ) : NEW_LINE INDENT global result NEW_LINE if ( root == None ) : NEW_LINE INDENT res = [ 0 for i in range ( distance + 1 ) ] NEW_LINE return res NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT res = [ 0 for i in range ( distance + 1 ) ] NEW_LINE res [ 1 ] += 1 NEW_LINE return res NEW_LINE DEDENT left = dfs ( root . left , distance ) NEW_LINE right = dfs ( root . right , distance ) NEW_LINE res = [ 0 for i in range ( distance + 1 ) ] NEW_LINE i = len ( res ) - 2 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT res [ i + 1 ] = left [ i ] + right [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT for l in range ( 1 , len ( left ) ) : NEW_LINE INDENT for r in range ( len ( right ) ) : NEW_LINE INDENT if ( l + r <= distance ) : NEW_LINE INDENT result += left [ l ] * right [ r ] NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE K = 3 NEW_LINE dfs ( root , K ) NEW_LINE print ( result ) NEW_LINE DEDENT |
Maximum absolute difference between any two level sum in a N | Python3 program for the above approach ; Function to find the maximum absolute difference of level sum ; Create the adjacency list ; Initialize value of maximum and minimum level sum ; Do Level order traversal keeping track of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Update the maximum level sum value ; Update the minimum level sum value ; Return the result ; Driver Code ; Number of nodes and edges ; Edges of the N - ary tree ; Given cost ; Function call | from collections import deque NEW_LINE def maxAbsDiffLevelSum ( N , M , cost , Edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE DEDENT maxSum = cost [ 0 ] NEW_LINE minSum = cost [ 0 ] NEW_LINE q = deque ( ) NEW_LINE q . append ( 0 ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT count = len ( q ) NEW_LINE sum = 0 NEW_LINE while ( count ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE q . pop ( ) NEW_LINE sum = sum + cost [ temp ] NEW_LINE for i in adj [ temp ] : NEW_LINE INDENT q . append ( i ) NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT maxSum = max ( sum , maxSum ) NEW_LINE minSum = min ( sum , minSum ) NEW_LINE DEDENT print ( abs ( maxSum - minSum ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE M = 9 NEW_LINE Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] NEW_LINE cost = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] NEW_LINE maxAbsDiffLevelSum ( N , M , cost , Edges ) NEW_LINE DEDENT |
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray | Python3 program for the above approach ; Function to find the minimum cost of splitting the array into subarrays ; Get the maximum element ; dp will store the minimum cost upto index i ; Initialize the result array ; Initialise the first element ; Create the frequency array ; Update the frequency ; Counting the cost of the duplicate element ; Minimum cost of operation from 0 to j ; Total cost of the array ; Driver Code ; Given cost K ; Function call | import sys NEW_LINE def findMinCost ( a , k , n ) : NEW_LINE INDENT max_ele = max ( a ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] = sys . maxsize NEW_LINE DEDENT dp [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT freq = [ 0 ] * ( max_ele + 1 ) NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT freq [ a [ j ] ] += 1 NEW_LINE cost = 0 NEW_LINE for x in range ( 0 , max_ele + 1 ) : NEW_LINE INDENT cost += ( 0 if ( freq [ x ] == 1 ) else freq [ x ] ) NEW_LINE DEDENT dp [ j + 1 ] = min ( dp [ i ] + cost + k , dp [ j + 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 , 1 ] ; NEW_LINE K = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findMinCost ( arr , K , n ) ) ; NEW_LINE DEDENT |
Find subarray with given sum | Set 2 ( Handles Negative Numbers ) | Function to print subarray with sum as given sum ; create an empty map ; if curr_sum is equal to target sum we found a subarray starting from index 0 and ending at index i ; If curr_sum - sum already exists in map we have found a subarray with target sum ; if value is not present then add to hashmap ; If we reach here , then no subarray exists ; Driver program to test above function | def subArraySum ( arr , n , Sum ) : NEW_LINE INDENT Map = { } NEW_LINE curr_sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_sum = curr_sum + arr [ i ] NEW_LINE if curr_sum == Sum : NEW_LINE INDENT print ( " Sum β found β between β indexes β 0 β to " , i ) NEW_LINE return NEW_LINE DEDENT if ( curr_sum - Sum ) in Map : NEW_LINE INDENT print ( " Sum β found β between β indexes " , \ Map [ curr_sum - Sum ] + 1 , " to " , i ) NEW_LINE return NEW_LINE DEDENT Map [ curr_sum ] = i NEW_LINE DEDENT print ( " No β subarray β with β given β sum β exists " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 2 , - 2 , - 20 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE Sum = - 10 NEW_LINE subArraySum ( arr , n , Sum ) NEW_LINE DEDENT |
Write Code to Determine if Two Trees are Identical | A binary tree node has data , pointer to left child and a pointer to right child ; Given two trees , return true if they are structurally identical ; 1. Both empty ; 2. Both non - empty -> Compare them ; 3. one empty , one not -- false ; Driver program to test identicalTress function | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def identicalTrees ( a , b ) : NEW_LINE INDENT if a is None and b is None : NEW_LINE INDENT return True NEW_LINE DEDENT if a is not None and b is not None : NEW_LINE INDENT return ( ( a . data == b . data ) and identicalTrees ( a . left , b . left ) and identicalTrees ( a . right , b . right ) ) NEW_LINE DEDENT return False NEW_LINE DEDENT root1 = Node ( 1 ) NEW_LINE root2 = Node ( 1 ) NEW_LINE root1 . left = Node ( 2 ) NEW_LINE root1 . right = Node ( 3 ) NEW_LINE root1 . left . left = Node ( 4 ) NEW_LINE root1 . left . right = Node ( 5 ) NEW_LINE root2 . left = Node ( 2 ) NEW_LINE root2 . right = Node ( 3 ) NEW_LINE root2 . left . left = Node ( 4 ) NEW_LINE root2 . left . right = Node ( 5 ) NEW_LINE if identicalTrees ( root1 , root2 ) : NEW_LINE INDENT print " Both β trees β are β identical " NEW_LINE DEDENT else : NEW_LINE INDENT print " Trees β are β not β identical " NEW_LINE DEDENT |
Queries to find Kth greatest character in a range [ L , R ] from a string with updates | Maximum Size of a String ; Fenwick Tree to store the frequencies of 26 alphabets ; Size of the String . ; Function to update Fenwick Tree for Character c at index val ; Add val to current node Fenwick Tree ; Move index to parent node in update View ; Function to get sum of frequencies of character c till index ; Stores the sum ; Add current element of Fenwick tree to sum ; Move index to parent node in getSum View ; Function to create the Fenwick tree ; Function to print the kth largest character in the range of l to r ; Stores the count of characters ; Stores the required character ; Calculate frequency of C in the given range ; Increase count ; If count exceeds K ; Required character found ; Function to update character at pos by character s ; 0 based index system ; Driver Code ; Number of queries ; Construct the Fenwick Tree | maxn = 100005 NEW_LINE BITree = [ [ 0 for x in range ( maxn ) ] for y in range ( 26 ) ] NEW_LINE N = 0 NEW_LINE def update_BITree ( index , C , val ) : NEW_LINE INDENT while ( index <= N ) : NEW_LINE INDENT BITree [ ord ( C ) - ord ( ' a ' ) ] [ index ] += val NEW_LINE index += ( index & - index ) NEW_LINE DEDENT DEDENT def sum_BITree ( index , C ) : NEW_LINE INDENT s = 0 NEW_LINE while ( index ) : NEW_LINE INDENT s += BITree [ ord ( C ) - ord ( ' a ' ) ] [ index ] NEW_LINE index -= ( index & - index ) NEW_LINE DEDENT return s NEW_LINE DEDENT def buildTree ( st ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT update_BITree ( i , st [ i ] , 1 ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def printCharacter ( st , l , r , k ) : NEW_LINE INDENT count = 0 NEW_LINE for C in range ( ord ( ' z ' ) , ord ( ' a ' ) - 1 , - 1 ) : NEW_LINE INDENT times = ( sum_BITree ( r , chr ( C ) ) - sum_BITree ( l - 1 , chr ( C ) ) ) NEW_LINE count += times NEW_LINE if ( count >= k ) : NEW_LINE INDENT ans = chr ( C ) NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def updateTree ( st , pos , s ) : NEW_LINE INDENT index = pos ; NEW_LINE update_BITree ( index , st [ index ] , - 1 ) NEW_LINE st . replace ( st [ index ] , s , 1 ) NEW_LINE update_BITree ( index , s , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " abcddef " NEW_LINE N = len ( st ) NEW_LINE Q = 3 NEW_LINE buildTree ( st ) NEW_LINE print ( printCharacter ( st , 1 , 2 , 2 ) ) NEW_LINE updateTree ( st , 4 , ' g ' ) NEW_LINE print ( printCharacter ( st , 1 , 5 , 4 ) ) NEW_LINE DEDENT |
Generate a string from an array of alphanumeric strings based on given conditions | Function to generate required string ; To store the result ; Split name and number ; Stores the maximum number less than or equal to the length of name ; Check for number by parsing it to integer if it is greater than max number so far ; Check if no such number is found then we append X to the result . ; Otherwise ; Append max index of the name ; Return the final string ; Driver Code ; Function call | def generatePassword ( s , T ) : NEW_LINE INDENT result = [ ] NEW_LINE for currentString in s : NEW_LINE INDENT person = currentString . split ( " : " ) NEW_LINE name = person [ 0 ] NEW_LINE number = person [ 1 ] NEW_LINE n = len ( name ) NEW_LINE max = 0 NEW_LINE for i in range ( len ( number ) ) : NEW_LINE INDENT temp = int ( number [ i ] ) NEW_LINE if ( temp > max and temp <= n ) : NEW_LINE INDENT max = temp NEW_LINE DEDENT DEDENT if max == 0 : NEW_LINE INDENT result . append ( T ) NEW_LINE DEDENT else : NEW_LINE INDENT result . append ( name [ max - 1 ] ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ " Geeks : 89167" , " gfg : 68795" ] NEW_LINE T = ' X ' NEW_LINE print ( * generatePassword ( arr , T ) , sep = " " ) NEW_LINE |
Minimum number of edges required to be removed from an Undirected Graph to make it acyclic | Stores the adjacency list ; Stores if a vertex is visited or not ; Function to perform DFS Traversal to count the number and size of all connected components ; Mark the current node as visited ; Traverse the adjacency list of the current node ; For every unvisited node ; Recursive DFS Call ; Function to add undirected edge in the graph ; Function to calculate minimum number of edges to be removed ; Create Adjacency list ; Iterate over all the nodes ; Print the final count ; Driver Code | vec = [ [ ] for i in range ( 100001 ) ] NEW_LINE vis = [ False ] * 100001 NEW_LINE cc = 1 NEW_LINE def dfs ( node ) : NEW_LINE INDENT global cc NEW_LINE vis [ node ] = True NEW_LINE for x in vec [ node ] : NEW_LINE INDENT if ( vis [ x ] == 0 ) : NEW_LINE INDENT cc += 1 NEW_LINE dfs ( x ) NEW_LINE DEDENT DEDENT DEDENT def addEdge ( u , v ) : NEW_LINE INDENT vec [ u ] . append ( v ) NEW_LINE vec [ v ] . append ( u ) NEW_LINE DEDENT def minEdgeRemoved ( N , M , Edges ) : NEW_LINE INDENT global cc NEW_LINE for i in range ( M ) : NEW_LINE INDENT addEdge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) NEW_LINE DEDENT memset ( vis , false , sizeof ( vis ) ) NEW_LINE k = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( not vis [ i ] ) : NEW_LINE INDENT cc = 1 NEW_LINE dfs ( i ) NEW_LINE k += 1 NEW_LINE DEDENT DEDENT print ( M - N + k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE M = 2 NEW_LINE Edges = [ [ 1 , 2 ] , [ 2 , 3 ] ] NEW_LINE minEdgeRemoved ( N , M , Edges ) NEW_LINE DEDENT |
Group Shifted String | Total lowercase letter ; Method to a difference string for a given string . If string is " adf " then difference string will be " cb " ( first difference3 then difference 2 ) ; Representing the difference as char ; This string will be 1 less length than str ; Method for grouping shifted string ; map for storing indices of string which are in same group ; Iterating through map to print group ; Driver code | ALPHA = 26 NEW_LINE def getDiffString ( str ) : NEW_LINE INDENT shift = " " NEW_LINE for i in range ( 1 , len ( str ) ) : NEW_LINE INDENT dif = ( ord ( str [ i ] ) - ord ( str [ i - 1 ] ) ) NEW_LINE if ( dif < 0 ) : NEW_LINE INDENT dif += ALPHA NEW_LINE DEDENT shift += chr ( dif + ord ( ' a ' ) ) NEW_LINE DEDENT return shift NEW_LINE DEDENT def groupShiftedString ( str , n ) : NEW_LINE INDENT groupMap = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT diffStr = getDiffString ( str [ i ] ) NEW_LINE if diffStr not in groupMap : NEW_LINE INDENT groupMap [ diffStr ] = [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT groupMap [ diffStr ] . append ( i ) NEW_LINE DEDENT DEDENT for it in groupMap : NEW_LINE INDENT v = groupMap [ it ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT print ( str [ v [ i ] ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT str = [ " acd " , " dfg " , " wyz " , " yab " , " mop " , " bdfh " , " a " , " x " , " moqs " ] NEW_LINE n = len ( str ) NEW_LINE groupShiftedString ( str , n ) NEW_LINE |
Check if a Binary Tree consists of a pair of leaf nodes with sum K | Stores if a pair exists or not ; Struct binary tree node ; Function to check if a pair of leaf nodes exists with sum K ; Checks if root is NULL ; Checks if the current node is a leaf node ; Checks for a valid pair of leaf nodes ; Insert value of current node into the set ; Traverse left and right subtree ; Driver Code ; Construct binary tree ; Stores the leaf nodes | pairFound = False NEW_LINE S = set ( ) NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def pairSum ( root , target ) : NEW_LINE INDENT global pairFound NEW_LINE global S NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT temp = list ( S ) NEW_LINE if ( temp . count ( target - root . data ) ) : NEW_LINE INDENT print ( target - root . data , root . data ) NEW_LINE pairFound = True NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT S . add ( root . data ) NEW_LINE DEDENT DEDENT pairSum ( root . left , target ) NEW_LINE pairSum ( root . right , target ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE K = 13 NEW_LINE pairSum ( root , K ) NEW_LINE if ( pairFound == False ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT |
Maximum non | Function to prthe maximum rooks and their positions ; Marking the location of already placed rooks ; Print number of non - attacking rooks that can be placed ; To store the placed rook location ; Print lexographically smallest order ; Driver Code ; Size of board ; Number of rooks already placed ; Position of rooks ; Function call | def countRooks ( n , k , pos ) : NEW_LINE INDENT row = [ 0 for i in range ( n ) ] NEW_LINE col = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT row [ pos [ i ] [ 0 ] - 1 ] = 1 NEW_LINE col [ pos [ i ] [ 1 ] - 1 ] = 1 NEW_LINE DEDENT res = n - k NEW_LINE print ( res ) NEW_LINE ri = 0 NEW_LINE ci = 0 NEW_LINE while ( res > 0 ) : NEW_LINE INDENT while ( row [ ri ] == 1 ) : NEW_LINE INDENT ri += 1 NEW_LINE DEDENT while ( col [ ci ] == 1 ) : NEW_LINE INDENT ci += 1 NEW_LINE DEDENT print ( ( ri + 1 ) , ( ci + 1 ) ) NEW_LINE ri += 1 NEW_LINE ci += 1 NEW_LINE res -= 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE K = 2 NEW_LINE pos = [ [ 1 , 4 ] , [ 2 , 2 ] ] NEW_LINE countRooks ( N , K , pos ) NEW_LINE DEDENT |
Minimum insertions to form a palindrome with permutations allowed | Python3 program to find minimum number of insertions to make a string palindrome ; Function will return number of characters to be added ; To store str1ing length ; To store number of characters occurring odd number of times ; To store count of each character ; To store occurrence of each character ; To count characters with odd occurrence ; As one character can be odd return res - 1 but if str1ing is already palindrome return 0 ; Driver Code | import math as mt NEW_LINE def minInsertion ( tr1 ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = 0 NEW_LINE count = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( count [ i ] % 2 == 1 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT if ( res == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return res - 1 NEW_LINE DEDENT DEDENT str1 = " geeksforgeeks " NEW_LINE print ( minInsertion ( str1 ) ) NEW_LINE |
Check for Palindrome after every character replacement Query | Function to check if string is Palindrome or Not ; Takes two inputs for Q queries . For every query , it prints Yes if string becomes palindrome and No if not . ; Process all queries one by one ; query 1 : i1 = 3 , i2 = 0 , ch = ' e ' query 2 : i1 = 0 , i2 = 2 , ch = ' s ' replace character at index i1 & i2 with new ' ch ' ; check string is palindrome or not ; Driver Code | def isPalindrome ( string : list ) -> bool : NEW_LINE INDENT n = len ( string ) NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if string [ i ] != string [ n - 1 - i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def Query ( string : list , Q : int ) -> None : NEW_LINE INDENT for i in range ( Q ) : NEW_LINE INDENT inp = list ( input ( ) . split ( ) ) NEW_LINE i1 = int ( inp [ 0 ] ) NEW_LINE i2 = int ( inp [ 1 ] ) NEW_LINE ch = inp [ 2 ] NEW_LINE string [ i1 ] = string [ i2 ] = ch NEW_LINE if isPalindrome ( string ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = list ( " geeks " ) NEW_LINE Q = 2 NEW_LINE Query ( string , Q ) NEW_LINE DEDENT |
Generate a string which differs by only a single character from all given strings | Function to check if a given string differs by a single character from all the strings in an array ; Traverse over the strings ; Stores the count of characters differing from the strings ; If differs by more than one character ; Function to find the string which only differ at one position from the all given strings of the array ; Size of the array ; Length of a string ; Replace i - th character by all possible characters ; Check if it differs by a single character from all other strings ; If desired string is obtained ; Print the answer ; Driver Code ; Function call | def check ( ans , s , n , m ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if ( ans [ j ] != s [ i ] [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findString ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = len ( s [ 0 ] ) NEW_LINE ans = s [ 0 ] NEW_LINE flag = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT x = list ( ans ) NEW_LINE x [ i ] = chr ( j + ord ( ' a ' ) ) NEW_LINE if ( check ( x , s , n , m ) ) : NEW_LINE INDENT ans = x NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT else : NEW_LINE INDENT return ' ' . join ( ans ) NEW_LINE DEDENT DEDENT s = [ " geeks " , " teeds " ] NEW_LINE print ( findString ( s ) ) NEW_LINE |
Minimum increments of Non | Function to return to the minimum number of operations required to make the array non - decreasing ; Stores the count of operations ; If arr [ i ] > arr [ i + 1 ] , add arr [ i ] - arr [ i + 1 ] to the answer Otherwise , add 0 ; Driver Code | def getMinOps ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT ans += max ( arr [ i ] - arr [ i + 1 ] , 0 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 3 , 1 , 2 , 4 ] NEW_LINE print ( getMinOps ( arr ) ) NEW_LINE |
Maximum difference between frequency of two elements such that element having greater frequency is also greater | Python program to find maximum difference between frequency of any two element such that element with greater frequency is also greater in value . ; Return the maximum difference between frequencies of any two elements such that element with greater frequency is also greater in value . ; Finding the frequency of each element . ; finding difference such that element having greater frequency is also greater in value . ; Driver Code | from collections import defaultdict NEW_LINE def maxdiff ( arr , n ) : NEW_LINE INDENT freq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if freq [ arr [ i ] ] > freq [ arr [ j ] ] and arr [ i ] > arr [ j ] : NEW_LINE INDENT ans = max ( ans , freq [ arr [ i ] ] - freq [ arr [ j ] ] ) NEW_LINE DEDENT elif freq [ arr [ i ] ] < freq [ arr [ j ] ] and arr [ i ] < arr [ j ] : NEW_LINE INDENT ans = max ( ans , freq [ arr [ j ] ] - freq [ arr [ i ] ] ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 1 , 3 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxdiff ( arr , n ) ) NEW_LINE |
Maximum difference between frequency of two elements such that element having greater frequency is also greater | Return the maximum difference between frequencies of any two elements such that element with greater frequency is also greater in value . ; Finding the frequency of each element . ; Sorting the distinct element ; Iterate through all sorted distinct elements . For each distinct element , maintaining the element with minimum frequency than that element and also finding the maximum frequency difference ; Driven Program | def maxdiff ( arr , n ) : NEW_LINE INDENT freq = { } NEW_LINE dist = [ 0 ] * n NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in freq ) : NEW_LINE INDENT dist [ j ] = arr [ i ] NEW_LINE j += 1 NEW_LINE freq [ arr [ i ] ] = 0 NEW_LINE DEDENT if ( arr [ i ] in freq ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT DEDENT dist = dist [ : j ] NEW_LINE dist . sort ( ) NEW_LINE min_freq = n + 1 NEW_LINE ans = 0 NEW_LINE for i in range ( j ) : NEW_LINE INDENT cur_freq = freq [ dist [ i ] ] NEW_LINE ans = max ( ans , cur_freq - min_freq ) NEW_LINE min_freq = min ( min_freq , cur_freq ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 1 , 3 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxdiff ( arr , n ) ) NEW_LINE |
Maximum Sum possible by selecting X elements from a Matrix based on given conditions | Python3 program to implement the above approach ; Function to calculate the maximum possible sum by selecting X elements from the Matrix ; Generate prefix sum of the matrix ; Initialize [ , ] dp ; Maximum possible sum by selecting 0 elements from the first i rows ; If a single row is present ; If elements from the current row is not selected ; Iterate over all possible selections from current row ; Return maximum possible sum ; Driver Code | import sys NEW_LINE def maxSum ( grid ) : NEW_LINE INDENT prefsum = [ [ 0 for x in range ( m ) ] for y in range ( m ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for x in range ( m ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT prefsum [ i ] [ x ] = grid [ i ] [ x ] NEW_LINE DEDENT else : NEW_LINE INDENT prefsum [ i ] [ x ] = ( prefsum [ i ] [ x - 1 ] + grid [ i ] [ x ] ) NEW_LINE DEDENT DEDENT DEDENT dp = [ [ - sys . maxsize - 1 for x in range ( X + 1 ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 1 , min ( m , X ) ) : NEW_LINE INDENT dp [ 0 ] [ i ] = ( dp [ 0 ] [ i - 1 ] + grid [ 0 ] [ i - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , X + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE for x in range ( 1 , min ( j , m ) + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - x ] + prefsum [ i ] [ x - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n - 1 ] [ X ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 4 NEW_LINE X = 6 NEW_LINE grid = [ [ 3 , 2 , 6 , 1 ] , [ 1 , 9 , 2 , 4 ] , [ 4 , 1 , 3 , 9 ] , [ 3 , 8 , 2 , 1 ] ] NEW_LINE ans = maxSum ( grid ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Difference between highest and least frequencies in an array | Python3 code to find the difference between highest nd least frequencies ; sort the array ; checking consecutive elements ; Driver Code | def findDiff ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 0 ; max_count = 0 ; min_count = n NEW_LINE for i in range ( 0 , ( n - 1 ) ) : NEW_LINE INDENT if arr [ i ] == arr [ i + 1 ] : NEW_LINE INDENT count += 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT max_count = max ( max_count , count ) NEW_LINE min_count = min ( min_count , count ) NEW_LINE count = 0 NEW_LINE DEDENT DEDENT return max_count - min_count NEW_LINE DEDENT arr = [ 7 , 8 , 4 , 5 , 4 , 1 , 1 , 7 , 7 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findDiff ( arr , n ) ) NEW_LINE |