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_LIN...
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 le...
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 ( ro...
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...
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 cou...
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 ] == ar...
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 a...
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 ; ...
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...
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 ; requ...
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 DE...
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 ' ...
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...
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 ;...
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_...
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 '...
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 ) : NE...
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 [ ...
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 ...
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 DED...
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_L...
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 ...
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 i...
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 ...
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 cou...
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 ) :...
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 inc...
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 , ...
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 = ...
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 les...
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...
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 D...
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 min...
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 ...
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 eleme...
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 ] , "...
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_LIN...
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...
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 maximizeMango...
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 ...
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 ...
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 i...
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 ...
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 . appen...
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 taki...
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 ...
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 ...
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...
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 . ; T...
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_LIN...
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 t...
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 N...
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 ; '' Ins...
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 ...
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 . i...
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 t...
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 * ...
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 ele...
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_...
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 char...
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_LI...
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 ...
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 ...
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 e...
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 ) ) : N...
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 ; '' S...
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 ...
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 ,...
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 ra...
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_L...
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 = ' $ ' 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 ) ...
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 simil...
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...
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 retu...
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_LI...
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 = " ▁ " ) ...
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 len...
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 [...
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 vecto...
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 ) ...
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 , prin...
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 retur...
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 ...
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 ) :...
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 , ma...
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 ]...
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 retu...
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...
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_LI...
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 ...
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_L...
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_LI...
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 ; '' In...
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 )...
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 ; ...
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...
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 : NE...
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 ...
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_...
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...
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...
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 l...
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_LI...
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 ...
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...
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...
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 prim...
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 N...
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...
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 ) : ...
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 LI...
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 ,...
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 th...
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 =...
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 correspondi...
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 ...
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 cu...
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 [ la...
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 co...
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 m...
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 ...
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 ...
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 distanc...
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 ...
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 ...
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 ( " " . ...
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...
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 ...
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 ) ...
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...
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 ...
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 ) * ...
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...
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...
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...
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 ...
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 ;...
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_LIN...
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 s...
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 -...
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 identi...
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...
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 no...
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 DEDEN...
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 ...
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 tem...
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 t...
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 d...
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 ; ...
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...
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 curre...
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...
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...
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...
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 ch...
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 ] ...
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 ...
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 f...
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 ; Functio...
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 NE...
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 ...
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 [ ...
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 ele...
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 f...
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 ...
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 pre...
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...