text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Minimum Decrements on Subarrays required to reduce all Array elements to zero | Function to count the minimum number of subarrays that are required to be decremented by 1 ; Base case ; Initializing ans to first element ; For A [ i ] > A [ i - 1 ] , operation ( A [ i ] - A [ i - 1 ] ) is required ; Return the count ; Dr... | def min_operations ( A ) : NEW_LINE INDENT if len ( A ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = A [ 0 ] NEW_LINE for i in range ( 1 , len ( A ) ) : NEW_LINE INDENT if A [ i ] > A [ i - 1 ] : NEW_LINE INDENT ans += A [ i ] - A [ i - 1 ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 1 , 2 , 3 , 2 ... |
Difference between highest and least frequencies in an array | Python code to find the difference between highest and least frequencies ; Put all elements in a hash map ; Find counts of maximum and minimum frequent elements ; Driver code | from collections import defaultdict NEW_LINE def findDiff ( 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 max_count = 0 ; min_count = n NEW_LINE for key , values in mp . items ( ) : NEW_LINE INDENT max_count = max ( max_... |
Iterative function to check if two trees are identical | Iterative Python3 program to check if two trees are identical ; Utility function to create a new tree node ; Iterative method to find height of Binary Tree ; Return true if both trees are empty ; Return false if one is empty and other is not ; Create an empty que... | from queue import Queue NEW_LINE 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 areIdentical ( root1 , root2 ) : NEW_LINE INDENT if ( root1 and root2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i... |
Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph | Maximum number of nodes or vertices that can be present in the graph ; Store the parent of each vertex ; Stores the size of each set ; Function to initialize the parent of each vertices ; Function to find the representativ... | MAX_NODES = 100005 NEW_LINE parent = [ 0 for i in range ( MAX_NODES ) ] ; NEW_LINE size_set = [ 0 for i in range ( MAX_NODES ) ] ; NEW_LINE def make_set ( v ) : NEW_LINE INDENT parent [ v ] = v ; NEW_LINE size_set [ v ] = 1 ; NEW_LINE DEDENT def find_set ( v ) : NEW_LINE INDENT if ( v == parent [ v ] ) : NEW_LINE INDEN... |
Count of N | Function to calculate the total count of N - digit numbers such that the sum of digits at even positions and odd positions are divisible by A and B respectively ; For single digit numbers ; Largest possible number ; Count of possible odd digits ; Count of possible even digits ; Calculate total count of seq... | def count ( N , A , B ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 9 // B + 1 NEW_LINE DEDENT max_sum = 9 * N NEW_LINE odd_count = N // 2 + N % 2 NEW_LINE even_count = N - odd_count NEW_LINE dp = [ [ 0 for x in range ( max_sum + 1 ) ] for y in range ( even_count ) ] NEW_LINE for i in range ( 10 ) : NEW_LI... |
Maximum possible difference of two subsets of an array | Python3 find maximum difference of subset sum ; function for maximum subset diff ; if frequency of any element is two make both equal to zero ; Driver Code | import math NEW_LINE def maxDiff ( arr , n ) : NEW_LINE INDENT SubsetSum_1 = 0 NEW_LINE SubsetSum_2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT isSingleOccurance = True NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT isSingleOccurance = False NEW_LINE ... |
Count of all possible Paths in a Tree such that Node X does not appear before Node Y | Maximum number of nodes ; Vector to store the tree ; Function to perform DFS Traversal ; Mark the node as visited ; Initialize the subtree size of each node as 1 ; If the node is same as A ; Mark check_subtree [ node ] as true ; Othe... | NN = int ( 3e5 ) NEW_LINE G = [ ] NEW_LINE for i in range ( NN + 1 ) : NEW_LINE INDENT G . append ( [ ] ) NEW_LINE DEDENT def dfs ( node , A , subtree_size , visited , check_subtree ) : NEW_LINE INDENT visited [ node ] = True NEW_LINE subtree_size [ node ] = 1 NEW_LINE if ( node == A ) : NEW_LINE INDENT check_subtree [... |
Largest possible value of M not exceeding N having equal Bitwise OR and XOR between them | Python3 program to implement the above approach ; Function to find required number M ; Initialising m ; Finding the index of the most significant bit of N ; Calculating required number ; Driver Code | from math import log2 NEW_LINE def equalXORandOR ( n ) : NEW_LINE INDENT m = 0 NEW_LINE MSB = int ( log2 ( n ) ) NEW_LINE for i in range ( MSB + 1 ) : NEW_LINE INDENT if ( not ( n & ( 1 << i ) ) ) : NEW_LINE INDENT m += ( 1 << i ) NEW_LINE DEDENT DEDENT return m NEW_LINE DEDENT n = 14 NEW_LINE print ( equalXORandOR ( n... |
Maximum possible difference of two subsets of an array | function for maximum subset diff ; sort the array ; calculate the result ; check for last element ; return result ; Driver Code | def maxDiff ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) != abs ( arr [ i + 1 ] ) ) : NEW_LINE INDENT result += abs ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT pass NEW_LINE DEDENT DEDENT if ( arr [ n - 2 ] != arr [ ... |
Count of Palindromic Strings possible by swapping of a pair of Characters | Function to return the count of possible palindromic strings ; Stores the frequencies of each character ; Stores the length of the string ; Increase the number of swaps , the current character make with its previous occurrences ; Increase frequ... | def findNewString ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE freq = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT s = " aaabaaa " NEW_LINE p... |
Maximum possible difference of two subsets of an array | function for maximum subset diff ; construct hash for positive elements ; calculate subset sum for positive elements ; construct hash for negative elements ; calculate subset sum for negative elements ; Driver Code | def maxDiff ( arr , n ) : NEW_LINE INDENT hashPositive = dict ( ) NEW_LINE hashNegative = dict ( ) NEW_LINE SubsetSum_1 , SubsetSum_2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT hashPositive [ arr [ i ] ] = hashPositive . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT DEDEN... |
Change the given string according to the given conditions | Function to proofread the spells ; Loop to iterate over the characters of the string ; Push the current character c in the stack ; Check for Rule 1 ; Check for Rule 2 ; To store the resultant string ; Loop to iterate over the characters of stack ; Return the r... | def proofreadSpell ( str ) : NEW_LINE INDENT result = [ ] NEW_LINE for c in str : NEW_LINE INDENT result . append ( c ) NEW_LINE n = len ( result ) NEW_LINE if ( n >= 3 ) : NEW_LINE INDENT if ( result [ n - 1 ] == result [ n - 2 ] and result [ n - 1 ] == result [ n - 3 ] ) : NEW_LINE INDENT result . pop ( ) NEW_LINE DE... |
Smallest subarray with k distinct numbers | Prints the minimum range that contains exactly k distinct numbers . ; Consider every element as starting point . ; Find the smallest window starting with arr [ i ] and containing exactly k distinct elements . ; There are less than k distinct elements now , so no need to conti... | def minRange ( arr , n , k ) : NEW_LINE INDENT l = 0 NEW_LINE r = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT s . append ( arr [ j ] ) NEW_LINE if ( len ( s ) == k ) : NEW_LINE INDENT if ( ( j - i ) < ( r - l ) ) : NEW_LINE INDENT r = j NEW_LINE l = i NE... |
Smallest subarray with k distinct numbers | Python3 program to find the minimum range that contains exactly k distinct numbers . ; Prints the minimum range that contains exactly k distinct numbers . ; Initially left and right side is - 1 and - 1 , number of distinct elements are zero and range is n . ; Initialize right... | from collections import defaultdict NEW_LINE def minRange ( arr , n , k ) : NEW_LINE INDENT l , r = 0 , n NEW_LINE i = 0 NEW_LINE j = - 1 NEW_LINE hm = defaultdict ( lambda : 0 ) NEW_LINE while i < n : NEW_LINE INDENT while j < n : NEW_LINE INDENT j += 1 NEW_LINE if len ( hm ) < k and j < n : NEW_LINE INDENT hm [ arr [... |
Sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers | Function to calculate the sum ; map to keep a count of occurrences ; Traverse in the list from start to end number of times a [ i ] can be in a pair and to get the difference we subtract pre_sum . ; if the ( a [ i ] - 1 ) is present then subtract... | def sum ( a , n ) : NEW_LINE INDENT cnt = dict ( ) NEW_LINE ans = 0 NEW_LINE pre_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += ( i * a [ i ] ) - pre_sum NEW_LINE pre_sum += a [ i ] NEW_LINE if ( a [ i ] - 1 ) in cnt : NEW_LINE INDENT ans -= cnt [ a [ i ] - 1 ] NEW_LINE DEDENT if ( a [ i ] + 1 ) in cnt ... |
Minimum distance between the maximum and minimum element of a given Array | Python3 Program to implement the above approach ; Function to find the minimum distance between the minimum and the maximum element ; Stores the minimum and maximum array element ; Stores the most recently traversed indices of the minimum and t... | import sys NEW_LINE def minDistance ( a , n ) : NEW_LINE INDENT maximum = - 1 NEW_LINE minimum = sys . maxsize NEW_LINE min_index = - 1 NEW_LINE max_index = - 1 NEW_LINE min_dist = n + 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > maximum ) : NEW_LINE INDENT maximum = a [ i ] NEW_LINE DEDENT if ( a [... |
Kth diagonal from the top left of a given matrix | Function returns required diagonal ; Initialize values to prupper diagonals ; Initialize values to print lower diagonals ; Traverse the diagonals ; Print its contents ; Driver code | def printDiagonal ( K , N , M ) : NEW_LINE INDENT startrow , startcol = 0 , 0 NEW_LINE if K - 1 < N : NEW_LINE INDENT startrow = K - 1 NEW_LINE startcol = 0 NEW_LINE DEDENT else : NEW_LINE INDENT startrow = N - 1 NEW_LINE startcol = K - N NEW_LINE DEDENT while startrow >= 0 and startcol < N : NEW_LINE INDENT print ( M ... |
Longest substring that starts with X and ends with Y | Function returns length of longest substring starting with X and ending with Y ; Length of string ; Find the length of the string starting with X from the beginning ; Find the length of the string ending with Y from the end ; Longest substring ; Print the length ; ... | def longestSubstring ( str , X , Y ) : NEW_LINE INDENT N = len ( str ) NEW_LINE start = 0 NEW_LINE end = N - 1 NEW_LINE xPos = 0 NEW_LINE yPos = 0 NEW_LINE while ( True ) : NEW_LINE INDENT if ( str [ start ] == X ) : NEW_LINE INDENT xPos = start NEW_LINE break NEW_LINE DEDENT start += 1 NEW_LINE DEDENT while ( True ) :... |
Find parent of given node in a Binary Tree with given postorder traversal | Python implementation to find the parent of the given node ; Function to find the parent of the given node ; Check whether the given node is a root node . if it is then return - 1 because root node has no parent ; Loop till we found the given n... | import math NEW_LINE def findParent ( height , node ) : NEW_LINE INDENT start = 1 NEW_LINE end = pow ( 2 , height ) - 1 NEW_LINE if ( end == node ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT while ( node >= 1 ) : NEW_LINE INDENT end = end - 1 NEW_LINE mid = start + ( end - start ) // 2 NEW_LINE if ( mid == node or en... |
Replace every element with the smallest of the others | Python3 code for the above approach . ; There should be atleast two elements ; If current element is smaller than firstSmallest then update both firstSmallest and secondSmallest ; If arr [ i ] is in between firstSmallest and secondSmallest then update secondSmalle... | def ReplaceElements ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " Invalid β Input " ) NEW_LINE return NEW_LINE DEDENT firstSmallest = 10 ** 18 NEW_LINE secondSmallest = 10 ** 18 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < firstSmallest ) : NEW_LINE INDENT secondSmallest = f... |
Count subarrays with equal number of 1 ' s β and β 0' s | function to count subarrays with equal number of 1 ' s β and β 0' s ; ' um ' implemented as hash table to store frequency of values obtained through cumulative sum ; Traverse original array and compute cumulative sum and increase count by 1 for this sum in ' um ... | def countSubarrWithEqualZeroAndOne ( arr , n ) : NEW_LINE INDENT um = dict ( ) NEW_LINE curr_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sum += ( - 1 if ( arr [ i ] == 0 ) else arr [ i ] ) NEW_LINE if um . get ( curr_sum ) : NEW_LINE INDENT um [ curr_sum ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT um... |
Longest subarray having count of 1 s one more than count of 0 s | function to find the length of longest subarray having count of 1 ' s β one β more β than β count β of β 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as '-1 ; when subarray starts form index '0 ; mak... | def lenOfLongSubarr ( arr , n ) : NEW_LINE INDENT um = { i : 0 for i in range ( 10 ) } NEW_LINE sum = 0 NEW_LINE maxLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT sum += - 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT if ( sum == 1 ) : NEW_LINE INDENT max... |
Print all triplets in sorted array that form AP | Function to print all triplets in given sorted array that forms AP ; Use hash to find if there is a previous element with difference equal to arr [ j ] - arr [ i ] ; Driver code | def printAllAPTriplets ( arr , n ) : NEW_LINE INDENT s = [ ] ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT diff = arr [ j ] - arr [ i ] ; NEW_LINE if ( ( arr [ i ] - diff ) in arr ) : NEW_LINE INDENT print ( " { } β { } β { } " . format ( ( arr [ i ] - diff ) ,... |
Print all triplets in sorted array that form AP | Function to print all triplets in given sorted array that forms AP ; Search other two elements of AP with arr [ i ] as middle . ; if a triplet is found ; Since elements are distinct , arr [ k ] and arr [ j ] cannot form any more triplets with arr [ i ] ; If middle eleme... | def printAllAPTriplets ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT j = i - 1 NEW_LINE k = i + 1 NEW_LINE while ( j >= 0 and k < n ) : NEW_LINE INDENT if ( arr [ j ] + arr [ k ] == 2 * arr [ i ] ) : NEW_LINE INDENT print ( arr [ j ] , " " , arr [ i ] , " " , arr [ k ] ) NEW_LINE k += 1 N... |
Check if there is a root to leaf path with given sequence | Class of Node ; Util function ; If root is NULL or reached end of the array ; If current node is leaf ; If current node is equal to arr [ index ] this means that till this level path has been matched and remaining path can be either in left subtree or right su... | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def existPathUtil ( root , arr , n , index ) : NEW_LINE INDENT if not root or index == n : NEW_LINE INDENT return False NEW_LINE DEDENT if not root ... |
All unique triplets that sum up to a given value | Function to all find unique triplets without using extra space ; Sort the input array ; For handling the cases when no such triplets exits . ; Iterate over the array from start to n - 2. ; Index of the first element in remaining range . ; Index of the last element ; Se... | def findTriplets ( a , n , sum ) : NEW_LINE INDENT a . sort ( ) NEW_LINE flag = False NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( i == 0 or a [ i ] > a [ i - 1 ] ) : NEW_LINE INDENT start = i + 1 NEW_LINE end = n - 1 NEW_LINE target = sum - a [ i ] NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( star... |
Find the position of the given row in a 2 | Python implementation of the approach ; Function to find a row in the given matrix using linear search ; Assume that the current row matched with the given array ; If any element of the current row doesn 't match with the corresponding element of the given array ; Set match... | m , n = 6 , 4 ; NEW_LINE def linearCheck ( ar , arr ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT matched = True ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ar [ i ] [ j ] != arr [ j ] ) : NEW_LINE INDENT matched = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( matched ) : NEW_LINE INDENT ... |
Count number of triplets with product equal to given number | Method to count such triplets ; Consider all triplets and count if their product is equal to m ; Driver code | def countTriplets ( arr , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] * arr [ j ] * arr [ k ] == m ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DED... |
Count number of triplets with product equal to given number | Function to find the triplet ; Consider all pairs and check for a third number so their product is equal to product ; Check if current pair divides product or not If yes , then search for ( product / li [ i ] * li [ j ] ) ; Check if the third number is prese... | def countTriplets ( li , product ) : NEW_LINE INDENT flag = 0 NEW_LINE count = 0 NEW_LINE for i in range ( len ( li ) ) : NEW_LINE INDENT if li [ i ] != 0 and product % li [ i ] == 0 : NEW_LINE INDENT for j in range ( i + 1 , len ( li ) ) : NEW_LINE INDENT if li [ j ] != 0 and product % ( li [ j ] * li [ i ] ) == 0 : N... |
Count of index pairs with equal elements in an array | Return the number of pairs with equal values . ; for each index i and j ; finding the index with same value but different index . ; Driven Code | def countPairs ( arr , n ) : NEW_LINE INDENT ans = 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 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE ... |
Queries to answer the number of ones and zero to the left of given index | Function to pre - calculate the left [ ] array ; Iterate in the binary array ; Initialize the number of 1 and 0 ; Increase the count ; Driver code ; Queries ; Solve queries | def preCalculate ( binary , n , left ) : NEW_LINE INDENT count1 , count0 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left [ i ] [ 0 ] = count1 NEW_LINE left [ i ] [ 1 ] = count0 NEW_LINE if ( binary [ i ] ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT DEDE... |
Count of index pairs with equal elements in an array | Python3 program to count of index pairs with equal elements in an array . ; Return the number of pairs with equal values . ; Finding frequency of each number . ; Calculating pairs of each value . ; Driver Code | import math as mt NEW_LINE def countPairs ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for it in mp : N... |
Partition the array into three equal sum segments | This function returns true if the array can be divided into three equal sum segments ; Prefix Sum Array ; Suffix Sum Array ; Stores the total sum of the array ; We can also take pre [ pos2 - 1 ] - pre [ pos1 ] == total_sum / 3 here . ; Driver Code | def equiSumUtil ( arr , pos1 , pos2 ) : NEW_LINE INDENT n = len ( arr ) ; NEW_LINE pre = [ 0 ] * n ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE pre [ i ] = sum ; NEW_LINE DEDENT suf = [ 0 ] * n ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_L... |
Print cousins of a given node in Binary Tree | A utility function to create a new Binary Tree Node ; It returns level of the node if it is present in tree , otherwise returns 0. ; base cases ; If node is present in left subtree ; If node is not present in left subtree ; Prnodes at a given level such that sibling of nod... | class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def getLevel ( root , node , level ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root == node ) : NEW_LINE INDENT ... |
Leftmost and rightmost indices of the maximum and the minimum element of an array | Function to return the index of the rightmost minimum element from the array ; First element is the minimum in a sorted array ; While the elements are equal to the minimum update rightMin ; Final check whether there are any elements whi... | def getRightMin ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE rightMin = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] == min ) : NEW_LINE INDENT rightMin = i NEW_LINE DEDENT i *= 2 NEW_LINE DEDENT i = rightMin + 1 NEW_LINE while ( i < n and arr [ i ] == min ) : NEW_LINE INDENT rig... |
Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Sort the array ; Check if elements are consecutive or not . If not , update count ; Drivers code | def countNum ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] and arr [ i ] != arr [ i + 1 ] - 1 ) : NEW_LINE INDENT count += arr [ i + 1 ] - arr [ i ] - 1 ; NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [... |
Find the k smallest numbers after deleting given elements | Python3 program to find the k maximum number from the array after n deletions ; Find k maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Search i... | import math as mt NEW_LINE def findElementsAfterDel ( arr , m , dell , n , k ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if dell [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ dell [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ dell [ i ] ] = 1 NEW_LINE DEDENT DEDENT heap ... |
Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Make a hash of elements and store minimum and maximum element ; Traverse all elements from minimum to maximum and count if it is not in the hash ; Driver code | def countNum ( arr , n ) : NEW_LINE INDENT s = dict ( ) NEW_LINE count , maxm , minm = 0 , - 10 ** 9 , 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s [ arr [ i ] ] = 1 NEW_LINE if ( arr [ i ] < minm ) : NEW_LINE INDENT minm = arr [ i ] NEW_LINE DEDENT if ( arr [ i ] > maxm ) : NEW_LINE INDENT maxm = arr [ i ... |
Find minimum speed to finish all Jobs | Function to check if the person can do all jobs in H hours with speed K ; Function to return the minimum speed of person to complete all jobs ; If H < N it is not possible to complete all jobs as person can not move from one element to another during current hour ; Max element of... | def isPossible ( A , n , H , K ) : NEW_LINE INDENT time = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT time += ( A [ i ] - 1 ) // K + 1 NEW_LINE DEDENT return time <= H NEW_LINE DEDENT def minJobSpeed ( A , n , H ) : NEW_LINE INDENT if H < n : NEW_LINE INDENT return - 1 NEW_LINE DEDENT Max = max ( A ) NEW_LINE lo ... |
Number of anomalies in an array | Python3 program to implement the above approach ; Sort the array so that we can apply binary search . ; One by one check every element if it is anomaly or not using binary search . ; If arr [ i ] is not largest element and element just greater than it is within k , then return False . ... | def countAnomalies ( a , n , k ) : NEW_LINE INDENT a = sorted ( a ) ; NEW_LINE res = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT u = upper_bound ( a , 0 , n , a [ i ] ) ; NEW_LINE if ( u < n and a [ u ] - a [ i ] <= k ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT s = lower_bound ( a , 0 , n , a [ i ] ) ; NEW_L... |
Subarrays with distinct elements | Returns sum of lengths of all subarrays with distinct elements . ; For maintaining distinct elements . ; Initialize ending point and result ; Fix starting point ; Calculating and adding all possible length subarrays in arr [ i . . j ] ; Remove arr [ i ] as we pick new stating point fr... | def sumoflength ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE j = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( j < n and ( arr [ j ] not in s ) ) : NEW_LINE INDENT s . append ( arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT ans += ( ( j - i ) * ( j - i + 1 ) ) // 2 NEW_LINE s . remove ( arr ... |
Count subarrays having total distinct elements same as original array | Function to calculate distinct sub - array ; Count distinct elements in whole array ; Reset the container by removing all elements ; Use sliding window concept to find count of subarrays having k distinct elements . ; If window size equals to array... | def countDistictSubarray ( arr , n ) : NEW_LINE INDENT vis = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT vis [ arr [ i ] ] = 1 NEW_LINE DEDENT k = len ( vis ) NEW_LINE vid = dict ( ) NEW_LINE ans = 0 NEW_LINE right = 0 NEW_LINE window = 0 NEW_LINE for left in range ( n ) : NEW_LINE INDENT while ( right < n... |
Count subarrays with same even and odd elements | function that returns the count of subarrays that contain equal number of odd as well as even numbers ; initialize difference and answer with 0 ; initialize these auxiliary arrays with 0 ; since the difference is initially 0 , we have to initialize hash_positive [ 0 ] w... | def countSubarrays ( arr , n ) : NEW_LINE INDENT difference = 0 NEW_LINE ans = 0 NEW_LINE hash_positive = [ 0 ] * ( n + 1 ) NEW_LINE hash_negative = [ 0 ] * ( n + 1 ) NEW_LINE hash_positive [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 == 1 ) : NEW_LINE INDENT difference = difference + 1 ... |
Evaluation of Expression Tree | Class to represent the nodes of syntax tree ; This function receives a node of the syntax tree and recursively evaluate it ; empty tree ; leaf node ; evaluate left tree ; evaluate right tree ; check which operation to apply ; Driver function to test above problem | class node : NEW_LINE INDENT def __init__ ( self , value ) : NEW_LINE INDENT self . left = None NEW_LINE self . data = value NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def evaluateExpressionTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . left is None and roo... |
Minimum number of distinct elements after removing m items | Function to find distintc id 's ; Store the occurrence of ids ; Store into the list value as key and vice - versa ; Start removing elements from the beginning ; Remove if current value is less than or equal to mi ; Return the remaining size ; Driver code | def distinctIds ( arr , n , mi ) : NEW_LINE INDENT m = { } NEW_LINE v = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in m : NEW_LINE m [ arr [ i ] ] += 1 NEW_LINE else : NEW_LINE m [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in m : NEW_LINE INDENT v . append ( [ m [ i ] , i ] ) NEW_LI... |
Number of Larger Elements on right side in a string | Python3 program to find counts of right greater characters for every character . ; Driver code | def printGreaterCount ( str ) : NEW_LINE INDENT len__ = len ( str ) NEW_LINE right = [ 0 for i in range ( len__ ) ] NEW_LINE for i in range ( len__ ) : NEW_LINE INDENT for j in range ( i + 1 , len__ , 1 ) : NEW_LINE INDENT if ( str [ i ] < str [ j ] ) : NEW_LINE INDENT right [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT for... |
Maximum consecutive numbers present in an array | Python3 program to find largest consecutive numbers present in arr . ; We insert all the array elements into unordered set . ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; Then check ... | def findLongestConseqSubseq ( arr , n ) : NEW_LINE INDENT S = set ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT S . add ( arr [ i ] ) ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if S . __contains__ ( arr [ i ] ) : NEW_LINE INDENT j = arr [ i ] ; NEW_LINE while ( S . __contains__ ... |
N / 3 repeated number in an array with O ( 1 ) space | Python 3 program to find if any element appears more than n / 3. ; take the integers as the maximum value of integer hoping the integer would not be present in the array ; if this element is previously seen , increment count1 . ; if this element is previously seen ... | import sys NEW_LINE def appearsNBy3 ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE count2 = 0 NEW_LINE first = sys . maxsize NEW_LINE second = sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( first == arr [ i ] ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT elif ( second == arr [ i ] ) : NEW_L... |
Count pairs in array whose sum is divisible by 4 | Python3 code to count pairs whose sum is divisible by '4 ; Function to count pairs whose sum is divisible by '4 ; Create a frequency array to count occurrences of all remainders when divided by 4 ; Count occurrences of all remainders ; If both pairs are divisible by '4... | ' NEW_LINE ' NEW_LINE def count4Divisibiles ( arr , n ) : NEW_LINE INDENT freq = [ 0 , 0 , 0 , 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] % 4 ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT ans = freq [ 0 ] * ( freq [ 0 ] - 1 ) / 2 NEW_LINE ans += freq [ 2 ] * ( freq [ 2 ] - 1 ) / 2 NEW_LINE a... |
Find Sum of all unique sub | function for finding grandSum ; calculate cumulative sum of array cArray [ 0 ] will store sum of zero elements ; store all subarray sum in vector ; sort the vector ; mark all duplicate sub - array sum to zero ; calculate total sum ; return totalSum ; Drivers code | def findSubarraySum ( arr , n ) : NEW_LINE INDENT cArray = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT cArray [ i + 1 ] = cArray [ i ] + arr [ i ] NEW_LINE DEDENT subArrSum = [ ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 , 1 ) : NEW... |
Smallest number whose set bits are maximum in a given range | Python code to find number whose set bits are maximum among ' l ' and 'r ; Returns smallest number whose set bits are maximum in given range . ; Initialize the maximum count and final answer as ' num ' ; Traverse for every bit of ' i ' number ; If count is g... | ' NEW_LINE def countMaxSetBits ( left , right ) : NEW_LINE INDENT max_count = - 1 NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT temp = i NEW_LINE cnt = 0 NEW_LINE while temp : NEW_LINE INDENT if temp & 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT temp = temp >> 1 NEW_LINE DEDENT if cnt > max_count : NE... |
Find Sum of all unique sub | function for finding grandSum ; Go through all subarrays , compute sums and count occurrences of sums . ; Print all those Sums that appear once . ; Driver code | def findSubarraySum ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT Sum += arr [ j ] NEW_LINE m [ Sum ] = m . get ( Sum , 0 ) + 1 NEW_LINE DEDENT DEDENT for x in m : NEW_LINE INDENT if m [ x ] == 1 : ... |
Recaman 's sequence | Prints first n terms of Recaman sequence ; Create an array to store terms ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code | def recaman ( n ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE arr [ 0 ] = 0 NEW_LINE print ( arr [ 0 ] , end = " , β " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr = arr [ i - 1 ] - i NEW_LINE for j in range ( 0 , i ) : NEW_LINE INDENT if ( ( arr [ j ] == curr ) or curr < 0 ) : NEW_LINE INDENT curr = arr [... |
Print the longest leaf to leaf path in a Binary tree | Tree node structure used in the program ; Function to find height of a tree ; Update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; Save the root , this will help us finding the left and th... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def height ( root ) : NEW_LINE INDENT global ans , k , lh , rh , f NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left_height ... |
Recaman 's sequence | Prints first n terms of Recaman sequence ; Print first term and store it in a hash ; Print remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code | def recaman ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( 0 , " , " , end = ' ' ) NEW_LINE s = set ( [ ] ) NEW_LINE s . add ( 0 ) NEW_LINE prev = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr = prev - i NEW_LINE if ( curr < 0 or curr in s ) : NEW_LINE INDENT curr = ... |
Largest subset whose all elements are Fibonacci numbers | Prints largest subset of an array whose all elements are fibonacci numbers ; Find maximum element in arr [ ] ; Generate all Fibonacci numbers till max and store them in hash . ; Npw iterate through all numbers and quickly check for Fibonacci using hash . ; Drive... | def findFibSubset ( arr , n ) : NEW_LINE INDENT m = max ( arr ) NEW_LINE a = 0 NEW_LINE b = 1 NEW_LINE hash = [ ] NEW_LINE hash . append ( a ) NEW_LINE hash . append ( b ) NEW_LINE while ( b < m ) : NEW_LINE INDENT c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE hash . append ( b ) NEW_LINE DEDENT for i in range ( n )... |
Pairs of Amicable Numbers | Efficient Python3 program to count Amicable pairs in an array . ; Calculating the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; check if pair is ambicle ; This function prints count of amicable pairs present in the input array ; Map to store the numbers ; Itera... | import math NEW_LINE def sumOfDiv ( x ) : NEW_LINE INDENT sum = 1 ; NEW_LINE for i in range ( 2 , int ( math . sqrt ( x ) ) ) : NEW_LINE INDENT if x % i == 0 : NEW_LINE INDENT sum += i NEW_LINE if i != x / i : NEW_LINE INDENT sum += x / i NEW_LINE DEDENT DEDENT DEDENT return int ( sum ) ; NEW_LINE DEDENT def isAmbicle ... |
Minimum number of characters required to be removed such that every character occurs same number of times | Python3 program for the above approach ; Function to find minimum number of character removals required to make frequency of all distinct characters the same ; Stores the frequency of each character ; Traverse th... | import sys NEW_LINE def minimumDeletion ( s , n ) : NEW_LINE INDENT countMap = { } NEW_LINE for i in s : NEW_LINE INDENT countMap [ i ] = countMap . get ( i , 0 ) + 1 NEW_LINE DEDENT countMultiset = [ ] NEW_LINE for it in countMap : NEW_LINE INDENT countMultiset . append ( countMap [ it ] ) NEW_LINE DEDENT ans = sys . ... |
Calculate cost of visiting all array elements in increasing order | Function to calculate total cost of visiting array elements in increasing order ; Stores the pair of element and their positions ; Traverse the array arr [ ] ; Push the pair { arr [ i ] , i } in v ; Sort the vector in ascending order . ; Stores the tot... | def calculateDistance ( arr , N ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT v . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = 0 NEW_LINE last = 0 NEW_LINE for j in v : NEW_LINE INDENT ans += abs ( j [ 1 ] - last ) NEW_LINE last = j [ 1 ] NEW_LINE DEDENT return ... |
Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | Python 3 program of the above approach ; Function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; Traverse the array of strings ; C... | import math NEW_LINE def sortArr ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT s = str ( arr [ i ] ) NEW_LINE list1 = list ( s ) NEW_LINE list1 . sort ( reverse = True ) NEW_LINE s = ' ' . join ( list1 ) NEW_LINE arr [ i ] = int ( s ) NEW_LINE sr = int ( math . sqrt ( arr [ i ] ) ) NEW_LINE a = s... |
Minimize cost required to make all array elements greater than or equal to zero | Python3 program for the above approach ; Function to find the minimum cost to make all array of elements greater than or equal to 0 ; sort the array in ascending order ; stores the count to make current array element >= 0 ; stores the cos... | import sys NEW_LINE def mincost ( arr , N , X ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE cost = 0 NEW_LINE min_cost = sys . maxsize NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cost = abs ( arr [ i ] ) * x + ( sum - abs ( arr [ i ] ) * i ) NEW_LINE sum += ... |
Count arrays having at least K elements exceeding XOR of all given array elements by X given operations | Stores the final answer ; Utility function to count arrays having at least K elements exceeding XOR of all given array elements ; If no operations are left ; Stores the count of possible arrays ; Count array elemen... | ans = 0 NEW_LINE def countArraysUtil ( arr , X , K , xorVal ) : NEW_LINE INDENT global ans NEW_LINE if ( X == 0 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > xorVal ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt >= K ) : NEW_LINE INDENT ans += 1 NEW... |
Difference between maximum and minimum of a set of anagrams from an array | Python3 program for the above approach ; Utility function to find the hash value for each element of the given array ; Initialize an array with first 10 prime numbers ; Iterate over digits of N ; Update Hash Value ; Update N ; Function to find ... | import math NEW_LINE from collections import defaultdict NEW_LINE def hashFunction ( N ) : NEW_LINE INDENT prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 ] NEW_LINE value = 1 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT r = N % 10 NEW_LINE value = value * prime [ r ] NEW_LINE N = N // 10 NEW_LINE DEDENT return va... |
Maximum number of apples that can be eaten by a person | Function to find the maximum number of apples a person can eat such that the person eat at most one apple in a day . ; Store count of apples and number of days those apples are edible ; Stores indices of the array ; Stores count of days ; Stores maximum count of ... | def cntMaxApples ( apples , days ) : NEW_LINE INDENT pq = [ ] NEW_LINE i = 0 NEW_LINE n = len ( apples ) NEW_LINE total_apples = 0 NEW_LINE while ( i < n or len ( pq ) > 0 ) : NEW_LINE if ( i < n and apples [ i ] != 0 ) : NEW_LINE INDENT pq . append ( [ i + days [ i ] - 1 , apples [ i ] ] ) NEW_LINE pq . sort ( ) NEW_L... |
Maximum area rectangle by picking four sides from array | function for finding max area ; sort array in non - increasing order ; Initialize two sides of rectangle ; traverse through array ; if any element occurs twice store that as dimension ; return the product of dimensions ; Driver code | def findArea ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE dimension = [ 0 , 0 ] NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < n - 1 and j < 2 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT dimension [ j ] = arr [ i ] NEW_LINE j += 1 NEW_LINE i += 1 NEW_LINE DEDENT i... |
Maximum of sum of length of rectangles and squares formed by given sticks | Python3 implementation of the above approach ; Function to find the maximum of sum of lengths of rectangles and squares formed using given set of sticks ; Stores the count of frequencies of all the array elements ; Stores frequencies which are ... | from collections import Counter NEW_LINE def findSumLength ( arr , n ) : NEW_LINE INDENT freq = dict ( Counter ( arr ) ) NEW_LINE freq_2 = { } NEW_LINE for i in freq : NEW_LINE INDENT if freq [ i ] >= 2 : NEW_LINE INDENT freq_2 [ i ] = freq [ i ] NEW_LINE DEDENT DEDENT arr1 = [ ] NEW_LINE for i in freq_2 : NEW_LINE arr... |
Maximum area rectangle by picking four sides from array | function for finding max area ; traverse through array ; If this is first occurrence of arr [ i ] , simply insert and continue ; If this is second ( or more ) occurrence , update first and second maximum values . ; return the product of dimensions ; Driver Code | def findArea ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE first = 0 NEW_LINE second = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in s : NEW_LINE INDENT s . append ( arr [ i ] ) NEW_LINE continue NEW_LINE DEDENT if ( arr [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = arr [ i ... |
Print root to leaf paths without using recursion | Helper function that allocates a new node with the given data and None left and right pointers . ; Function to print root to leaf path for a leaf using parent nodes stored in map ; start from leaf node and keep on appending nodes into stack till root node is reached ; ... | 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 printTopToBottomPath ( curr , parent ) : NEW_LINE INDENT stk = [ ] NEW_LINE while ( curr ) : NEW_LINE INDENT stk . append ( curr ) NEW_LINE curr = paren... |
Game of replacing array elements | Function return which player win the game ; Create hash that will stores all distinct element ; Traverse an array element ; Driver code | def playGame ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT return 1 if len ( s ) % 2 == 0 else 2 NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Player " , playGame ( arr , n ) , " Wins " ) NEW_... |
Length of longest strict bitonic subsequence | function to find length of longest strict bitonic subsequence ; 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 / first element of that subsequence ; arrays to store the length of increasing and decrea... | def longLenStrictBitonicSub ( arr , n ) : NEW_LINE INDENT inc , dcr = dict ( ) , dict ( ) NEW_LINE len_inc , len_dcr = [ 0 ] * n , [ 0 ] * n NEW_LINE longLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT len = 0 NEW_LINE if inc . get ( arr [ i ] - 1 ) in inc . values ( ) : NEW_LINE INDENT len = inc . get ( arr [ ... |
Selection Sort VS Bubble Sort | ; Driver Code | def Selection_Sort ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT min_index = i NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] < arr [ min_index ] ) : NEW_LINE INDENT min_index = j NEW_LINE DEDENT DEDENT arr [ i ] , arr [ min_index ] = arr [ min_index ] , arr [ i ] NEW_... |
Last seen array element ( last appearance is earliest ) | Python3 program to find last seen element in an array . ; Returns last seen element in arr [ ] ; Store last occurrence index of every element ; Find an element in hash with minimum index value ; Driver code | import sys ; NEW_LINE def lastSeenElement ( a , n ) : NEW_LINE INDENT hash = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ a [ i ] ] = i NEW_LINE DEDENT res_ind = sys . maxsize NEW_LINE res = 0 NEW_LINE for x , y in hash . items ( ) : NEW_LINE INDENT if y < res_ind : NEW_LINE INDENT res_ind = y NEW_LINE re... |
Selection Sort VS Bubble Sort | ; Driver Code | def Bubble_Sort ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , n - i ) : NEW_LINE INDENT if ( arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ] NEW_LINE DEDENT DEDENT DEDENT return arr NEW_LINE DEDENT n = 5 NEW_LINE arr = [... |
Minimum cost required to connect all houses in a city | Python3 program for the above approach ; Utility function to find set of an element v using path compression technique ; If v is the parent ; Otherwise , recursively find its parent ; Function to perform union of the sets a and b ; Find parent of a and b ; If pare... | parent = [ 0 ] * 100 NEW_LINE size = [ 0 ] * 100 NEW_LINE def find_set ( v ) : NEW_LINE INDENT if ( v == parent [ v ] ) : NEW_LINE INDENT return v NEW_LINE DEDENT parent [ v ] = find_set ( parent [ v ] ) NEW_LINE return parent [ v ] NEW_LINE DEDENT def union_sets ( a , b ) : NEW_LINE INDENT a = find_set ( a ) NEW_LINE ... |
Lexicographically smallest subsequence possible by removing a character from given string | Function to find the lexicographically smallest subsequence of length N - 1 ; Store index of character to be deleted ; Traverse the String ; If ith character > ( i + 1 ) th character then store it ; If any character found in non... | def firstSubsequence ( s ) : NEW_LINE INDENT isMax = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] > s [ i + 1 ] ) : NEW_LINE INDENT isMax = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( isMax >= 0 ) : NEW_LINE INDENT s = s [ 0 : isMax ] + s [ isMax + 1 : len ( s ) ] NEW_LINE DEDENT s . rerase... |
Maximize product of array by replacing array elements with its sum or product with element from another array | Function to find the largest product of array A [ ] ; Base Case ; Store all the elements of the array A [ ] ; Sort the Array B [ ] ; Traverse the array B [ ] ; Pop minimum element ; Check which operation is p... | def largeProduct ( A , B , N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( A [ i ] ) NEW_LINE DEDENT B . sort ( ) NEW_LINE pq . sort ( reverse = True ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT minn = pq . pop ( ... |
Print all root to leaf paths with there relative positions | Python3 program to print the longest leaf to leaf path ; Tree node structure used in the program ; Prints given root to leafAllpaths with underscores ; Find the minimum horizontal distance value in current root to leafAllpaths ; Find minimum horizontal distan... | MAX_PATH_SIZE = 1000 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printPath ( size ) : NEW_LINE INDENT minimum_Hd = 10 ** 19 NEW_LINE p = [ ] NEW_LINE global Allpaths NEW_LINE for it ... |
Minimum steps required to rearrange given array to a power sequence of 2 | Function to calculate the minimum steps required to convert given array into a power sequence of 2 ; Sort the array in ascending order ; Calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; Return the answer ; Driver Co... | def minsteps ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += abs ( arr [ i ] - pow ( 2 , i ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 8 , 2 , 10 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minsteps ( arr , n ) ) NEW_LINE |
Block swap algorithm for array rotation | Wrapper over the recursive function leftRotateRec ( ) It left rotates arr by d . ; * Return If number of elements to be rotated is zero or equal to array size ; * If number of elements to be rotated is exactly half of array size ; If A is shorter ; If B is shorter ; function to... | def leftRotate ( arr , d , n ) : NEW_LINE INDENT leftRotateRec ( arr , 0 , d , n ) ; NEW_LINE DEDENT def leftRotateRec ( arr , i , d , n ) : NEW_LINE INDENT if ( d == 0 or d == n ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( n - d == d ) : NEW_LINE INDENT swap ( arr , i , n - d + i , d ) ; NEW_LINE return ; NEW_LIN... |
Cost required to empty a given array by repeated removal of maximum obtained by given operations | Function to find the total cost of removing all array elements ; Sort the array in descending order ; Stores the total cost ; Contribution of i - th greatest element to the cost ; Remove the element ; If negative ; Add to... | def findCost ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) NEW_LINE count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT p = a [ j ] - j NEW_LINE a [ j ] = 0 NEW_LINE if ( p < 0 ) : NEW_LINE INDENT p = 0 NEW_LINE continue NEW_LINE DEDENT count += p NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 1 ,... |
Block swap algorithm for array rotation | Python3 code for above implementation ; A is shorter ; B is shorter ; Finally , block swap A and B | def leftRotate ( arr , d , n ) : NEW_LINE INDENT if ( d == 0 or d == n ) : NEW_LINE INDENT return ; NEW_LINE DEDENT i = d NEW_LINE j = n - d NEW_LINE while ( i != j ) : NEW_LINE INDENT if ( i < j ) : NEW_LINE INDENT swap ( arr , d - i , d + j - i , i ) NEW_LINE j -= i NEW_LINE DEDENT else : NEW_LINE INDENT swap ( arr ,... |
Count of index pairs with equal elements in an array | Set 2 | Function that count the pairs having same elements in the array arr [ ] ; Hash map to keep track of occurences of elements ; Traverse the array arr [ ] ; Check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; Return the result ; Given array... | def countPairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE count = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in count : NEW_LINE INDENT ans += count [ arr [ i ] ] NEW_LINE DEDENT if arr [ i ] in count : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ arr... |
Maximize shortest path between given vertices by adding a single edge | Function that performs BFS Traversal ; Fill initially each distance as INF fill ( dist , dist + N , INF ) ; Perform BFS ; Traverse the current edges ; Update the distance ; Insert in queue ; Function that maximizes the shortest path between source ... | def bfs ( x , s ) : NEW_LINE INDENT global edges , dist NEW_LINE q = [ 0 for i in range ( 200000 ) ] NEW_LINE qh , qt = 0 , 0 NEW_LINE q [ qh ] = s NEW_LINE qh += 1 NEW_LINE dist [ x ] [ s ] = 0 NEW_LINE while ( qt < qh ) : NEW_LINE INDENT xx = q [ qt ] NEW_LINE qt += 1 NEW_LINE for y in edges [ xx ] : NEW_LINE INDENT ... |
Program to cyclically rotate an array by one | i and j pointing to first and last element respectively ; Driver function | def rotate ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while i != j : NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE i = i + 1 NEW_LINE pass NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given β array β is " ) NEW_LINE for i in range ( 0 , n... |
Minimum cost to empty Array where cost of removing an element is 2 ^ ( removed_count ) * arr [ i ] | Function to find the minimum cost of removing elements from the array ; Sorting in Increasing order ; Loop to find the minimum cost of removing elements ; Driver Code ; Function call | def removeElements ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += arr [ i ] * pow ( 2 , i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE arr = [ 3 , 1 , 2 , 3 ] NEW_LINE pr... |
Sorting boundary elements of a matrix | Python program for the above approach ; Appending border elements ; Sorting the list ; Printing first row with first N elements from A ; Printing N - 2 rows ; Print elements from last ; Print middle elements from original matrix ; Print elements from front ; Printing last row ; D... | def printMatrix ( grid , m , n ) : NEW_LINE INDENT A = [ ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if j == n - 1 or ( i == m - 1 ) or j == 0 or i == 0 : NEW_LINE INDENT A . append ( grid [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT A . sort ( ) NEW_LINE print ( * A [ : n ] ... |
Lexicographically largest string possible in one swap | Function to return the lexicographically largest string possible by swapping at most one character ; Initialize with - 1 for every character ; Keep updating the last occurrence of each character ; If a previously unvisited character occurs ; Stores the sorted stri... | def findLargest ( s ) : NEW_LINE INDENT Len = len ( s ) NEW_LINE loccur = [ - 1 for i in range ( 26 ) ] NEW_LINE for i in range ( Len - 1 , - 1 , - 1 ) : NEW_LINE INDENT chI = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( loccur [ chI ] == - 1 ) : NEW_LINE INDENT loccur [ chI ] = i NEW_LINE DEDENT DEDENT sorted_s = sor... |
Given a sorted and rotated array , find if there is a pair with a given sum | This function returns True if arr [ 0. . n - 1 ] has a pair with sum equals to x . ; Find the pivot element ; l is now index of smallest element ; r is now index of largest element ; Keep moving either l or r till they meet ; If we find a pai... | def pairInSortedRotated ( arr , n , x ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT l = ( i + 1 ) % n NEW_LINE r = i NEW_LINE while ( l != r ) : NEW_LINE INDENT if ( arr [ l ] + arr [ r ] == x ) : NEW_LINE INDENT retu... |
Given a sorted and rotated array , find if there is a pair with a given sum | This function returns count of number of pairs with sum equals to x . ; Find the pivot element . Pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; Variable to store count of num... | def pairsInSortedRotated ( arr , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] > arr [ i + 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT l = ( i + 1 ) % n NEW_LINE r = i NEW_LINE cnt = 0 NEW_LINE while ( l != r ) : NEW_LINE INDENT if arr [ l ] + arr [ r ] == x : NEW_LINE INDENT cnt ... |
Find maximum value of Sum ( i * arr [ i ] ) with only rotations on given array allowed | returns max possible value of Sum ( i * arr [ i ] ) ; stores sum of arr [ i ] ; stores sum of i * arr [ i ] ; initialize result ; try all rotations one by one and find the maximum rotation sum ; return result ; test maxsum ( arr ) ... | def maxSum ( arr ) : NEW_LINE INDENT arrSum = 0 NEW_LINE currVal = 0 NEW_LINE n = len ( arr ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT arrSum = arrSum + arr [ i ] NEW_LINE currVal = currVal + ( i * arr [ i ] ) NEW_LINE DEDENT maxVal = currVal NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT currVal = curr... |
Print the nodes at odd levels of a tree | Recursive Python3 program to print odd level nodes Utility method to create a node ; If empty tree ; If current node is of odd level ; Recur for children with isOdd switched . ; Driver code | 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 printOddNodes ( root , isOdd = True ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( isOdd ) : NEW_LINE INDENT prin... |
Maximum sum of i * arr [ i ] among all rotations of a given array | A Naive Python3 program to find maximum sum rotation ; Returns maximum value of i * arr [ i ] ; Initialize result ; Consider rotation beginning with i for all possible values of i . ; Initialize sum of current rotation ; Compute sum of all values . We ... | import sys NEW_LINE def maxSum ( arr , n ) : NEW_LINE INDENT res = - sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT index = int ( ( i + j ) % n ) NEW_LINE curr_sum += j * arr [ index ] NEW_LINE DEDENT res = max ( res , curr_sum ) NEW_LI... |
Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient Python3 program to compute maximum sum of i * arr [ i ] ; Compute sum of all array elements ; Compute sum of i * arr [ i ] for initial configuration . ; Initialize result ; Compute values for other iterations ; Compute next value using pre... | def maxSum ( arr , n ) : NEW_LINE INDENT cum_sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cum_sum += arr [ i ] NEW_LINE DEDENT curr_val = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_val += i * arr [ i ] NEW_LINE DEDENT res = curr_val NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT next... |
Find the Rotation Count in Rotated Sorted array | Returns count of rotations for an array which is first sorted in ascending order , then rotated ; We basically find index of minimum element ; Driver code | def countRotations ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( min > arr [ i ] ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE min_index = i NEW_LINE DEDENT DEDENT return min_index ; NEW_LINE DEDENT arr = [ 15 , 18 , 2 , 3 , 6 , 12 ] NEW_LINE n = len ( arr ) NEW_L... |
Find the Rotation Count in Rotated Sorted array | Returns count of rotations for an array which is first sorted in ascending order , then rotated ; This condition is needed to handle the case when array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum elemen... | def countRotations ( arr , low , high ) : NEW_LINE INDENT if ( high < low ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( high == low ) : NEW_LINE INDENT return low NEW_LINE DEDENT mid = low + ( high - low ) / 2 ; NEW_LINE mid = int ( mid ) NEW_LINE if ( mid < high and arr [ mid + 1 ] < arr [ mid ] ) : NEW_LINE INDEN... |
Quickly find multiple left rotations of an array | Set 1 | Fills temp with two copies of arr ; Store arr elements at i and i + n ; Function to left rotate an array k times ; Starting position of array after k rotations in temp will be k % n ; Print array after k rotations ; Driver program | def preprocess ( arr , n ) : NEW_LINE INDENT temp = [ None ] * ( 2 * n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp [ i ] = temp [ i + n ] = arr [ i ] NEW_LINE DEDENT return temp NEW_LINE DEDENT def leftRotate ( arr , n , k , temp ) : NEW_LINE INDENT start = k % n NEW_LINE for i in range ( start , start + n )... |
Arrange the array such that upon performing given operations an increasing order is obtained | Function to arrange array in such a way that after performing given operation We get increasing sorted array ; Size of given array ; Sort the given array ; Start erasing last element and place it at ith index ; While we reach... | def Desired_Array ( v ) : NEW_LINE INDENT n = len ( v ) NEW_LINE v . sort ( ) NEW_LINE i = n - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT p = v [ n - 1 ] NEW_LINE for j in range ( n - 1 , i - 1 , - 1 ) : NEW_LINE INDENT v [ j ] = v [ j - 1 ] NEW_LINE DEDENT v [ i ] = p NEW_LINE i -= 1 NEW_LINE DEDENT for x in v : NEW... |
Quickly find multiple left rotations of an array | Set 1 | Function to left rotate an array k times ; Print array after k rotations ; Driver Code | def leftRotate ( arr , n , k ) : NEW_LINE INDENT for i in range ( k , k + n ) : NEW_LINE INDENT print ( str ( arr [ i % n ] ) , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 5 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 ; NEW_LINE leftRotate ( arr , n , k ) NEW_LINE print ( ) NEW_LINE k = 3 ; NEW_LINE left... |
How to sort an array in a single loop ? | Function for Sorting the array using a single loop ; Finding the length of array 'arr ; Sorting using a single loop ; Checking the condition for two simultaneous elements of the array ; Swapping the elements . ; updating the value of j = - 1 so after getting updated for j ++ in... | def sortArrays ( arr ) : NEW_LINE ' NEW_LINE INDENT length = len ( arr ) NEW_LINE j = 0 NEW_LINE while j < length - 1 : NEW_LINE INDENT if ( arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ j + 1 ] NEW_LINE arr [ j + 1 ] = temp NEW_LINE j = - 1 NEW_LINE DEDENT j += 1 NEW_LINE DE... |
How to sort an array in a single loop ? | Function for Sorting the array using a single loop ; Sorting using a single loop ; Type Conversion of char to int . ; Comparing the ascii code . ; Swapping of the characters ; Declaring a String ; declaring character array ; copying the contents of the string to char array ; Pr... | def sortArrays ( arr , length ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < length - 1 ) : NEW_LINE INDENT d1 = arr [ j ] NEW_LINE d2 = arr [ j + 1 ] NEW_LINE if ( d1 > d2 ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ j + 1 ] NEW_LINE arr [ j + 1 ] = temp NEW_LINE j = - 1 NEW_LINE DEDENT j += 1 NEW_L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.