text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find the maximum element in an array which is first increasing and then decreasing | ; Base Case : Only one element is present in arr [ low . . high ] ; If there are two elements and first is greater then the first element is maximum ; If there are two elements and second is greater then the second element is maximum ; If we reach a point where arr [ mid ] is greater than both of its adjacent elements arr [ mid - 1 ] and arr [ mid + 1 ] , then arr [ mid ] is the maximum element ; If arr [ mid ] is greater than the next element and smaller than the previous element then maximum lies on left side of mid ; when arr [ mid ] is greater than arr [ mid - 1 ] and smaller than arr [ mid + 1 ] ; Driver program to check above functions
def findMaximum ( arr , low , high ) : NEW_LINE INDENT if low == high : NEW_LINE INDENT return arr [ low ] NEW_LINE DEDENT if high == low + 1 and arr [ low ] >= arr [ high ] : NEW_LINE INDENT return arr [ low ] ; NEW_LINE DEDENT if high == low + 1 and arr [ low ] < arr [ high ] : NEW_LINE INDENT return arr [ high ] NEW_LINE DEDENT mid = ( low + high ) // 2 NEW_LINE if arr [ mid ] > arr [ mid + 1 ] and arr [ mid ] > arr [ mid - 1 ] : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if arr [ mid ] > arr [ mid + 1 ] and arr [ mid ] < arr [ mid - 1 ] : NEW_LINE INDENT return findMaximum ( arr , low , mid - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return findMaximum ( arr , mid + 1 , high ) NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 50 , 10 , 9 , 7 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The ▁ maximum ▁ element ▁ is ▁ % d " % findMaximum ( arr , 0 , n - 1 ) ) NEW_LINE
Count smaller elements on right side | ; initialize all the counts in countSmaller array as 0 ; Utility function that prints out an array on a line ; Driver code
def constructLowerArray ( arr , countSmaller , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT countSmaller [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] < arr [ i ] ) : NEW_LINE INDENT countSmaller [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 12 , 10 , 5 , 4 , 2 , 20 , 6 , 1 , 0 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE low = [ 0 ] * n NEW_LINE constructLowerArray ( arr , low , n ) NEW_LINE printArray ( low , n ) NEW_LINE
Find the smallest positive number missing from an unsorted array | Set 1 | Utility function that puts all non - positive ( 0 and negative ) numbers on left side of arr [ ] and return count of such numbers ; increment count of non - positive integers ; Find the smallest positive missing number in an array that contains all positive integers ; Mark arr [ i ] as visited by making arr [ arr [ i ] - 1 ] negative . Note that 1 is subtracted because index start from 0 and positive numbers start from 1 ; Return the first index value at which is positive ; 1 is added because indexes start from 0 ; Find the smallest positive missing number in an array that contains both positive and negative integers ; First separate positive and negative numbers ; Shift the array and call findMissingPositive for positive part ; Driver code
def segregate ( arr , size ) : NEW_LINE INDENT j = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( arr [ i ] <= 0 ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return j NEW_LINE DEDENT def findMissingPositive ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) - 1 < size and arr [ abs ( arr [ i ] ) - 1 ] > 0 ) : NEW_LINE INDENT arr [ abs ( arr [ i ] ) - 1 ] = - arr [ abs ( arr [ i ] ) - 1 ] NEW_LINE DEDENT DEDENT for i in range ( size ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT return i + 1 NEW_LINE DEDENT DEDENT return size + 1 NEW_LINE DEDENT def findMissing ( arr , size ) : NEW_LINE INDENT shift = segregate ( arr , size ) NEW_LINE return findMissingPositive ( arr [ shift : ] , size - shift ) NEW_LINE DEDENT arr = [ 0 , 10 , 2 , - 10 , - 20 ] NEW_LINE arr_size = len ( arr ) NEW_LINE missing = findMissing ( arr , arr_size ) NEW_LINE print ( " The ▁ smallest ▁ positive ▁ missing ▁ number ▁ is ▁ " , missing ) NEW_LINE
Given an array of size n and a number k , find all elements that appear more than n / k times | Python3 implementation ; Function to find the number of array elements with frequency more than n / k times ; Calculating n / k ; Counting frequency of every element using Counter ; Traverse the map and print all the elements with occurrence more than n / k times ; Driver code
from collections import Counter NEW_LINE def printElements ( arr , n , k ) : NEW_LINE INDENT x = n // k NEW_LINE mp = Counter ( arr ) NEW_LINE for it in mp : NEW_LINE INDENT if mp [ it ] > x : NEW_LINE INDENT print ( it ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 1 , 2 , 2 , 3 , 5 , 4 , 2 , 2 , 3 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE printElements ( arr , n , k ) NEW_LINE
Maximum Sum Path in Two Arrays | This function returns the sum of elements on maximum path from beginning to end ; initialize indexes for ar1 [ ] and ar2 [ ] ; Initialize result and current sum through ar1 [ ] and ar2 [ ] ; Below 3 loops are similar to merge in merge sort ; Add elements of ar1 [ ] to sum1 ; Add elements of ar2 [ ] to sum2 ; we reached a common point ; Take the maximum of two sums and add to result ; update sum1 and sum2 to be considered fresh for next elements ; update i and j to move to next element in each array ; Add remaining elements of ar1 [ ] ; Add remaining elements of b [ ] ; Add maximum of two sums of remaining elements ; Driver code ; Function call
def maxPathSum ( ar1 , ar2 , m , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE result , sum1 , sum2 = 0 , 0 , 0 NEW_LINE while ( i < m and j < n ) : NEW_LINE INDENT if ar1 [ i ] < ar2 [ j ] : NEW_LINE INDENT sum1 += ar1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT elif ar1 [ i ] > ar2 [ j ] : NEW_LINE INDENT sum2 += ar2 [ j ] NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT result += max ( sum1 , sum2 ) + ar1 [ i ] NEW_LINE sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while i < m : NEW_LINE INDENT sum1 += ar1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT while j < n : NEW_LINE INDENT sum2 += ar2 [ j ] NEW_LINE j += 1 NEW_LINE DEDENT result += max ( sum1 , sum2 ) NEW_LINE return result NEW_LINE DEDENT ar1 = [ 2 , 3 , 7 , 10 , 12 , 15 , 30 , 34 ] NEW_LINE ar2 = [ 1 , 5 , 7 , 8 , 10 , 15 , 16 , 19 ] NEW_LINE m = len ( ar1 ) NEW_LINE n = len ( ar2 ) NEW_LINE print " Maximum ▁ sum ▁ path ▁ is " , maxPathSum ( ar1 , ar2 , m , n ) NEW_LINE
Smallest greater elements in whole array | Simple Python3 program to find smallest greater element in whole array for every element . ; Find the closest greater element for arr [ j ] in the entire array . ; Check if arr [ i ] is largest ; Driver code
def smallestGreater ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT diff = 1000 ; NEW_LINE closest = - 1 ; NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] and arr [ j ] - arr [ i ] < diff ) : NEW_LINE INDENT diff = arr [ j ] - arr [ i ] ; NEW_LINE closest = j ; NEW_LINE DEDENT DEDENT if ( closest == - 1 ) : NEW_LINE INDENT print ( " _ ▁ " , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " { } ▁ " . format ( arr [ closest ] ) , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT ar = [ 6 , 3 , 9 , 8 , 10 , 2 , 1 , 15 , 7 ] ; NEW_LINE n = len ( ar ) ; NEW_LINE smallestGreater ( ar , n ) ; NEW_LINE
Smallest greater elements in whole array | Efficient Python3 program to find smallest greater element in whole array for every element ; lowerbound function ; Driver code
def smallestGreater ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT newAr = [ ] NEW_LINE for p in s : NEW_LINE INDENT newAr . append ( p ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT temp = lowerBound ( newAr , 0 , len ( newAr ) , arr [ i ] ) NEW_LINE if ( temp < n ) : NEW_LINE INDENT print ( newAr [ temp ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " _ ▁ " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT def lowerBound ( vec , low , high , element ) : NEW_LINE INDENT array = [ 0 ] * ( len ( vec ) ) NEW_LINE k = 0 NEW_LINE for val in vec : NEW_LINE INDENT array [ k ] = val NEW_LINE k += 1 NEW_LINE DEDENT while ( low < high ) : NEW_LINE INDENT middle = low + int ( ( high - low ) / 2 ) NEW_LINE if ( element > array [ middle ] ) : NEW_LINE INDENT low = middle + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = middle NEW_LINE DEDENT DEDENT return low + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ 6 , 3 , 9 , 8 , 10 , 2 , 1 , 15 , 7 ] NEW_LINE n = len ( ar ) NEW_LINE smallestGreater ( ar , n ) NEW_LINE DEDENT
Online algorithm for checking palindrome in a stream | d is the number of characters in input alphabet ; q is a prime number used for evaluating Rabin Karp 's Rolling hash ; Length of input string ; A single character is always a palindrome ; Return if string has only one character ; Initialize first half reverse and second half for as firstr and second characters ; Now check for palindromes from second character onward ; If the hash values of ' firstr ' and ' second ' match , then only check individual characters ; Check if str [ 0. . i ] is palindrome using simple character by character match ; Calculate hash values for next iteration . Don 't calculate hash for next characters if this is the last character of string ; If i is even ( next i is odd ) ; Add next character after first half at beginning of 'firstr ; Add next character after second half at the end of second half . ; If next i is odd ( next i is even ) then we need not to change firstr , we need to remove first character of second and append a character to it . ; Driver program
d = 256 NEW_LINE q = 103 NEW_LINE def checkPalindromes ( string ) : NEW_LINE INDENT N = len ( string ) NEW_LINE print string [ 0 ] + " ▁ Yes " NEW_LINE if N == 1 : NEW_LINE INDENT return NEW_LINE DEDENT firstr = ord ( string [ 0 ] ) % q NEW_LINE second = ord ( string [ 1 ] ) % q NEW_LINE h = 1 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE for i in xrange ( 1 , N ) : NEW_LINE INDENT if firstr == second : NEW_LINE INDENT for j in xrange ( 0 , i / 2 ) : NEW_LINE INDENT if string [ j ] != string [ i - j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT j += 1 NEW_LINE if j == i / 2 : NEW_LINE INDENT print string [ i ] + " ▁ Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print string [ i ] + " ▁ No " NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print string [ i ] + " ▁ No " NEW_LINE DEDENT if i != N - 1 : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT h = ( h * d ) % q NEW_LINE firstr = ( firstr + h * ord ( string [ i / 2 ] ) ) % q NEW_LINE second = ( second * d + ord ( string [ i + 1 ] ) ) % q NEW_LINE DEDENT else : NEW_LINE INDENT second = ( d * ( second + q - ord ( string [ ( i + 1 ) / 2 ] ) * h ) % q + ord ( string [ i + 1 ] ) ) % q NEW_LINE DEDENT DEDENT DEDENT DEDENT txt = " aabaacaabaa " NEW_LINE checkPalindromes ( txt ) NEW_LINE
Find zeroes to be flipped so that number of consecutive 1 's is maximized | m is maximum of number zeroes allowed to flip , n is size of array ; Left and right indexes of current window ; Left index and size of the widest window ; Count of zeroes in current window ; While right boundary of current window doesn 't cross right end ; If zero count of current window is less than m , widen the window toward right ; If zero count of current window is more than m , reduce the window from left ; Updqate widest window if this window size is more ; Print positions of zeroes in the widest window ; Driver program
def findZeroes ( arr , n , m ) : NEW_LINE INDENT wL = wR = 0 NEW_LINE bestL = bestWindow = 0 NEW_LINE zeroCount = 0 NEW_LINE while wR < n : NEW_LINE INDENT if zeroCount <= m : NEW_LINE INDENT if arr [ wR ] == 0 : NEW_LINE INDENT zeroCount += 1 NEW_LINE DEDENT wR += 1 NEW_LINE DEDENT if zeroCount > m : NEW_LINE INDENT if arr [ wL ] == 0 : NEW_LINE INDENT zeroCount -= 1 NEW_LINE DEDENT wL += 1 NEW_LINE DEDENT if ( wR - wL > bestWindow ) and ( zeroCount <= m ) : NEW_LINE INDENT bestWindow = wR - wL NEW_LINE bestL = wL NEW_LINE DEDENT DEDENT for i in range ( 0 , bestWindow ) : NEW_LINE INDENT if arr [ bestL + i ] == 0 : NEW_LINE INDENT print ( bestL + i , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE m = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( " Indexes ▁ of ▁ zeroes ▁ to ▁ be ▁ flipped ▁ are " , end = " ▁ " ) NEW_LINE findZeroes ( arr , n , m ) NEW_LINE
Count Strictly Increasing Subarrays | Python3 program to count number of strictly increasing subarrays ; Initialize count of subarrays as 0 ; Pick starting point ; Pick ending point ; If subarray arr [ i . . j ] is not strictly increasing , then subarrays after it , i . e . , arr [ i . . j + 1 ] , arr [ i . . j + 2 ] , ... . cannot be strictly increasing ; Driver code
def countIncreasing ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ j ] > arr [ j - 1 ] : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Count ▁ of ▁ strictly ▁ increasing ▁ subarrays ▁ is " , countIncreasing ( arr , n ) ) NEW_LINE
Count Strictly Increasing Subarrays | Python3 program to count number of strictlyincreasing subarrays in O ( n ) time . ; Initialize result ; Initialize length of current increasing subarray ; Traverse through the array ; If arr [ i + 1 ] is greater than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver program
def countIncreasing ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE len = 1 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if arr [ i + 1 ] > arr [ i ] : NEW_LINE INDENT len += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += ( ( ( len - 1 ) * len ) / 2 ) NEW_LINE len = 1 NEW_LINE DEDENT DEDENT if len > 1 : NEW_LINE INDENT cnt += ( ( ( len - 1 ) * len ) / 2 ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Count ▁ of ▁ strictly ▁ increasing ▁ subarrays ▁ is " , int ( countIncreasing ( arr , n ) ) ) NEW_LINE
Maximum difference between group of k | utility function for array sum ; function for finding maximum group difference of array ; sort the array ; find array sum ; difference for k - smallest diff1 = ( arraysum - k_smallest ) - k_smallest ; reverse array for finding sum 0f 1 st k - largest ; difference for k - largest diff2 = ( arraysum - k_largest ) - k_largest ; return maximum difference value ; Driver Code
def arraySum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def maxDiff ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arraysum = arraySum ( arr , n ) NEW_LINE diff1 = abs ( arraysum - 2 * arraySum ( arr , k ) ) NEW_LINE arr . reverse ( ) NEW_LINE diff2 = abs ( arraysum - 2 * arraySum ( arr , k ) ) NEW_LINE return ( max ( diff1 , diff2 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 7 , 4 , 8 , - 1 , 5 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Maximum ▁ Difference ▁ = " , maxDiff ( arr , n , k ) ) NEW_LINE DEDENT
Minimum number of elements to add to make median equals x | Returns count of elements to be added to make median x . This function assumes that a [ ] has enough extra space . ; to sort the array in increasing order . ; Driver code
def minNumber ( a , n , x ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE k = 0 NEW_LINE while ( a [ int ( ( n - 1 ) / 2 ) ] != x ) : NEW_LINE INDENT a [ n - 1 ] = x NEW_LINE n += 1 NEW_LINE a . sort ( reverse = False ) NEW_LINE k += 1 NEW_LINE DEDENT return k NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 10 NEW_LINE a = [ 10 , 20 , 30 ] NEW_LINE n = 3 NEW_LINE print ( minNumber ( a , n , x ) ) NEW_LINE DEDENT
Minimum number of elements to add to make median equals x | Python3 program to find minimum number of elements to add so that its median equals x . ; no . of elements equals to x , that is , e . ; no . of elements greater than x , that is , h . ; no . of elements smaller than x , that is , l . ; subtract the no . of elements that are equal to x . ; Driver code
def minNumber ( a , n , x ) : NEW_LINE INDENT l = 0 NEW_LINE h = 0 NEW_LINE e = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] == x : NEW_LINE INDENT e += 1 NEW_LINE DEDENT elif a [ i ] > x : NEW_LINE INDENT h += 1 NEW_LINE DEDENT elif a [ i ] < x : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT ans = 0 ; NEW_LINE if l > h : NEW_LINE INDENT ans = l - h NEW_LINE DEDENT elif l < h : NEW_LINE INDENT ans = h - l - 1 ; NEW_LINE DEDENT return ans + 1 - e NEW_LINE DEDENT x = 10 NEW_LINE a = [ 10 , 20 , 30 ] NEW_LINE n = len ( a ) NEW_LINE print ( minNumber ( a , n , x ) ) NEW_LINE
Find whether a subarray is in form of a mountain or not | Utility method to construct left and right array ; initialize first left index as that index only ; if current value is greater than previous , update last increasing ; initialize last right index as that index only ; if current value is greater than next , update first decreasing ; method returns true if arr [ L . . R ] is in mountain form ; return true only if right at starting range is greater than left at ending range ; Driver code
def preprocess ( arr , N , left , right ) : NEW_LINE INDENT left [ 0 ] = 0 NEW_LINE lastIncr = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT lastIncr = i NEW_LINE DEDENT left [ i ] = lastIncr NEW_LINE DEDENT right [ N - 1 ] = N - 1 NEW_LINE firstDecr = N - 1 NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT firstDecr = i NEW_LINE DEDENT right [ i ] = firstDecr NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT def isSubarrayMountainForm ( arr , left , right , L , R ) : NEW_LINE INDENT return ( right [ L ] >= left [ R ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 2 , 4 , 4 , 6 , 3 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE left = [ 0 for i in range ( N ) ] NEW_LINE right = [ 0 for i in range ( N ) ] NEW_LINE preprocess ( arr , N , left , right ) NEW_LINE L = 0 NEW_LINE R = 2 NEW_LINE if ( isSubarrayMountainForm ( arr , left , right , L , R ) ) : NEW_LINE INDENT print ( " Subarray ▁ is ▁ in ▁ mountain ▁ form " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Subarray ▁ is ▁ not ▁ in ▁ mountain ▁ form " ) NEW_LINE DEDENT L = 1 NEW_LINE R = 3 NEW_LINE if ( isSubarrayMountainForm ( arr , left , right , L , R ) ) : NEW_LINE INDENT print ( " Subarray ▁ is ▁ in ▁ mountain ▁ form " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Subarray ▁ is ▁ not ▁ in ▁ mountain ▁ form " ) NEW_LINE DEDENT DEDENT
Number of primes in a subarray ( with updates ) | Python3 program to find number of prime numbers in a subarray and performing updates ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; A utility function to get the middle index from corner indexes . ; A recursive function to get the number of primes in a given range of array indexes . The following are parameters for this function . st -- > Pointer to segment tree index -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node , i . e . , st [ index ] qs & qe -- > Starting and ending indexes of query range ; If segment of this node is a part of given range , then return the number of primes in the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; A recursive function to update the nodes which have the given index in their range . The following are parameters st , si , ss and se are same as getSumUtil ( ) i -- > index of the element to be updated . This index is in input array . diff -- > Value to be added to all nodes which have i in range ; Base Case : If the input index lies outside the range of this segment ; If the input index is in range of this node , then update the value of the node and its children ; The function to update a value in input array and segment tree . It uses updateValueUtil ( ) to update the value in segment tree ; Check for erroneous input index ; Update the value in array ; Case 1 : Old and new values both are primes ; Case 2 : Old and new values both non primes ; Case 3 : Old value was prime , new value is non prime ; Case 4 : Old value was non prime , new_val is prime ; Update the values of nodes in segment tree ; Return number of primes in range from index qs ( query start ) to qe ( query end ) . It mainly uses queryPrimesUtil ( ) ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , check if it is prime then store 1 in the segment tree else store 0 and return ; if arr [ ss ] is prime ; If there are more than one elements , then recur for left and right subtrees and store the sum of the two values in this node ; Function to construct segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Height of segment tree ; Maximum size of segment tree ; Fill the allocated memory st ; Return the constructed segment tree ; Driver code ; Preprocess all primes till MAX . Create a boolean array " isPrime [ 0 . . MAX ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Build segment tree from given array ; Query 1 : Query ( start = 0 , end = 4 ) ; Query 2 : Update ( i = 3 , x = 6 ) , i . e Update a [ i ] to x ; Query 3 : Query ( start = 0 , end = 4 )
from math import ceil , floor , log NEW_LINE MAX = 1000 NEW_LINE def sieveOfEratosthenes ( isPrime ) : NEW_LINE INDENT isPrime [ 1 ] = False NEW_LINE for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if p * p > MAX : NEW_LINE INDENT break NEW_LINE DEDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , MAX + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def getMid ( s , e ) : NEW_LINE INDENT return s + ( e - s ) // 2 NEW_LINE DEDENT def queryPrimesUtil ( st , ss , se , qs , qe , index ) : NEW_LINE INDENT if ( qs <= ss and qe >= se ) : NEW_LINE INDENT return st [ index ] NEW_LINE DEDENT if ( se < qs or ss > qe ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE return queryPrimesUtil ( st , ss , mid , qs , qe , 2 * index + 1 ) + queryPrimesUtil ( st , mid + 1 , se , qs , qe , 2 * index + 2 ) NEW_LINE DEDENT def updateValueUtil ( st , ss , se , i , diff , si ) : NEW_LINE INDENT if ( i < ss or i > se ) : NEW_LINE INDENT return NEW_LINE DEDENT st [ si ] = st [ si ] + diff NEW_LINE if ( se != ss ) : NEW_LINE INDENT mid = getMid ( ss , se ) NEW_LINE updateValueUtil ( st , ss , mid , i , diff , 2 * si + 1 ) NEW_LINE updateValueUtil ( st , mid + 1 , se , i , diff , 2 * si + 2 ) NEW_LINE DEDENT DEDENT def updateValue ( arr , st , n , i , new_val , isPrime ) : NEW_LINE INDENT if ( i < 0 or i > n - 1 ) : NEW_LINE INDENT printf ( " Invalid ▁ Input " ) NEW_LINE return NEW_LINE DEDENT diff , oldValue = 0 , 0 NEW_LINE oldValue = arr [ i ] NEW_LINE arr [ i ] = new_val NEW_LINE if ( isPrime [ oldValue ] and isPrime [ new_val ] ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ( not isPrime [ oldValue ] ) and ( not isPrime [ new_val ] ) ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( isPrime [ oldValue ] and not isPrime [ new_val ] ) : NEW_LINE INDENT diff = - 1 NEW_LINE DEDENT if ( not isPrime [ oldValue ] and isPrime [ new_val ] ) : NEW_LINE INDENT diff = 1 NEW_LINE DEDENT updateValueUtil ( st , 0 , n - 1 , i , diff , 0 ) NEW_LINE DEDENT def queryPrimes ( st , n , qs , qe ) : NEW_LINE INDENT primesInRange = queryPrimesUtil ( st , 0 , n - 1 , qs , qe , 0 ) NEW_LINE print ( " Number ▁ of ▁ Primes ▁ in ▁ subarray ▁ from ▁ " , qs , " ▁ to ▁ " , qe , " ▁ = ▁ " , primesInRange ) NEW_LINE DEDENT def constructSTUtil ( arr , ss , se , st , si , isPrime ) : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT if ( isPrime [ arr [ ss ] ] ) : NEW_LINE INDENT st [ si ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT st [ si ] = 0 NEW_LINE DEDENT return st [ si ] NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 , isPrime ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 , isPrime ) NEW_LINE return st [ si ] NEW_LINE DEDENT def constructST ( arr , n , isPrime ) : NEW_LINE INDENT x = ceil ( log ( n , 2 ) ) NEW_LINE max_size = 2 * pow ( 2 , x ) - 1 NEW_LINE st = [ 0 ] * ( max_size ) NEW_LINE constructSTUtil ( arr , 0 , n - 1 , st , 0 , isPrime ) NEW_LINE return st NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 5 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE isPrime = [ True ] * ( MAX + 1 ) NEW_LINE sieveOfEratosthenes ( isPrime ) NEW_LINE st = constructST ( arr , n , isPrime ) NEW_LINE start = 0 NEW_LINE end = 4 NEW_LINE queryPrimes ( st , n , start , end ) NEW_LINE i = 3 NEW_LINE x = 6 NEW_LINE updateValue ( arr , st , n , i , x , isPrime ) NEW_LINE start = 0 NEW_LINE end = 4 NEW_LINE queryPrimes ( st , n , start , end ) NEW_LINE DEDENT
Check in binary array the number represented by a subarray is odd or even | Prints if subarray is even or odd ; if arr [ r ] = 1 print odd ; if arr [ r ] = 0 print even ; Driver code
def checkEVENodd ( arr , n , l , r ) : NEW_LINE INDENT if ( arr [ r ] == 1 ) : NEW_LINE INDENT print ( " odd " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " even " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE checkEVENodd ( arr , n , 1 , 3 ) NEW_LINE
Array Queries for multiply , replacements and product | vector of 1000 elements , all set to 0 ; vector of 1000 elements , all set to 0 ; Function to check number of trailing zeros in multiple of 2 ; Function to check number of trailing zeros in multiple of 5 ; Function to solve the queries received ; If the query is of typee 1. ; Counting the number of zeros in the given value of x ; The value x has been multiplied to their respective indices ; The value obtained above has been added to their respective vectors ; If the query is of typee 2. ; Counting the number of zero in the given value of x ; The value y has been replaced to their respective indices ; The value obtained above has been added to their respective vectors ; If the query is of typee 2 ; As the number of trailing zeros for each case has been found for each array element then we simply add those to the respective index to a variable ; Compare the number of zeros obtained in the multiples of five and two consider the minimum of them and add them ; Input the Size of array and number of queries ; Running the while loop for m number of queries
twos = [ 0 ] * 1000 NEW_LINE fives = [ 0 ] * 1000 NEW_LINE sum = 0 NEW_LINE def returnTwos ( val ) : NEW_LINE INDENT count = 0 NEW_LINE while ( val % 2 == 0 and val != 0 ) : NEW_LINE INDENT val = val // 2 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def returnFives ( val ) : NEW_LINE INDENT count = 0 NEW_LINE while ( val % 5 == 0 and val != 0 ) : NEW_LINE INDENT val = val // 5 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def solve_queries ( arr , n ) : NEW_LINE INDENT global sum NEW_LINE arrr1 = list ( map ( int , input ( ) . split ( ) ) ) NEW_LINE typee = arrr1 [ 0 ] NEW_LINE if ( typee == 1 ) : NEW_LINE INDENT ql , qr , x = arrr1 [ 1 ] , arrr1 [ 2 ] , arrr1 [ 3 ] NEW_LINE temp = returnTwos ( x ) NEW_LINE temp1 = returnFives ( x ) NEW_LINE i = ql - 1 NEW_LINE while ( i < qr ) : NEW_LINE INDENT arr [ i ] = arr [ i ] * x NEW_LINE twos [ i ] += temp NEW_LINE fives [ i ] += temp1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if ( typee == 2 ) : NEW_LINE INDENT ql , qr , y = arrr1 [ 1 ] , arrr1 [ 2 ] , arrr1 [ 3 ] NEW_LINE temp = returnTwos ( y ) NEW_LINE temp1 = returnFives ( y ) NEW_LINE i = ql - 1 NEW_LINE while ( i < qr ) : NEW_LINE INDENT arr [ i ] = ( i - ql + 2 ) * y NEW_LINE twos [ i ] = returnTwos ( i - ql + 2 ) + temp NEW_LINE fives [ i ] = returnFives ( i - ql + 2 ) + temp1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if ( typee == 3 ) : NEW_LINE INDENT ql , qr = arrr1 [ 1 ] , arrr1 [ 2 ] NEW_LINE sumtwos = 0 NEW_LINE sumfives = 0 NEW_LINE i = ql - 1 NEW_LINE while ( i < qr ) : NEW_LINE INDENT sumtwos += twos [ i ] NEW_LINE sumfives += fives [ i ] NEW_LINE i += 1 NEW_LINE DEDENT sum += min ( sumtwos , sumfives ) NEW_LINE DEDENT DEDENT n , m = map ( int , input ( ) . split ( ) ) NEW_LINE arr = list ( map ( int , input ( ) . split ( ) ) ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT twos [ i ] = returnTwos ( arr [ i ] ) NEW_LINE fives [ i ] = returnFives ( arr [ i ] ) NEW_LINE DEDENT while ( m ) : NEW_LINE INDENT m -= 1 NEW_LINE solve_queries ( arr , n ) NEW_LINE DEDENT print ( sum ) NEW_LINE
Mean of range in array | Python 3 program to find floor value of mean in range l to r ; To find mean of range in l to r ; Both sum and count are initialize to 0 ; To calculate sum and number of elements in range l to r ; Calculate floor value of mean ; Returns mean of array in range l to r ; Driver Code
import math NEW_LINE def findMean ( arr , l , r ) : NEW_LINE INDENT sum , count = 0 , 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE count += 1 NEW_LINE DEDENT mean = math . floor ( sum / count ) NEW_LINE return mean NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE print ( findMean ( arr , 0 , 2 ) ) NEW_LINE print ( findMean ( arr , 1 , 3 ) ) NEW_LINE print ( findMean ( arr , 0 , 4 ) ) NEW_LINE
Mean of range in array | Python3 program to find floor value of mean in range l to r ; To calculate prefixSum of array ; Calculate prefix sum of array ; To return floor of mean in range l to r ; Sum of elements in range l to r is prefixSum [ r ] - prefixSum [ l - 1 ] Number of elements in range l to r is r - l + 1 ; Driver Code
import math as mt NEW_LINE MAX = 1000005 NEW_LINE prefixSum = [ 0 for i in range ( MAX ) ] NEW_LINE def calculatePrefixSum ( arr , n ) : NEW_LINE INDENT prefixSum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] NEW_LINE DEDENT DEDENT def findMean ( l , r ) : NEW_LINE INDENT if ( l == 0 ) : NEW_LINE INDENT return mt . floor ( prefixSum [ r ] / ( r + 1 ) ) NEW_LINE DEDENT return ( mt . floor ( ( prefixSum [ r ] - prefixSum [ l - 1 ] ) / ( r - l + 1 ) ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE calculatePrefixSum ( arr , n ) NEW_LINE print ( findMean ( 0 , 2 ) ) NEW_LINE print ( findMean ( 1 , 3 ) ) NEW_LINE print ( findMean ( 0 , 4 ) ) NEW_LINE
Print modified array after executing the commands of addition and subtraction | Update function for every command ; If q == 0 , add ' k ' and ' - k ' to ' l - 1' and ' r ' index ; If q == 1 , add ' - k ' and ' k ' to ' l - 1' and ' r ' index ; Function to generate the final array after executing all commands ; Generate final array with the help of DP concept ; Driver Code ; Generate final array ; Printing the final modified array
def updateQuery ( arr , n , q , l , r , k ) : NEW_LINE INDENT if ( q == 0 ) : NEW_LINE INDENT arr [ l - 1 ] += k NEW_LINE arr [ r ] += - k NEW_LINE DEDENT else : NEW_LINE INDENT arr [ l - 1 ] += - k NEW_LINE arr [ r ] += k NEW_LINE DEDENT return NEW_LINE DEDENT def generateArray ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] NEW_LINE DEDENT return NEW_LINE DEDENT n = 5 NEW_LINE arr = [ 0 for i in range ( n + 1 ) ] NEW_LINE q = 0 ; l = 1 ; r = 3 ; k = 2 NEW_LINE updateQuery ( arr , n , q , l , r , k ) NEW_LINE q , l , r , k = 1 , 3 , 5 , 3 NEW_LINE updateQuery ( arr , n , q , l , r , k ) ; NEW_LINE q , l , r , k = 0 , 2 , 5 , 1 NEW_LINE updateQuery ( arr , n , q , l , r , k ) NEW_LINE generateArray ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Products of ranges in an array | Function to calculate Product in the given range . ; As our array is 0 based and L and R are given as 1 based index . ; Driver code
def calculateProduct ( A , L , R , P ) : NEW_LINE INDENT L = L - 1 NEW_LINE R = R - 1 NEW_LINE ans = 1 NEW_LINE for i in range ( R + 1 ) : NEW_LINE INDENT ans = ans * A [ i ] NEW_LINE ans = ans % P NEW_LINE DEDENT return ans NEW_LINE DEDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE P = 229 NEW_LINE L = 2 NEW_LINE R = 5 NEW_LINE print ( calculateProduct ( A , L , R , P ) ) NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE print ( calculateProduct ( A , L , R , P ) ) NEW_LINE
Products of ranges in an array | Returns modulo inverse of a with respect to m using extended Euclid Algorithm . Assumption : a and m are coprimes , i . e . , gcd ( a , m ) = 1 ; q is quotient ; m is remainder now , process same as Euclid 's algo ; Make x1 positive ; calculating pre_product array ; Cacluating inverse_product array . ; Function to calculate Product in the given range . ; As our array is 0 based as and L and R are given as 1 based index . ; Driver Code ; Array ; Prime P ; Calculating PreProduct and InverseProduct ; Range [ L , R ] in 1 base index
def modInverse ( a , m ) : NEW_LINE INDENT m0 , x0 , x1 = m , 0 , 1 NEW_LINE if m == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT while a > 1 : NEW_LINE INDENT q = a // m NEW_LINE t = m NEW_LINE m , a = a % m , t NEW_LINE t = x0 NEW_LINE x0 = x1 - q * x0 NEW_LINE x1 = t NEW_LINE DEDENT if x1 < 0 : NEW_LINE INDENT x1 += m0 NEW_LINE DEDENT return x1 NEW_LINE DEDENT def calculate_Pre_Product ( A , N , P ) : NEW_LINE INDENT pre_product [ 0 ] = A [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pre_product [ i ] = pre_product [ i - 1 ] * A [ i ] NEW_LINE pre_product [ i ] = pre_product [ i ] % P NEW_LINE DEDENT DEDENT def calculate_inverse_product ( A , N , P ) : NEW_LINE INDENT inverse_product [ 0 ] = modInverse ( pre_product [ 0 ] , P ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT inverse_product [ i ] = modInverse ( pre_product [ i ] , P ) NEW_LINE DEDENT DEDENT def calculateProduct ( A , L , R , P ) : NEW_LINE INDENT L = L - 1 NEW_LINE R = R - 1 NEW_LINE ans = 0 NEW_LINE if L == 0 : NEW_LINE INDENT ans = pre_product [ R ] NEW_LINE DEDENT else : NEW_LINE INDENT ans = pre_product [ R ] * inverse_product [ L - 1 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( A ) NEW_LINE P = 113 NEW_LINE MAX = 100 NEW_LINE pre_product = [ None ] * ( MAX ) NEW_LINE inverse_product = [ None ] * ( MAX ) NEW_LINE calculate_Pre_Product ( A , N , P ) NEW_LINE calculate_inverse_product ( A , N , P ) NEW_LINE L , R = 2 , 5 NEW_LINE print ( calculateProduct ( A , L , R , P ) ) NEW_LINE L , R = 1 , 3 NEW_LINE print ( calculateProduct ( A , L , R , P ) ) NEW_LINE DEDENT
Count Primes in Ranges | Python3 program to answer queries for count of primes in given range . ; prefix [ i ] is going to store count of primes till i ( including i ) . ; Create a boolean array value in prime [ i ] will " prime [ 0 . . n ] " . A finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array prefix [ 0 ] = prefix [ 1 ] = 0 ; ; Returns count of primes in range from L to R ( both inclusive ) . ; Driver code
MAX = 10000 NEW_LINE prefix = [ 0 ] * ( MAX + 1 ) NEW_LINE def buildPrefix ( ) : NEW_LINE INDENT prime = [ 1 ] * ( MAX + 1 ) NEW_LINE p = 2 NEW_LINE while ( p * p <= MAX ) : NEW_LINE INDENT if ( prime [ p ] == 1 ) : NEW_LINE INDENT i = p * 2 NEW_LINE while ( i <= MAX ) : NEW_LINE INDENT prime [ i ] = 0 NEW_LINE i += p NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT prefix [ p ] = prefix [ p - 1 ] NEW_LINE if ( prime [ p ] == 1 ) : NEW_LINE INDENT prefix [ p ] += 1 NEW_LINE DEDENT DEDENT DEDENT def query ( L , R ) : NEW_LINE INDENT return prefix [ R ] - prefix [ L - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT buildPrefix ( ) NEW_LINE L = 5 NEW_LINE R = 10 NEW_LINE print ( query ( L , R ) ) NEW_LINE L = 1 NEW_LINE R = 10 NEW_LINE print ( query ( L , R ) ) NEW_LINE DEDENT
Binary array after M range toggle operations | function for toggle ; function for final processing of array ; function for printing result ; Driver Code ; function call for toggle ; process array ; print result
def command ( brr , a , b ) : NEW_LINE INDENT arr [ a ] ^= 1 NEW_LINE arr [ b + 1 ] ^= 1 NEW_LINE DEDENT def process ( arr , n ) : NEW_LINE INDENT for k in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT arr [ k ] ^= arr [ k - 1 ] NEW_LINE DEDENT DEDENT def result ( arr , n ) : NEW_LINE INDENT for k in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT print ( arr [ k ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE m = 3 NEW_LINE arr = [ 0 for i in range ( n + 2 ) ] NEW_LINE command ( arr , 1 , 5 ) NEW_LINE command ( arr , 2 , 5 ) NEW_LINE command ( arr , 3 , 5 ) NEW_LINE process ( arr , n ) NEW_LINE result ( arr , n ) NEW_LINE DEDENT
Print modified array after multiple array range increment operations | function to increment values in the given range by a value d for multiple queries ; for each ( start , end ) index pair perform the following operations on 'sum[] ; increment the value at index ' start ' by the given value ' d ' in 'sum[] ; if the index ' ( end + 1 ) ' exists then decrement the value at index ' ( end + 1 ) ' by the given value ' d ' in 'sum[] ; Now , perform the following operations : accumulate values in the ' sum [ ] ' array and then add them to the corresponding indexes in 'arr[] ; function to print the elements of the given array ; Driver Code ; modifying the array for multiple queries
def incrementByD ( arr , q_arr , n , m , d ) : NEW_LINE INDENT sum = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT sum [ q_arr [ i ] [ 0 ] ] += d NEW_LINE if ( ( q_arr [ i ] [ 1 ] + 1 ) < n ) : NEW_LINE INDENT sum [ q_arr [ i ] [ 1 ] + 1 ] -= d NEW_LINE DEDENT DEDENT arr [ 0 ] += sum [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT sum [ i ] += sum [ i - 1 ] NEW_LINE arr [ i ] += sum [ i ] NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in arr : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 3 , 5 , 4 , 8 , 6 , 1 ] NEW_LINE q_arr = [ [ 0 , 3 ] , [ 4 , 5 ] , [ 1 , 4 ] , [ 0 , 1 ] , [ 2 , 5 ] ] NEW_LINE n = len ( arr ) NEW_LINE m = len ( q_arr ) NEW_LINE d = 2 NEW_LINE print ( " Original ▁ Array : " ) NEW_LINE printArray ( arr , n ) NEW_LINE incrementByD ( arr , q_arr , n , m , d ) NEW_LINE print ( " Modified Array : " ) NEW_LINE printArray ( arr , n ) NEW_LINE
Queries for number of distinct elements in a subarray | Python3 code to find number of distinct numbers in a subarray ; structure to store queries ; updating the bit array ; querying the bit array ; initialising bit array ; holds the rightmost index of any number as numbers of a [ i ] are less than or equal to 10 ^ 6 ; answer for each query ; If last visit is not - 1 update - 1 at the idx equal to last_visit [ arr [ i ] ] ; Setting last_visit [ arr [ i ] ] as i and updating the bit array accordingly ; If i is equal to r of any query store answer for that query in ans [ ] ; print answer for each query ; Driver Code
MAX = 1000001 NEW_LINE class Query : NEW_LINE INDENT def __init__ ( self , l , r , idx ) : NEW_LINE INDENT self . l = l NEW_LINE self . r = r NEW_LINE self . idx = idx NEW_LINE DEDENT DEDENT def update ( idx , val , bit , n ) : NEW_LINE INDENT while idx <= n : NEW_LINE INDENT bit [ idx ] += val NEW_LINE idx += idx & - idx NEW_LINE DEDENT DEDENT def query ( idx , bit , n ) : NEW_LINE INDENT summ = 0 NEW_LINE while idx : NEW_LINE INDENT summ += bit [ idx ] NEW_LINE idx -= idx & - idx NEW_LINE DEDENT return summ NEW_LINE DEDENT def answeringQueries ( arr , n , queries , q ) : NEW_LINE INDENT bit = [ 0 ] * ( n + 1 ) NEW_LINE last_visit = [ - 1 ] * MAX NEW_LINE ans = [ 0 ] * q NEW_LINE query_counter = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if last_visit [ arr [ i ] ] != - 1 : NEW_LINE INDENT update ( last_visit [ arr [ i ] ] + 1 , - 1 , bit , n ) NEW_LINE DEDENT last_visit [ arr [ i ] ] = i NEW_LINE update ( i + 1 , 1 , bit , n ) NEW_LINE while query_counter < q and queries [ query_counter ] . r == i : NEW_LINE INDENT ans [ queries [ query_counter ] . idx ] = query ( queries [ query_counter ] . r + 1 , bit , n ) - query ( queries [ query_counter ] . l , bit , n ) NEW_LINE query_counter += 1 NEW_LINE DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT print ( ans [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 1 , 2 , 1 , 3 ] NEW_LINE n = len ( a ) NEW_LINE queries = [ Query ( 0 , 4 , 0 ) , Query ( 1 , 3 , 1 ) , Query ( 2 , 4 , 2 ) ] NEW_LINE q = len ( queries ) NEW_LINE queries . sort ( key = lambda x : x . r ) NEW_LINE answeringQueries ( a , n , queries , q ) NEW_LINE DEDENT
Count and Toggle Queries on a Binary Array | Python program to implement toggle and count queries on a binary array . ; segment tree to store count of 1 's within range ; bool type tree to collect the updates for toggling the values of 1 and 0 in given range ; function for collecting updates of toggling node -- > index of current node in segment tree st -- > starting index of current node en -- > ending index of current node us -- > starting index of range update query ue -- > ending index of range update query ; If lazy value is non - zero for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before making new updates . Because this value may be used by parent after recursive calls ( See last line of this function ) ; Make pending updates using value stored in lazy nodes ; checking if it is not leaf node because if it is leaf node then we cannot go further ; We can postpone updating children we don ' t ▁ ▁ need ▁ their ▁ new ▁ values ▁ now . ▁ ▁ Since ▁ we ▁ are ▁ not ▁ yet ▁ updating ▁ children ▁ of ▁ ' node ', we need to set lazy flags for the children ; out of range ; Current segment is fully in range ; Add the difference to current node ; same logic for checking leaf node or not ; This is where we store values in lazy nodes , rather than updating the segment tree itelf Since we don 't need these updated values now we postpone updates by storing values in lazy[] ; If not completely in rang , but overlaps , recur for children , ; And use the result of children calls to update this node ; function to count number of 1 's within given range ; current node is out of range ; If lazy flag is set for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before processing the sub sum query ; Make pending updates to this node . Note that this node represents sum of elements in arr [ st . . en ] and all these elements must be increased by lazy [ node ] ; checking if it is not leaf node because if it is leaf node then we cannot go further ; Since we are not yet updating children os si , we need to set lazy values for the children ; At this point we are sure that pending lazy updates are done for current node . So we can return value If this segment lies in range ; If a part of this segment overlaps with the given range ; Driver Code ; Toggle 1 2 ; Toggle 2 4 ; count 2 3 ; Toggle 2 4 ; count 1 4
MAX = 100000 NEW_LINE tree = [ 0 ] * MAX NEW_LINE lazy = [ False ] * MAX NEW_LINE def toggle ( node : int , st : int , en : int , us : int , ue : int ) : NEW_LINE INDENT if lazy [ node ] : NEW_LINE INDENT lazy [ node ] = False NEW_LINE tree [ node ] = en - st + 1 - tree [ node ] NEW_LINE if st < en : NEW_LINE INDENT lazy [ node << 1 ] = not lazy [ node << 1 ] NEW_LINE lazy [ 1 + ( node << 1 ) ] = not lazy [ 1 + ( node << 1 ) ] NEW_LINE DEDENT DEDENT if st > en or us > en or ue < st : NEW_LINE INDENT return NEW_LINE DEDENT if us <= st and en <= ue : NEW_LINE INDENT tree [ node ] = en - st + 1 - tree [ node ] NEW_LINE if st < en : NEW_LINE INDENT lazy [ node << 1 ] = not lazy [ node << 1 ] NEW_LINE lazy [ 1 + ( node << 1 ) ] = not lazy [ 1 + ( node << 1 ) ] NEW_LINE DEDENT return NEW_LINE DEDENT mid = ( st + en ) // 2 NEW_LINE toggle ( ( node << 1 ) , st , mid , us , ue ) NEW_LINE toggle ( ( node << 1 ) + 1 , mid + 1 , en , us , ue ) NEW_LINE if st < en : NEW_LINE INDENT tree [ node ] = tree [ node << 1 ] + tree [ ( node << 1 ) + 1 ] NEW_LINE DEDENT DEDENT def countQuery ( node : int , st : int , en : int , qs : int , qe : int ) -> int : NEW_LINE INDENT if st > en or qs > en or qe < st : NEW_LINE INDENT return 0 NEW_LINE DEDENT if lazy [ node ] : NEW_LINE INDENT lazy [ node ] = False NEW_LINE tree [ node ] = en - st + 1 - tree [ node ] NEW_LINE if st < en : NEW_LINE INDENT lazy [ node << 1 ] = not lazy [ node << 1 ] NEW_LINE lazy [ ( node << 1 ) + 1 ] = not lazy [ ( node << 1 ) + 1 ] NEW_LINE DEDENT DEDENT if qs <= st and en <= qe : NEW_LINE INDENT return tree [ node ] NEW_LINE DEDENT mid = ( st + en ) // 2 NEW_LINE return countQuery ( ( node << 1 ) , st , mid , qs , qe ) + countQuery ( ( node << 1 ) + 1 , mid + 1 , en , qs , qe ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE DEDENT toggle ( 1 , 0 , n - 1 , 1 , 2 ) NEW_LINE toggle ( 1 , 0 , n - 1 , 2 , 4 ) NEW_LINE print ( countQuery ( 1 , 0 , n - 1 , 2 , 3 ) ) NEW_LINE toggle ( 1 , 0 , n - 1 , 2 , 4 ) NEW_LINE print ( countQuery ( 1 , 0 , n - 1 , 1 , 4 ) ) NEW_LINE
No of pairs ( a [ j ] >= a [ i ] ) with k numbers in range ( a [ i ] , a [ j ] ) that are divisible by x | Python3 program to calculate the number pairs satisfying th condition ; function to calculate the number of pairs ; traverse through all elements ; current number 's divisor ; use binary search to find the element after k multiples of x ; use binary search to find the element after k + 1 multiples of x so that we get the answer bu subtracting ; the difference of index will be the answer ; Driver code ; function call to get the number of pairs
import bisect NEW_LINE def countPairs ( a , n , x , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT d = ( a [ i ] - 1 ) // x NEW_LINE it1 = bisect . bisect_left ( a , max ( ( d + k ) * x , a [ i ] ) ) NEW_LINE it2 = bisect . bisect_left ( a , max ( ( d + k + 1 ) * x , a [ i ] ) ) NEW_LINE ans += it2 - it1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 3 , 5 , 7 ] NEW_LINE n = len ( a ) NEW_LINE x = 2 NEW_LINE k = 1 NEW_LINE print ( countPairs ( a , n , x , k ) ) NEW_LINE DEDENT
Probability of a random pair being the maximum weighted pair | ; Function to return probability ; Count occurrences of maximum element in A [ ] ; Count occurrences of maximum element in B [ ] ; Returning probability ; Driver code
import sys NEW_LINE def probability ( a , b , size1 , size2 ) : NEW_LINE INDENT max1 = - ( sys . maxsize - 1 ) NEW_LINE count1 = 0 NEW_LINE for i in range ( size1 ) : NEW_LINE INDENT if a [ i ] > max1 : NEW_LINE INDENT count1 = 1 NEW_LINE DEDENT elif a [ i ] == max1 : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT DEDENT max2 = - ( sys . maxsize - 1 ) NEW_LINE count2 = 0 NEW_LINE for i in range ( size2 ) : NEW_LINE INDENT if b [ i ] > max2 : NEW_LINE INDENT max2 = b [ i ] NEW_LINE count2 = 1 NEW_LINE DEDENT elif b [ i ] == max2 : NEW_LINE INDENT count2 += 1 NEW_LINE DEDENT DEDENT return round ( ( count1 * count2 ) / ( size1 * size2 ) , 6 ) NEW_LINE DEDENT a = [ 1 , 2 , 3 ] NEW_LINE b = [ 1 , 3 , 3 ] NEW_LINE size1 = len ( a ) NEW_LINE size2 = len ( b ) NEW_LINE print ( probability ( a , b , size1 , size2 ) ) NEW_LINE
Minimum De | function to count Dearrangement ; create a copy of original array ; sort the array ; traverse sorted array for counting mismatches ; reverse the sorted array ; traverse reverse sorted array for counting mismatches ; return minimum mismatch count ; Driven code
def countDe ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE v = arr . copy ( ) NEW_LINE arr . sort ( ) NEW_LINE count1 = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] != v [ i ] ) : NEW_LINE INDENT count1 = count1 + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT arr . sort ( reverse = True ) NEW_LINE count2 = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] != v [ i ] ) : NEW_LINE INDENT count2 = count2 + 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return ( min ( count1 , count2 ) ) NEW_LINE DEDENT arr = [ 5 , 9 , 21 , 17 , 13 ] NEW_LINE n = 5 NEW_LINE print ( " Minimum ▁ Dearrangement ▁ = " , countDe ( arr , n ) ) NEW_LINE
Divide an array into k segments to maximize maximum of segment minimums | function to calculate the max of all the minimum segments ; if we have to divide it into 1 segment then the min will be the answer ; If k >= 3 , return maximum of all elements . ; Driver code
def maxOfSegmentMins ( a , n , k ) : NEW_LINE INDENT if k == 1 : NEW_LINE INDENT return min ( a ) NEW_LINE DEDENT if k == 2 : NEW_LINE INDENT return max ( a [ 0 ] , a [ n - 1 ] ) NEW_LINE DEDENT return max ( a ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ - 10 , - 9 , - 8 , 2 , 7 , - 6 , - 5 ] NEW_LINE n = len ( a ) NEW_LINE k = 2 NEW_LINE print ( maxOfSegmentMins ( a , n , k ) ) NEW_LINE DEDENT
Minimum product pair an array of positive Integers | Function to calculate minimum product of pair ; Initialize first and second minimums . It is assumed that the array has at least two elements . ; Traverse remaining array and keep track of two minimum elements ( Note that the two minimum elements may be same if minimum element appears more than once ) more than once ) ; Driver code
def printMinimumProduct ( arr , n ) : NEW_LINE INDENT first_min = min ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE second_min = max ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] < first_min ) : NEW_LINE INDENT second_min = first_min NEW_LINE first_min = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < second_min ) : NEW_LINE INDENT second_min = arr [ i ] NEW_LINE DEDENT DEDENT return first_min * second_min NEW_LINE DEDENT a = [ 11 , 8 , 5 , 7 , 5 , 100 ] NEW_LINE n = len ( a ) NEW_LINE print ( printMinimumProduct ( a , n ) ) NEW_LINE
Count ways to form minimum product triplets | function to calculate number of triples ; Sort the array ; Count occurrences of third element ; If all three elements are same ( minimum element appears at l east 3 times ) . Answer is nC3 . ; If minimum element appears once . Answer is nC2 . ; Minimum two elements are distinct . Answer is nC1 . ; Driver code
def noOfTriples ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == arr [ 2 ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if arr [ 0 ] == arr [ 2 ] : NEW_LINE INDENT return ( count - 2 ) * ( count - 1 ) * ( count ) / 6 NEW_LINE DEDENT elif arr [ 1 ] == arr [ 2 ] : NEW_LINE INDENT return ( count - 1 ) * ( count ) / 2 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 1 , 3 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( noOfTriples ( arr , n ) ) NEW_LINE
Check if reversing a sub array make the array sorted | Return true , if reversing the subarray will sort the array , else return false . ; Copying the array ; Sort the copied array . ; Finding the first mismatch . ; Finding the last mismatch . ; If whole array is sorted ; Checking subarray is decreasing or not . ; Driver code
def checkReverse ( arr , n ) : NEW_LINE INDENT temp = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp [ i ] = arr [ i ] NEW_LINE DEDENT temp . sort ( ) NEW_LINE for front in range ( n ) : NEW_LINE INDENT if temp [ front ] != arr [ front ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for back in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if temp [ back ] != arr [ back ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if front >= back : NEW_LINE INDENT return True NEW_LINE DEDENT while front != back : NEW_LINE INDENT front += 1 NEW_LINE if arr [ front - 1 ] < arr [ front ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 1 , 2 , 5 , 4 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE if checkReverse ( arr , n ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check if reversing a sub array make the array sorted | Python3 program to check whether reversing a sub array make the array sorted or not ; Return True , if reversing the subarray will sort the array , else return False . ; Find first increasing part ; Find reversed part ; Find last increasing part ; To handle cases like 1 , 2 , 3 , 4 , 20 , 9 , 16 , 17 ; Driver Code
import math as mt NEW_LINE def checkReverse ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i - 1 ] < arr [ i ] : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT j = i NEW_LINE while ( j < n and arr [ j ] < arr [ j - 1 ] ) : NEW_LINE INDENT if ( i > 1 and arr [ j ] < arr [ i - 2 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT k = j NEW_LINE if ( arr [ k ] < arr [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( k > 1 and k < n ) : NEW_LINE INDENT if ( arr [ k ] < arr [ k - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT k += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 10 , 9 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE if checkReverse ( arr , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Making elements of two arrays same with minimum increment / decrement | Python 3 program to find minimum increment / decrement operations to make array elements same . ; sorting both arrays in ascending order ; variable to store the final result ; After sorting both arrays . Now each array is in non - decreasing order . Thus , we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b [ ] . ; Driver code
def MinOperation ( a , b , n ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE b . sort ( reverse = False ) NEW_LINE result = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( a [ i ] > b [ i ] ) : NEW_LINE INDENT result = result + abs ( a [ i ] - b [ i ] ) NEW_LINE DEDENT elif ( a [ i ] < b [ i ] ) : NEW_LINE INDENT result = result + abs ( a [ i ] - b [ i ] ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 3 , 1 , 1 ] NEW_LINE b = [ 1 , 2 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( MinOperation ( a , b , n ) ) NEW_LINE DEDENT
Sorting array except elements in a subarray | Sort whole array a [ ] except elements in range a [ l . . r ] ; Copy all those element that need to be sorted to an auxiliary array b [ ] ; sort the array b ; Copy sorted elements back to a [ ] ; Driver code
def sortExceptUandL ( a , l , u , n ) : NEW_LINE INDENT b = [ 0 ] * ( n - ( u - l + 1 ) ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT b [ i ] = a [ i ] NEW_LINE DEDENT for i in range ( u + 1 , n ) : NEW_LINE INDENT b [ l + ( i - ( u + 1 ) ) ] = a [ i ] NEW_LINE DEDENT b . sort ( ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT a [ i ] = b [ i ] NEW_LINE DEDENT for i in range ( u + 1 , n ) : NEW_LINE INDENT a [ i ] = b [ l + ( i - ( u + 1 ) ) ] NEW_LINE DEDENT DEDENT a = [ 5 , 4 , 3 , 12 , 14 , 9 ] NEW_LINE n = len ( a ) NEW_LINE l = 2 NEW_LINE u = 4 NEW_LINE sortExceptUandL ( a , l , u , n ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( " { } ▁ " . format ( a [ i ] ) , end = " " ) NEW_LINE DEDENT
Sorting all array elements except one | Python3 program to sort all elements except element at index k . ; Move k - th element to end ; Sort all elements except last ; Store last element ( originally k - th ) ; Move all elements from k - th to one position ahead . ; Restore k - th element ; Driver code
def sortExcept ( arr , k , n ) : NEW_LINE INDENT arr [ k ] , arr [ - 1 ] = arr [ - 1 ] , arr [ k ] NEW_LINE arr = sorted ( arr , key = lambda i : ( i is arr [ - 1 ] , i ) ) NEW_LINE last = arr [ - 1 ] NEW_LINE i = n - 1 NEW_LINE while i > k : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT arr [ k ] = last NEW_LINE return arr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 10 , 4 , 11 , 7 , 6 , 20 ] NEW_LINE k = 2 NEW_LINE n = len ( a ) NEW_LINE a = sortExcept ( a , k , n ) NEW_LINE print ( " ▁ " . join ( list ( map ( str , a ) ) ) ) NEW_LINE DEDENT
Sort the linked list in the order of elements appearing in the array | Linked list node ; Function to insert a node at the beginning of the linked list ; function to print the linked list ; Function that sort list in order of apperaing elements in an array ; Store frequencies of elements in a hash table . ; One by one put elements in lis according to their appearance in array ; Update ' frequency ' nodes with value equal to arr [ i ] ; Modify list data as element appear in an array ; Driver Code ; creating the linked list ; Function call to sort the list in order elements are apperaing in an array ; print the modified linked list
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " - > " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT def sortlist ( arr , N , head ) : NEW_LINE INDENT hash = dict ( ) NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT hash [ temp . data ] = hash . get ( temp . data , 0 ) + 1 NEW_LINE temp = temp . next NEW_LINE DEDENT temp = head NEW_LINE for i in range ( N ) : NEW_LINE INDENT frequency = hash . get ( arr [ i ] , 0 ) NEW_LINE while ( frequency > 0 ) : NEW_LINE INDENT frequency = frequency - 1 NEW_LINE temp . data = arr [ i ] NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT DEDENT head = None NEW_LINE arr = [ 5 , 1 , 3 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE sortlist ( arr , N , head ) NEW_LINE print ( " Sorted ▁ List : " ) NEW_LINE printList ( head ) NEW_LINE
Maximum number of partitions that can be sorted individually to make sorted | Function to find maximum partitions . ; Find maximum in prefix arr [ 0. . i ] ; If maximum so far is equal to index , we can make a new partition ending at index i . ; Driver code
def maxPartitions ( arr , n ) : NEW_LINE INDENT ans = 0 ; max_so_far = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT max_so_far = max ( max_so_far , arr [ i ] ) NEW_LINE if ( max_so_far == i ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 0 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxPartitions ( arr , n ) ) NEW_LINE
Rank of all elements in an array | Python Code to find rank of elements ; Rank Vector ; Sweep through all elements in A for each element count the number of less than and equal elements separately in r and s . ; Use formula to obtain rank ; Driver code
def rankify ( A ) : NEW_LINE INDENT R = [ 0 for x in range ( len ( A ) ) ] NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT ( r , s ) = ( 1 , 1 ) NEW_LINE for j in range ( len ( A ) ) : NEW_LINE INDENT if j != i and A [ j ] < A [ i ] : NEW_LINE INDENT r += 1 NEW_LINE DEDENT if j != i and A [ j ] == A [ i ] : NEW_LINE INDENT s += 1 NEW_LINE DEDENT DEDENT R [ i ] = r + ( s - 1 ) / 2 NEW_LINE DEDENT return R NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 5 , 2 , 1 , 25 , 2 ] NEW_LINE print ( A ) NEW_LINE print ( rankify ( A ) ) NEW_LINE DEDENT
Minimum number of subtract operation to make an array decreasing | Function to count minimum no of operation ; Count how many times we have to subtract . ; Check an additional subtraction is required or not . ; Modify the value of arr [ i ] . ; Count total no of operation / subtraction . ; Driver Code
def min_noOf_operation ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT noOfSubtraction = 0 NEW_LINE if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT noOfSubtraction = ( arr [ i ] - arr [ i - 1 ] ) / k ; NEW_LINE if ( ( arr [ i ] - arr [ i - 1 ] ) % k != 0 ) : NEW_LINE INDENT noOfSubtraction += 1 NEW_LINE DEDENT arr [ i ] = arr [ i ] - k * noOfSubtraction NEW_LINE DEDENT res = res + noOfSubtraction NEW_LINE DEDENT return int ( res ) NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE k = 5 NEW_LINE print ( min_noOf_operation ( arr , N , k ) ) NEW_LINE
Maximize the sum of arr [ i ] * i | Python program to find the maximum value of i * arr [ i ] ; Sort the array ; Finding the sum of arr [ i ] * i ; Driver Program
def maxSum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] * i NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 3 , 5 , 6 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE
Pairs with Difference less than K | Function to count pairs ; Driver code
def countPairs ( a , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( abs ( a [ j ] - a [ i ] ) < k ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT a = [ 1 , 10 , 4 , 2 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n , k ) , end = " " ) NEW_LINE
Pairs with Difference less than K | Python code to find count of Pairs with difference less than K . ; to sort the array ; Keep incrementing result while subsequent elements are within limits . ; Driver code
def countPairs ( a , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j < n and a [ j ] - a [ i ] < k ) : NEW_LINE INDENT res += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT a = [ 1 , 10 , 4 , 2 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n , k ) , end = " " ) NEW_LINE
Merging two unsorted arrays in sorted order | Function to merge array in sorted order ; Sorting a [ ] and b [ ] ; Merge two sorted arrays into res [ ] ; Merging remaining elements of a [ ] ( if any ) ; Merging remaining elements of b [ ] ( if any ) ; Driver code ; Final merge list
def sortedMerge ( a , b , res , n , m ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE i , j , k = 0 , 0 , 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( a [ i ] <= b [ j ] ) : NEW_LINE INDENT res [ k ] = a [ i ] NEW_LINE i += 1 NEW_LINE k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res [ k ] = b [ j ] NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT while ( i < n ) : NEW_LINE INDENT res [ k ] = a [ i ] NEW_LINE i += 1 NEW_LINE k += 1 NEW_LINE DEDENT while ( j < m ) : NEW_LINE INDENT res [ k ] = b [ j ] NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT a = [ 10 , 5 , 15 ] NEW_LINE b = [ 20 , 3 , 2 , 12 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE res = [ 0 for i in range ( n + m ) ] NEW_LINE sortedMerge ( a , b , res , n , m ) NEW_LINE print " Sorted ▁ merged ▁ list ▁ : " NEW_LINE for i in range ( n + m ) : NEW_LINE INDENT print res [ i ] , NEW_LINE DEDENT
Maximizing Unique Pairs from two arrays | Returns count of maximum pairs that can be formed from a [ ] and b [ ] under given constraints . ; Sorting the first array . ; Sorting the second array . ; To keep track of visited elements of b [ ] ; For every element of a [ ] , find a pair for it and break as soon as a pair is found . ; Increasing the count if a pair is formed . ; Making the corresponding flag array element as 1 indicating the element in the second array element has been used . ; We break the loop to make sure an element of a [ ] is used only once . ; Driver code
def findMaxPairs ( a , b , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE flag = [ False ] * n NEW_LINE result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( abs ( a [ i ] - b [ j ] ) <= k and flag [ j ] == False ) : NEW_LINE INDENT result += 1 NEW_LINE flag [ j ] = True NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 10 , 15 , 20 ] NEW_LINE b = [ 17 , 12 , 24 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE print ( findMaxPairs ( a , b , n , k ) ) NEW_LINE DEDENT
Maximizing Unique Pairs from two arrays | Returns count of maximum pairs that caan be formed from a [ ] and b [ ] under given constraints . ; Sorting the first array . ; Sorting the second array . ; Increasing array pointer of both the first and the second array . ; Increasing array pointer of the second array . ; Driver code
def findMaxPairs ( a , b , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE result = 0 NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if j < n : NEW_LINE INDENT if abs ( a [ i ] - b [ j ] ) <= k : NEW_LINE INDENT result += 1 NEW_LINE j += 1 NEW_LINE DEDENT elif a [ i ] > b [ j ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 10 , 15 , 20 ] NEW_LINE b = [ 17 , 12 , 24 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE print ( findMaxPairs ( a , b , n , k ) ) NEW_LINE DEDENT
Sum of minimum absolute difference of each array element | function to find the sum of minimum absolute difference ; sort the given array ; initialize sum ; min absolute difference for the 1 st array element ; min absolute difference for the last array element ; find min absolute difference for rest of the array elements and add them to sum ; required sum ; Driver code
def sumOfMinAbsDifferences ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE sum += abs ( arr [ 0 ] - arr [ 1 ] ) ; NEW_LINE sum += abs ( arr [ n - 1 ] - arr [ n - 2 ] ) ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT sum += min ( abs ( arr [ i ] - arr [ i - 1 ] ) , abs ( arr [ i ] - arr [ i + 1 ] ) ) NEW_LINE DEDENT return sum ; NEW_LINE DEDENT arr = [ 5 , 10 , 1 , 4 , 8 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Sum ▁ = ▁ " , sumOfMinAbsDifferences ( arr , n ) ) NEW_LINE
Smallest Difference pair of values between two unsorted Arrays | Python 3 Code to find Smallest Difference between two Arrays ; function to calculate Small result between two arrays ; Sort both arrays using sort function ; Initialize result as max value ; Scan Both Arrays upto sizeof of the Arrays ; Move Smaller Value ; return final sma result ; Input given array A ; Input given array B ; Calculate size of Both arrays ; Call function to print smallest result
import sys NEW_LINE def findSmallestDifference ( A , B , m , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE result = sys . maxsize NEW_LINE while ( a < m and b < n ) : NEW_LINE INDENT if ( abs ( A [ a ] - B [ b ] ) < result ) : NEW_LINE INDENT result = abs ( A [ a ] - B [ b ] ) NEW_LINE DEDENT if ( A [ a ] < B [ b ] ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT else : NEW_LINE INDENT b += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT A = [ 1 , 2 , 11 , 5 ] NEW_LINE B = [ 4 , 12 , 19 , 23 , 127 , 235 ] NEW_LINE m = len ( A ) NEW_LINE n = len ( B ) NEW_LINE print ( findSmallestDifference ( A , B , m , n ) ) NEW_LINE
Find elements larger than half of the elements in an array | Prints elements larger than n / 2 element ; Sort the array in ascending order ; Print last ceil ( n / 2 ) elements ; Driver program
def findLarger ( arr , n ) : NEW_LINE INDENT x = sorted ( arr ) NEW_LINE for i in range ( n / 2 , n ) : NEW_LINE INDENT print ( x [ i ] ) , NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 6 , 1 , 0 , 9 ] NEW_LINE n = len ( arr ) ; NEW_LINE findLarger ( arr , n ) NEW_LINE
Find the element that appears once in an array where every other element appears twice | singleelement function ; Driver code
def singleelement ( arr , n ) : NEW_LINE INDENT low = 0 NEW_LINE high = n - 2 NEW_LINE mid = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( arr [ mid ] == arr [ mid ^ 1 ] ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return arr [ low ] NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 4 , 5 , 3 , 4 ] NEW_LINE size = len ( arr ) NEW_LINE arr . sort ( ) NEW_LINE print ( singleelement ( arr , size ) ) NEW_LINE
Count triplets with sum smaller than a given value | A Simple Python 3 program to count triplets with sum smaller than a given value include < bits / stdc ++ . h > ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver program
def countTriplets ( arr , n , sum ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , 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 ] < sum ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 1 , 3 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 12 NEW_LINE print ( countTriplets ( arr , n , sum ) ) NEW_LINE
Count triplets with sum smaller than a given value | Python3 program to count triplets with sum smaller than a given value ; Sort input array ; Initialize result ; Every iteration of loop counts triplet with first element as arr [ i ] . ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there can be total k - j third elements . ; Driver program
def countTriplets ( arr , n , sum ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT j = i + 1 NEW_LINE k = n - 1 NEW_LINE while ( j < k ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) : NEW_LINE INDENT k = k - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( k - j ) NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 1 , 3 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 12 NEW_LINE print ( countTriplets ( arr , n , sum ) ) NEW_LINE DEDENT
Number of unique triplets whose XOR is zero | function to count the number of unique triplets whose xor is 0 ; To store values that are present ; stores the count of unique triplets ; traverse for all i , j pairs such that j > i ; xor of a [ i ] and a [ j ] ; if xr of two numbers is present , then increase the count ; returns answer ; Driver code
def countTriplets ( a , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( a [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT xr = a [ i ] ^ a [ j ] NEW_LINE if ( xr in s and xr != a [ i ] and xr != a [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return int ( count / 3 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 3 , 5 , 10 , 14 , 15 ] NEW_LINE n = len ( a ) NEW_LINE print ( countTriplets ( a , n ) ) NEW_LINE DEDENT
Find the Missing Number | getMissingNo takes list as argument ; Driver program to test the above function
def getMissingNo ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE total = ( n + 1 ) * ( n + 2 ) / 2 NEW_LINE sum_of_A = sum ( A ) NEW_LINE return total - sum_of_A NEW_LINE DEDENT A = [ 1 , 2 , 4 , 5 , 6 ] NEW_LINE miss = getMissingNo ( A ) NEW_LINE print ( miss ) NEW_LINE
Find the Missing Number | a represents the array n : Number of elements in array a ; Driver Code
def getMissingNo ( a , n ) : NEW_LINE INDENT i , total = 0 , 1 NEW_LINE for i in range ( 2 , n + 2 ) : NEW_LINE INDENT total += i NEW_LINE total -= a [ i - 2 ] NEW_LINE DEDENT return total NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 5 ] NEW_LINE print ( getMissingNo ( arr , len ( arr ) ) ) NEW_LINE
Find the Missing Number | getMissingNo takes list as argument ; Driver program to test above function
def getMissingNo ( a , n ) : NEW_LINE INDENT n_elements_sum = n * ( n + 1 ) // 2 NEW_LINE return n_elements_sum - sum ( a ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 2 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) + 1 NEW_LINE miss = getMissingNo ( a , n ) NEW_LINE print ( miss ) NEW_LINE DEDENT
Count number of occurrences ( or frequency ) in a sorted array | Returns number of times x occurs in arr [ 0. . n - 1 ] ; Driver code
def countOccurrences ( arr , n , x ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if x == arr [ i ] : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 2 , 2 , 3 , 4 , 7 , 8 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE x = 2 NEW_LINE print ( countOccurrences ( arr , n , x ) ) NEW_LINE
Count number of occurrences ( or frequency ) in a sorted array | A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; Returns number of times x occurs in arr [ 0. . n - 1 ] ; If element is not present ; Count elements on left side . ; Count elements on right side . ; Driver code
def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if ( r < l ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = int ( l + ( r - l ) / 2 ) NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ mid ] > x : NEW_LINE INDENT return binarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT def countOccurrences ( arr , n , x ) : NEW_LINE INDENT ind = binarySearch ( arr , 0 , n - 1 , x ) NEW_LINE if ind == - 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 1 NEW_LINE left = ind - 1 NEW_LINE while ( left >= 0 and arr [ left ] == x ) : NEW_LINE INDENT count += 1 NEW_LINE left -= 1 NEW_LINE DEDENT right = ind + 1 ; NEW_LINE while ( right < n and arr [ right ] == x ) : NEW_LINE INDENT count += 1 NEW_LINE right += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 2 , 2 , 3 , 4 , 7 , 8 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE x = 2 NEW_LINE print ( countOccurrences ( arr , n , x ) ) NEW_LINE
Given a sorted array and a number x , find the pair in array whose sum is closest to x | A sufficiently large value greater than any element in the input array ; Prints the pair with sum closest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver code to test above
MAX_VAL = 1000000000 NEW_LINE def printClosest ( arr , n , x ) : NEW_LINE INDENT res_l , res_r = 0 , 0 NEW_LINE l , r , diff = 0 , n - 1 , MAX_VAL NEW_LINE while r > l : NEW_LINE INDENT if abs ( arr [ l ] + arr [ r ] - x ) < diff : NEW_LINE INDENT res_l = l NEW_LINE res_r = r NEW_LINE diff = abs ( arr [ l ] + arr [ r ] - x ) NEW_LINE DEDENT if arr [ l ] + arr [ r ] > x : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT print ( ' The ▁ closest ▁ pair ▁ is ▁ { } ▁ and ▁ { } ' . format ( arr [ res_l ] , arr [ res_r ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 22 , 28 , 29 , 30 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 54 NEW_LINE printClosest ( arr , n , x ) NEW_LINE DEDENT
Count 1 's in a sorted binary array | Returns counts of 1 's in arr[low..high]. The array is assumed to be sorted in non-increasing order ; get the middle index ; check if the element at middle index is last 1 ; If element is not last 1 , recur for right side ; else recur for left side ; Driver Code
def countOnes ( arr , low , high ) : NEW_LINE INDENT if high >= low : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( ( mid == high or arr [ mid + 1 ] == 0 ) and ( arr [ mid ] == 1 ) ) : NEW_LINE INDENT return mid + 1 NEW_LINE DEDENT if arr [ mid ] == 1 : NEW_LINE INDENT return countOnes ( arr , ( mid + 1 ) , high ) NEW_LINE DEDENT return countOnes ( arr , low , mid - 1 ) NEW_LINE DEDENT return 0 NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 1 , 0 , 0 , 0 ] NEW_LINE print ( " Count ▁ of ▁ 1 ' s ▁ in ▁ given ▁ array ▁ is " , countOnes ( arr , 0 , len ( arr ) - 1 ) ) NEW_LINE
Find lost element from a duplicated array | Function to find missing element based on binary search approach . arr1 [ ] is of larger size and N is size of it . arr1 [ ] and arr2 [ ] are assumed to be in same order . ; special case , for only element which is missing in second array ; special case , for first element missing ; Initialize current corner points ; loop until lo < hi ; If element at mid indices are equal then go to right subarray ; if lo , hi becomes contiguous , break ; missing element will be at hi index of bigger array ; This function mainly does basic error checking and calls findMissingUtil ; Driver Code
def findMissingUtil ( arr1 , arr2 , N ) : NEW_LINE INDENT if N == 1 : NEW_LINE INDENT return arr1 [ 0 ] ; NEW_LINE DEDENT if arr1 [ 0 ] != arr2 [ 0 ] : NEW_LINE INDENT return arr1 [ 0 ] NEW_LINE DEDENT lo = 0 NEW_LINE hi = N - 1 NEW_LINE while ( lo < hi ) : NEW_LINE INDENT mid = ( lo + hi ) / 2 NEW_LINE if arr1 [ mid ] == arr2 [ mid ] : NEW_LINE INDENT lo = mid NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid NEW_LINE DEDENT if lo == hi - 1 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return arr1 [ hi ] NEW_LINE DEDENT def findMissing ( arr1 , arr2 , M , N ) : NEW_LINE INDENT if N == M - 1 : NEW_LINE INDENT print ( " Missing ▁ Element ▁ is " , findMissingUtil ( arr1 , arr2 , M ) ) NEW_LINE DEDENT elif M == N - 1 : NEW_LINE INDENT print ( " Missing ▁ Element ▁ is " , findMissingUtil ( arr2 , arr1 , N ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid ▁ Input " ) NEW_LINE DEDENT DEDENT arr1 = [ 1 , 4 , 5 , 7 , 9 ] NEW_LINE arr2 = [ 4 , 5 , 7 , 9 ] NEW_LINE M = len ( arr1 ) NEW_LINE N = len ( arr2 ) NEW_LINE findMissing ( arr1 , arr2 , M , N ) NEW_LINE
Find lost element from a duplicated array | This function mainly does XOR of all elements of arr1 [ ] and arr2 [ ] ; Do XOR of all element ; Driver Code
def findMissing ( arr1 , arr2 , M , N ) : NEW_LINE INDENT if ( M != N - 1 and N != M - 1 ) : NEW_LINE INDENT print ( " Invalid ▁ Input " ) NEW_LINE return NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT res = res ^ arr1 [ i ] ; NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT res = res ^ arr2 [ i ] NEW_LINE DEDENT print ( " Missing ▁ element ▁ is " , res ) NEW_LINE DEDENT arr1 = [ 4 , 1 , 5 , 9 , 7 ] NEW_LINE arr2 = [ 7 , 5 , 9 , 4 ] NEW_LINE M = len ( arr1 ) NEW_LINE N = len ( arr2 ) NEW_LINE findMissing ( arr1 , arr2 , M , N ) NEW_LINE
Find the repeating and the missing | Added 3 new methods | Python3 code to Find the repeating and the missing elements ; Driver program to test above function
def printTwoElements ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT if arr [ abs ( arr [ i ] ) - 1 ] > 0 : NEW_LINE INDENT arr [ abs ( arr [ i ] ) - 1 ] = - arr [ abs ( arr [ i ] ) - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ repeating ▁ element ▁ is " , abs ( arr [ i ] ) ) NEW_LINE DEDENT DEDENT for i in range ( size ) : NEW_LINE INDENT if arr [ i ] > 0 : NEW_LINE INDENT print ( " and ▁ the ▁ missing ▁ element ▁ is " , i + 1 ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 7 , 3 , 4 , 5 , 5 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE printTwoElements ( arr , n ) NEW_LINE
Find the repeating and the missing | Added 3 new methods | The output of this function is stored at x and y ; Will hold xor of all elements and numbers from 1 to n ; Get the xor of all array elements ; XOR the previous result with numbers from 1 to n ; Will have only single set bit of xor1 ; Now divide elements into two sets by comparing a rightmost set bit of xor1 with the bit at the same position in each element . Also , get XORs of two sets . The two XORs are the output elements . The following two for loops serve the purpose ; arr [ i ] belongs to first set ; arr [ i ] belongs to second set ; i belongs to first set ; i belongs to second set ; Driver code
def getTwoElements ( arr , n ) : NEW_LINE INDENT global x , y NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE xor1 = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT xor1 = xor1 ^ arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT xor1 = xor1 ^ i NEW_LINE DEDENT set_bit_no = xor1 & ~ ( xor1 - 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & set_bit_no ) != 0 : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i & set_bit_no ) != 0 : NEW_LINE INDENT x = x ^ i NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ i NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 3 , 4 , 5 , 5 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE getTwoElements ( arr , n ) NEW_LINE print ( " The ▁ missing ▁ element ▁ is " , x , " and ▁ the ▁ repeating ▁ number ▁ is " , y ) NEW_LINE
Find the repeating and the missing | Added 3 new methods | Python3 program to find the repeating and missing elements using Maps
def main ( ) : NEW_LINE INDENT arr = [ 4 , 3 , 6 , 2 , 1 , 1 ] NEW_LINE numberMap = { } NEW_LINE max = len ( arr ) NEW_LINE for i in arr : NEW_LINE INDENT if not i in numberMap : NEW_LINE INDENT numberMap [ i ] = True NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Repeating ▁ = " , i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , max + 1 ) : NEW_LINE INDENT if not i in numberMap : NEW_LINE INDENT print ( " Missing ▁ = " , i ) NEW_LINE DEDENT DEDENT DEDENT main ( ) NEW_LINE
Find four elements that sum to a given value | Set 1 ( n ^ 3 solution ) | A naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; Fix the first element and find other three ; Fix the second element and find other two ; Fix the third element and find the fourth ; find the fourth ; Driver program to test above function
def findFourElements ( A , n , X ) : NEW_LINE INDENT for i in range ( 0 , n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if A [ i ] + A [ j ] + A [ k ] + A [ l ] == X : NEW_LINE INDENT print ( " % d , ▁ % d , ▁ % d , ▁ % d " % ( A [ i ] , A [ j ] , A [ k ] , A [ l ] ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT A = [ 10 , 2 , 3 , 4 , 5 , 9 , 7 , 8 ] NEW_LINE n = len ( A ) NEW_LINE X = 23 NEW_LINE findFourElements ( A , n , X ) NEW_LINE
Find four elements that sum to a given value | Set 2 | The function finds four elements with given summ X ; Store summs of all pairs in a hash table ; Traverse through all pairs and search for X - ( current pair summ ) . ; If X - summ is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver code ; Function call
def findFourElements ( arr , n , X ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT mp [ arr [ i ] + arr [ j ] ] = [ i , j ] NEW_LINE DEDENT DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT summ = arr [ i ] + arr [ j ] NEW_LINE if ( X - summ ) in mp : NEW_LINE INDENT p = mp [ X - summ ] NEW_LINE if ( p [ 0 ] != i and p [ 0 ] != j and p [ 1 ] != i and p [ 1 ] != j ) : NEW_LINE INDENT print ( arr [ i ] , " , ▁ " , arr [ j ] , " , ▁ " , arr [ p [ 0 ] ] , " , ▁ " , arr [ p [ 1 ] ] , sep = " " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT arr = [ 10 , 20 , 30 , 40 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE X = 91 NEW_LINE findFourElements ( arr , n , X ) NEW_LINE
Find four elements that sum to a given value | Set 2 | Function to find 4 elements that add up to given sum ; Iterate from 0 to temp . length ; Iterate from 0 to length of arr ; Iterate from i + 1 to length of arr ; Store curr_sum = arr [ i ] + arr [ j ] ; Check if X - curr_sum if present in map ; Store pair having map value X - curr_sum ; Print the output ; Function for two Sum ; Driver code ; Function call
def fourSum ( X , arr , Map , N ) : NEW_LINE INDENT temp = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT curr_sum = arr [ i ] + arr [ j ] NEW_LINE if ( X - curr_sum ) in Map : NEW_LINE INDENT p = Map [ X - curr_sum ] NEW_LINE if ( p [ 0 ] != i and p [ 1 ] != i and p [ 0 ] != j and p [ 1 ] != j and temp [ p [ 0 ] ] == 0 and temp [ p [ 1 ] ] == 0 and temp [ i ] == 0 and temp [ j ] == 0 ) : NEW_LINE INDENT print ( arr [ i ] , " , " , arr [ j ] , " , " , arr [ p [ 0 ] ] , " , " , arr [ p [ 1 ] ] , sep = " " ) NEW_LINE temp [ p [ 1 ] ] = 1 NEW_LINE temp [ i ] = 1 NEW_LINE temp [ j ] = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def twoSum ( nums , N ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT Map [ nums [ i ] + nums [ j ] ] = [ ] NEW_LINE Map [ nums [ i ] + nums [ j ] ] . append ( i ) NEW_LINE Map [ nums [ i ] + nums [ j ] ] . append ( j ) NEW_LINE DEDENT DEDENT return Map NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 40 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE X = 91 NEW_LINE Map = twoSum ( arr , n ) NEW_LINE fourSum ( X , arr , Map , n ) NEW_LINE
Search an element in an array where difference between adjacent elements is 1 | x is the element to be searched in arr [ 0. . n - 1 ] ; Traverse the given array starting from leftmost element ; If x is found at index i ; Jump the difference between current array element and x ; Driver program to test above function
def search ( arr , n , x ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] == x ) : NEW_LINE INDENT return i NEW_LINE DEDENT i = i + abs ( arr [ i ] - x ) NEW_LINE DEDENT print ( " number ▁ is ▁ not ▁ present ! " ) NEW_LINE return - 1 NEW_LINE DEDENT arr = [ 8 , 7 , 6 , 7 , 6 , 5 , 4 , 3 , 2 , 3 , 4 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE x = 3 NEW_LINE print ( " Element " , x , " ▁ is ▁ present ▁ at ▁ index ▁ " , search ( arr , n , 3 ) ) NEW_LINE
Third largest element in an array of distinct elements | Python 3 program to find third Largest element in an array of distinct elements ; There should be atleast three elements ; Find first largest element ; Find second largest element ; Find third largest element ; Driver Code
import sys NEW_LINE def thirdLargest ( arr , arr_size ) : NEW_LINE INDENT if ( arr_size < 3 ) : NEW_LINE INDENT print ( " ▁ Invalid ▁ Input ▁ " ) NEW_LINE return NEW_LINE DEDENT first = arr [ 0 ] NEW_LINE for i in range ( 1 , arr_size ) : NEW_LINE INDENT if ( arr [ i ] > first ) : NEW_LINE INDENT first = arr [ i ] NEW_LINE DEDENT DEDENT second = - sys . maxsize NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT if ( arr [ i ] > second and arr [ i ] < first ) : NEW_LINE INDENT second = arr [ i ] NEW_LINE DEDENT DEDENT third = - sys . maxsize NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT if ( arr [ i ] > third and arr [ i ] < second ) : NEW_LINE INDENT third = arr [ i ] NEW_LINE DEDENT DEDENT print ( " The ▁ Third ▁ Largest " , " element ▁ is " , third ) NEW_LINE DEDENT arr = [ 12 , 13 , 1 , 10 , 34 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE thirdLargest ( arr , n ) NEW_LINE
Third largest element in an array of distinct elements | Python3 program to find third Largest element in an array ; There should be atleast three elements ; Initialize first , second and third Largest element ; Traverse array elements to find the third Largest ; If current element is greater than first , then update first , second and third ; If arr [ i ] is in between first and second ; If arr [ i ] is in between second and third ; Driver Code
import sys NEW_LINE def thirdLargest ( arr , arr_size ) : NEW_LINE INDENT if ( arr_size < 3 ) : NEW_LINE INDENT print ( " ▁ Invalid ▁ Input ▁ " ) NEW_LINE return NEW_LINE DEDENT first = arr [ 0 ] NEW_LINE second = - sys . maxsize NEW_LINE third = - sys . maxsize NEW_LINE for i in range ( 1 , arr_size ) : NEW_LINE INDENT if ( arr [ i ] > first ) : NEW_LINE INDENT third = second NEW_LINE second = first NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > second ) : NEW_LINE INDENT third = second NEW_LINE second = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > third ) : NEW_LINE INDENT third = arr [ i ] NEW_LINE DEDENT DEDENT print ( " The ▁ third ▁ Largest " , " element ▁ is " , third ) NEW_LINE DEDENT arr = [ 12 , 13 , 1 , 10 , 34 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE thirdLargest ( arr , n ) NEW_LINE
Check if there exist two elements in an array whose sum is equal to the sum of rest of the array | Function to check whether two elements exist whose sum is equal to sum of rest of the elements . ; Find sum of whole array ; / If sum of array is not even than we can not divide it into two part ; For each element arr [ i ] , see if there is another element with value sum - arr [ i ] ; If element exist than return the pair ; Driver Code
def checkPair ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if sum % 2 != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT sum = sum / 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT val = sum - arr [ i ] NEW_LINE if arr [ i ] not in s : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT if val in s : NEW_LINE INDENT print ( " Pair ▁ elements ▁ are " , arr [ i ] , " and " , int ( val ) ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 2 , 11 , 5 , 1 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE if checkPair ( arr , n ) == False : NEW_LINE INDENT print ( " No ▁ pair ▁ found " ) NEW_LINE DEDENT
Search an element in an unsorted array using minimum number of comparisons | function to search an element in minimum number of comparisons ; 1 st comparison ; no termination condition and thus no comparison ; this would be executed at - most n times and therefore at - most n comparisons ; replace arr [ n - 1 ] with its actual element as in original 'arr[] ; if ' x ' is found before the ' ( n - 1 ) th ' index , then it is present in the array final comparison ; else not present in the array ; Driver Code
def search ( arr , n , x ) : NEW_LINE INDENT if ( arr [ n - 1 ] == x ) : NEW_LINE INDENT return " Found " NEW_LINE DEDENT backup = arr [ n - 1 ] NEW_LINE arr [ n - 1 ] = x NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] == x ) : NEW_LINE INDENT arr [ n - 1 ] = backup NEW_LINE if ( i < n - 1 ) : NEW_LINE INDENT return " Found " NEW_LINE DEDENT return " Not ▁ Found " NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT DEDENT arr = [ 4 , 6 , 1 , 5 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE x = 1 NEW_LINE print ( search ( arr , n , x ) ) NEW_LINE
Count of only repeated element in a sorted array of consecutive elements | Assumptions : vector a is sorted , max - difference of two adjacent elements is 1 ; if a [ m ] = m + a [ 0 ] , there is no repeating character in [ s . . m ] ; if a [ m ] < m + a [ 0 ] , there is a repeating character in [ s . . m ] ; Driver code
def sequence ( a ) : NEW_LINE INDENT if ( len ( a ) == 0 ) : NEW_LINE INDENT return [ 0 , 0 ] NEW_LINE DEDENT s = 0 NEW_LINE e = len ( a ) - 1 NEW_LINE while ( s < e ) : NEW_LINE INDENT m = ( s + e ) // 2 NEW_LINE if ( a [ m ] >= m + a [ 0 ] ) : NEW_LINE INDENT s = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT e = m NEW_LINE DEDENT DEDENT return [ a [ s ] , len ( a ) - ( a [ len ( a ) - 1 ] - a [ 0 ] ) ] NEW_LINE DEDENT p = sequence ( [ 1 , 2 , 3 , 4 , 4 , 4 , 5 , 6 ] ) NEW_LINE print ( " Repeated ▁ element ▁ is " , p [ 0 ] , " , ▁ it ▁ appears " , p [ 1 ] , " times " ) NEW_LINE
Find element in a sorted array whose frequency is greater than or equal to n / 2. | Python 3 code to find majority element in a sorted array ; Driver Code
def findMajority ( arr , n ) : NEW_LINE INDENT return arr [ int ( n / 2 ) ] NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMajority ( arr , n ) ) NEW_LINE
Minimum absolute difference of adjacent elements in a circular array | Python3 program to find maximum difference between adjacent elements in a circular array . ; Checking normal adjacent elements ; Checking circular link ; Driver Code
def minAdjDifference ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : return NEW_LINE res = abs ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT res = min ( res , abs ( arr [ i ] - arr [ i - 1 ] ) ) NEW_LINE DEDENT res = min ( res , abs ( arr [ n - 1 ] - arr [ 0 ] ) ) NEW_LINE print ( " Min ▁ Difference ▁ = ▁ " , res ) NEW_LINE DEDENT a = [ 10 , 12 , 13 , 15 , 10 ] NEW_LINE n = len ( a ) NEW_LINE minAdjDifference ( a , n ) NEW_LINE
Find the first , second and third minimum elements in an array | A Python program to find the first , second and third minimum element in an array ; Check if current element is less than firstmin , then update first , second and third ; Check if current element is less than secmin then update second and third ; Check if current element is less than , then upadte third ; driver program
MAX = 100000 NEW_LINE def Print3Smallest ( arr , n ) : NEW_LINE INDENT firstmin = MAX NEW_LINE secmin = MAX NEW_LINE thirdmin = MAX NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] < firstmin : NEW_LINE INDENT thirdmin = secmin NEW_LINE secmin = firstmin NEW_LINE firstmin = arr [ i ] NEW_LINE DEDENT elif arr [ i ] < secmin : NEW_LINE INDENT thirdmin = secmin NEW_LINE secmin = arr [ i ] NEW_LINE DEDENT elif arr [ i ] < thirdmin : NEW_LINE INDENT thirdmin = arr [ i ] NEW_LINE DEDENT DEDENT print ( " First ▁ min ▁ = ▁ " , firstmin ) NEW_LINE print ( " Second ▁ min ▁ = ▁ " , secmin ) NEW_LINE print ( " Third ▁ min ▁ = ▁ " , thirdmin ) NEW_LINE DEDENT arr = [ 4 , 9 , 1 , 32 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE Print3Smallest ( arr , n ) NEW_LINE
Program to find the minimum ( or maximum ) element of an array | Python3 program to find minimum ( or maximum ) element in an array . ; If there is single element , return it . Else return minimum of first element and minimum of remaining array . ; If there is single element , return it . Else return maximum of first element and maximum of remaining array . ; Driver code
def getMin ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT return min ( getMin ( arr [ 1 : ] , n - 1 ) , arr [ 0 ] ) NEW_LINE DEDENT DEDENT def getMax ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT return max ( getMax ( arr [ 1 : ] , n - 1 ) , arr [ 0 ] ) NEW_LINE DEDENT DEDENT arr = [ 12 , 1234 , 45 , 67 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ element ▁ of ▁ array : ▁ " , getMin ( arr , n ) ) ; NEW_LINE print ( " Maximum ▁ element ▁ of ▁ array : ▁ " , getMax ( arr , n ) ) ; NEW_LINE
Program to find the minimum ( or maximum ) element of an array | Python3 program to find minimum ( or maximum ) element in an array . ; Driver Code
def getMin ( arr , n ) : NEW_LINE INDENT return min ( arr ) NEW_LINE DEDENT def getMax ( arr , n ) : NEW_LINE INDENT return max ( arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 1234 , 45 , 67 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ element ▁ of ▁ array : ▁ " , getMin ( arr , n ) ) NEW_LINE print ( " Maximum ▁ element ▁ of ▁ array : ▁ " , getMax ( arr , n ) ) NEW_LINE DEDENT
Closest greater element for every array element from another array | Python implementation to find result from target array for closest element ; Function for printing resultant array ; sort list for ease ; list for result ; calculate resultant array ; check location of upper bound element ; if no element found push - 1 ; else puch the element ; add to resultant ; Driver code
import bisect NEW_LINE def closestResult ( a , b , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE c = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT up = bisect . bisect_right ( a , b [ i ] ) NEW_LINE if up == n : NEW_LINE INDENT c . append ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT c . append ( a [ up ] ) NEW_LINE DEDENT DEDENT print ( " Result ▁ = ▁ " , end = " " ) NEW_LINE for i in c : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 5 , 6 , 1 , 8 , 9 ] NEW_LINE b = [ 2 , 1 , 0 , 5 , 4 , 9 ] NEW_LINE n = len ( a ) NEW_LINE closestResult ( a , b , n ) NEW_LINE DEDENT
Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Hashmap ; Traverse all array elements ; Update the frequency of array [ i ] ; Increase the index ; Driver code
def findCounts ( arr , n ) : NEW_LINE INDENT hash = [ 0 for i in range ( n ) ] NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT hash [ arr [ i ] - 1 ] += 1 NEW_LINE i += 1 NEW_LINE DEDENT print ( " Below ▁ are ▁ counts ▁ of ▁ all ▁ elements " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " - > " , hash [ i ] , end = " ▁ " ) NEW_LINE print ( ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 3 , 2 , 5 ] NEW_LINE findCounts ( arr , len ( arr ) ) NEW_LINE arr1 = [ 1 ] NEW_LINE findCounts ( arr1 , len ( arr1 ) ) NEW_LINE arr3 = [ 4 , 4 , 4 , 4 ] NEW_LINE findCounts ( arr3 , len ( arr3 ) ) NEW_LINE arr2 = [ 1 , 3 , 5 , 7 , 9 , 1 , 3 , 5 , 7 , 9 , 1 ] NEW_LINE findCounts ( arr2 , len ( arr2 ) ) NEW_LINE arr4 = [ 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 ] NEW_LINE findCounts ( arr4 , len ( arr4 ) ) NEW_LINE arr5 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] NEW_LINE findCounts ( arr5 , len ( arr5 ) ) NEW_LINE arr6 = [ 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ] NEW_LINE findCounts ( arr6 , len ( arr6 ) ) NEW_LINE
Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Traverse all array elements ; If this element is already processed , then nothing to do ; Find index corresponding to this element For example , index for 5 is 4 ; If the elementIndex has an element that is not processed yet , then first store that element to arr [ i ] so that we don 't lose anything. ; After storing arr [ elementIndex ] , change it to store initial count of 'arr[i] ; If this is NOT first occurrence of arr [ i ] , then decrement its count . ; And initialize arr [ i ] as 0 means the element ' i + 1' is not seen so far ; Driver program to test above function
def findCounts ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE while i < n : NEW_LINE INDENT if arr [ i ] <= 0 : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT elementIndex = arr [ i ] - 1 NEW_LINE if arr [ elementIndex ] > 0 : NEW_LINE INDENT arr [ i ] = arr [ elementIndex ] NEW_LINE arr [ elementIndex ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ elementIndex ] -= 1 NEW_LINE arr [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT print ( " Below ▁ are ▁ counts ▁ of ▁ all ▁ elements " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( " % d ▁ - > ▁ % d " % ( i + 1 , abs ( arr [ i ] ) ) ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT arr = [ 2 , 3 , 3 , 2 , 5 ] NEW_LINE findCounts ( arr , len ( arr ) ) NEW_LINE arr1 = [ 1 ] NEW_LINE findCounts ( arr1 , len ( arr1 ) ) NEW_LINE arr3 = [ 4 , 4 , 4 , 4 ] NEW_LINE findCounts ( arr3 , len ( arr3 ) ) NEW_LINE arr2 = [ 1 , 3 , 5 , 7 , 9 , 1 , 3 , 5 , 7 , 9 , 1 ] NEW_LINE findCounts ( arr2 , len ( arr2 ) ) NEW_LINE arr4 = [ 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 ] NEW_LINE findCounts ( arr4 , len ( arr4 ) ) NEW_LINE arr5 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] NEW_LINE findCounts ( arr5 , len ( arr5 ) ) NEW_LINE arr6 = [ 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ] NEW_LINE findCounts ( arr6 , len ( arr6 ) ) NEW_LINE
Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Subtract 1 from every element so that the elements become in range from 0 to n - 1 ; Use every element arr [ i ] as index and add ' n ' to element present at arr [ i ] % n to keep track of count of occurrences of arr [ i ] ; To print counts , simply print the number of times n was added at index corresponding to every element ; Driver code
def printfrequency ( arr , n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT arr [ j ] = arr [ j ] - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ arr [ i ] % n ] = arr [ arr [ i ] % n ] + n NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " - > " , arr [ i ] // n ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 3 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE printfrequency ( arr , n ) NEW_LINE
Delete an element from array ( Using two traversals and one traversal ) | This function removes an element x from arr [ ] and returns new size after removal ( size is reduced only when x is present in arr [ ] ; Search x in array ; If x found in array ; reduce size of array and move all elements on space ahead ; Driver Code ; Delete x from arr [ ]
def deleteElement ( arr , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == x ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i < n ) : NEW_LINE INDENT n = n - 1 ; NEW_LINE for j in range ( i , n , 1 ) : NEW_LINE INDENT arr [ j ] = arr [ j + 1 ] NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 15 , 6 , 8 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE x = 6 NEW_LINE n = deleteElement ( arr , n , x ) NEW_LINE print ( " Modified ▁ array ▁ is " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Delete an element from array ( Using two traversals and one traversal ) | This function removes an element x from arr [ ] and returns new size after removal . Returned size is n - 1 when element is present . Otherwise 0 is returned to indicate failure . ; If x is last element , nothing to do ; Start from rightmost element and keep moving elements one position ahead . ; If element was not found ; Else move the next element in place of x ; Driver code ; Delete x from arr [ ]
def deleteElement ( arr , n , x ) : NEW_LINE INDENT if arr [ n - 1 ] == x : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT prev = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] != x : NEW_LINE INDENT curr = arr [ i ] NEW_LINE arr [ i ] = prev NEW_LINE prev = curr NEW_LINE DEDENT DEDENT if i < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr [ i ] = prev NEW_LINE return n - 1 NEW_LINE DEDENT arr = [ 11 , 15 , 6 , 8 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE x = 6 NEW_LINE n = deleteElement ( arr , n , x ) NEW_LINE print ( " Modified ▁ array ▁ is " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Count Inversions of size three in a given array | Returns count of inversions of size 3 ; Initialize result ; Count all smaller elements on right of arr [ i ] ; Count all greater elements on left of arr [ i ] ; Update inversion count by adding all inversions that have arr [ i ] as middle of three elements ; Driver program to test above function
def getInvCount ( arr , n ) : NEW_LINE INDENT invcount = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT small = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT small += 1 NEW_LINE DEDENT DEDENT great = 0 ; NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] ) : NEW_LINE INDENT great += 1 NEW_LINE DEDENT DEDENT invcount += great * small NEW_LINE DEDENT return invcount NEW_LINE DEDENT arr = [ 8 , 4 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Inversion ▁ Count ▁ : " , getInvCount ( arr , n ) ) NEW_LINE
Trapping Rain Water | Function to return the maximum water that can be stored ; To store the maximum water that can be stored ; For every element of the array ; Find the maximum element on its left ; Find the maximum element on its right ; Update the maximum water ; Driver code
def maxWater ( arr , n ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT left = arr [ i ] ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT left = max ( left , arr [ j ] ) ; NEW_LINE DEDENT right = arr [ i ] ; NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT right = max ( right , arr [ j ] ) ; NEW_LINE DEDENT res = res + ( min ( left , right ) - arr [ i ] ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxWater ( arr , n ) ) ; NEW_LINE DEDENT
Trapping Rain Water | Python program to find maximum amount of water that can be trapped within given set of bars . ; left [ i ] contains height of tallest bar to the left of i 'th bar including itself ; Right [ i ] contains height of tallest bar to the right of ith bar including itself ; Initialize result ; Fill left array ; Fill right array ; Calculate the accumulated water element by element consider the amount of water on i 'th bar, the amount of water accumulated on this particular bar will be equal to min(left[i], right[i]) - arr[i] . ; Driver program
def findWater ( arr , n ) : NEW_LINE INDENT left = [ 0 ] * n NEW_LINE right = [ 0 ] * n NEW_LINE water = 0 NEW_LINE left [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT left [ i ] = max ( left [ i - 1 ] , arr [ i ] ) NEW_LINE DEDENT right [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT right [ i ] = max ( right [ i + 1 ] , arr [ i ] ) ; NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT water += min ( left [ i ] , right [ i ] ) - arr [ i ] NEW_LINE DEDENT return water NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ water ▁ that ▁ can ▁ be ▁ accumulated ▁ is " , findWater ( arr , n ) ) NEW_LINE
Trapping Rain Water | Python program to find maximum amount of water that can be trapped within given set of bars . Space Complexity : O ( 1 ) ; initialize output ; maximum element on left and right ; indices to traverse the array ; update max in left ; water on curr element = max - curr ; update right maximum ; Driver program
def findWater ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE left_max = 0 NEW_LINE right_max = 0 NEW_LINE lo = 0 NEW_LINE hi = n - 1 NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT if ( arr [ lo ] < arr [ hi ] ) : NEW_LINE INDENT if ( arr [ lo ] > left_max ) : NEW_LINE INDENT left_max = arr [ lo ] NEW_LINE DEDENT else : NEW_LINE INDENT result += left_max - arr [ lo ] NEW_LINE DEDENT lo += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( arr [ hi ] > right_max ) : NEW_LINE INDENT right_max = arr [ hi ] NEW_LINE DEDENT else : NEW_LINE INDENT result += right_max - arr [ hi ] NEW_LINE DEDENT hi -= 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ water ▁ that ▁ can ▁ be ▁ accumulated ▁ is ▁ " , findWater ( arr , n ) ) NEW_LINE
Trapping Rain Water | Function to return the maximum water that can be stored ; Let the first element be stored as previous , we shall loop from index 1 ; To store previous wall 's index ; To store the water until a larger wall is found , if there are no larger walls then delete temp value from water ; If the current wall is taller than the previous wall then make current wall as the previous wall and its index as previous wall 's index for the subsequent loops ; Because larger or same height wall is found ; Since current wall is shorter than the previous , we subtract previous wall ' s ▁ height ▁ from ▁ the ▁ current ▁ wall ' s height and add it to the water ; Store the same value in temp as well If we dont find any larger wall then we will subtract temp from water ; If the last wall was larger than or equal to the previous wall then prev_index would be equal to size of the array ( last element ) If we didn 't find a wall greater than or equal to the previous wall from the left then prev_index must be less than the index of the last element ; Temp would ' ve ▁ stored ▁ the ▁ water ▁ collected ▁ ▁ from ▁ previous ▁ largest ▁ wall ▁ till ▁ the ▁ end ▁ ▁ of ▁ array ▁ if ▁ no ▁ larger ▁ wall ▁ was ▁ found ▁ then ▁ ▁ it ▁ has ▁ excess ▁ water ▁ and ▁ remove ▁ that ▁ ▁ from ▁ ' water ' var ; We start from the end of the array , so previous should be assigned to the last element ; Loop from the end of array up to the ' previous ▁ index ' which would contain the " largest ▁ wall ▁ from ▁ the ▁ left " ; Right end wall will be definitely smaller than the ' previous ▁ index ' wall ; Return the maximum water ; Driver code
def maxWater ( arr , n ) : NEW_LINE INDENT size = n - 1 NEW_LINE prev = arr [ 0 ] NEW_LINE prev_index = 0 NEW_LINE water = 0 NEW_LINE temp = 0 NEW_LINE for i in range ( 1 , size + 1 ) : NEW_LINE INDENT if ( arr [ i ] >= prev ) : NEW_LINE INDENT prev = arr [ i ] NEW_LINE prev_index = i NEW_LINE temp = 0 NEW_LINE DEDENT else : NEW_LINE INDENT water += prev - arr [ i ] NEW_LINE temp += prev - arr [ i ] NEW_LINE DEDENT DEDENT if ( prev_index < size ) : NEW_LINE INDENT water -= temp NEW_LINE prev = arr [ size ] NEW_LINE for i in range ( size , prev_index - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] >= prev ) : NEW_LINE INDENT prev = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT water += prev - arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return water NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxWater ( arr , n ) ) NEW_LINE
Trapping Rain Water | Function to return the maximum water that can be stored ; Stores the indices of the bars ; size of the array ; Stores the final result ; Loop through the each bar ; Remove bars from the stack until the condition holds ; store the height of the top and pop it . ; If the stack does not have any bars or the the popped bar has no left boundary ; Get the distance between the left and right boundary of popped bar ; Calculate the min . height ; If the stack is either empty or height of the current bar is less than or equal to the top bar of stack ; Driver code
def maxWater ( height ) : NEW_LINE INDENT stack = [ ] NEW_LINE n = len ( height ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( len ( stack ) != 0 and ( height [ stack [ - 1 ] ] < height [ i ] ) ) : NEW_LINE INDENT pop_height = height [ stack [ - 1 ] ] NEW_LINE stack . pop ( ) NEW_LINE if ( len ( stack ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT distance = i - stack [ - 1 ] - 1 NEW_LINE min_height = min ( height [ stack [ - 1 ] ] , height [ i ] ) - pop_height NEW_LINE ans += distance * min_height NEW_LINE DEDENT stack . append ( i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE print ( maxWater ( arr ) ) NEW_LINE
Trapping Rain Water | Function to return the maximum water that can be stored ; indices to traverse the array ; To store Left max and right max for two pointers left and right ; To store the total amount of rain water trapped ; We need check for minimum of left and right max for each element ; Add the difference between current value and right max at index r ; Update right max ; Update right pointer ; Add the difference between current value and left max at index l ; Update left max ; Update left pointer ; Driver code
def maxWater ( arr , n ) : NEW_LINE INDENT left = 0 NEW_LINE right = n - 1 NEW_LINE l_max = 0 NEW_LINE r_max = 0 NEW_LINE result = 0 NEW_LINE while ( left <= right ) : NEW_LINE INDENT if r_max <= l_max : NEW_LINE INDENT result += max ( 0 , r_max - arr [ right ] ) NEW_LINE r_max = max ( r_max , arr [ right ] ) NEW_LINE right -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT result += max ( 0 , l_max - arr [ left ] ) NEW_LINE l_max = max ( l_max , arr [ left ] ) NEW_LINE left += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxWater ( arr , n ) ) NEW_LINE
Median of two sorted arrays with different sizes in O ( log ( min ( n , m ) ) ) | Python code for median with case of returning double value when even number of elements are present in both array combinely ; def to find max ; def to find minimum ; def to find median of two sorted arrays ; if i = n , it means that Elements from a [ ] in the second half is an empty set . and if j = 0 , it means that Elements from b [ ] in the first half is an empty set . so it is necessary to check that , because we compare elements from these two groups . Searching on right ; if i = 0 , it means that Elements from a [ ] in the first half is an empty set and if j = m , it means that Elements from b [ ] in the second half is an empty set . so it is necessary to check that , because we compare elements from these two groups . searching on left ; we have found the desired halves . ; this condition happens when we don 't have any elements in the first half from a[] so we returning the last element in b[] from the first half. ; and this condition happens when we don 't have any elements in the first half from b[] so we returning the last element in a[] from the first half. ; calculating the median . If number of elements is odd there is one middle element . ; Elements from a [ ] in the second half is an empty set . ; Elements from b [ ] in the second half is an empty set . ; Driver code ; we need to define the smaller array as the first parameter to make sure that the time complexity will be O ( log ( min ( n , m ) ) )
median = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE def maximum ( a , b ) : NEW_LINE INDENT return a if a > b else b NEW_LINE DEDENT def minimum ( a , b ) : NEW_LINE INDENT return a if a < b else b NEW_LINE DEDENT def findMedianSortedArrays ( a , n , b , m ) : NEW_LINE INDENT global median , i , j NEW_LINE min_index = 0 NEW_LINE max_index = n NEW_LINE while ( min_index <= max_index ) : NEW_LINE INDENT i = int ( ( min_index + max_index ) / 2 ) NEW_LINE j = int ( ( ( n + m + 1 ) / 2 ) - i ) NEW_LINE if ( i < n and j > 0 and b [ j - 1 ] > a [ i ] ) : NEW_LINE INDENT min_index = i + 1 NEW_LINE DEDENT elif ( i > 0 and j < m and b [ j ] < a [ i - 1 ] ) : NEW_LINE INDENT max_index = i - 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT median = b [ j - 1 ] NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT median = a [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT median = maximum ( a [ i - 1 ] , b [ j - 1 ] ) NEW_LINE DEDENT break NEW_LINE DEDENT DEDENT if ( ( n + m ) % 2 == 1 ) : NEW_LINE INDENT return median NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT return ( ( median + b [ j ] ) / 2.0 ) NEW_LINE DEDENT if ( j == m ) : NEW_LINE INDENT return ( ( median + a [ i ] ) / 2.0 ) NEW_LINE DEDENT return ( ( median + minimum ( a [ i ] , b [ j ] ) ) / 2.0 ) NEW_LINE DEDENT a = [ 900 ] NEW_LINE b = [ 10 , 13 , 14 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if ( n < m ) : NEW_LINE INDENT print ( " The ▁ median ▁ is ▁ : ▁ { } " . format ( findMedianSortedArrays ( a , n , b , m ) ) ) NEW_LINE DEDENT else : NEW_LINE INDENT echo ( " The ▁ median ▁ is ▁ : ▁ { } " . format ( findMedianSortedArrays ( b , m , a , n ) ) ) NEW_LINE DEDENT
Median of two sorted arrays with different sizes in O ( log ( min ( n , m ) ) ) | Function to find median of given two sorted arrays ; if i = n , it means that Elements from a [ ] in the second half is an empty set . If j = 0 , it means that Elements from b [ ] in the first half is an empty set . so it is necessary to check that , because we compare elements from these two groups . searching on right ; if i = 0 , it means that Elements from a [ ] in the first half is an empty set and if j = m , it means that Elements from b [ ] in the second half is an a [ ] in the first half is an empty set that , because we compare elements from these two groups . searching on left ; we have found the desired halves . ; this condition happens when we don 't have any elements in the first half from a[] so we returning the last element in b[] from the first half. ; and this condition happens when we don 't have any elements in the first half from b[] so we returning the last element in a[] from the first half. ; Function to find maximum ; Driver code ; we need to define the smaller array as the first parameter to make sure that the time complexity will be O ( log ( min ( n , m ) ) )
def findMedianSortedArrays ( a , n , b , m ) : NEW_LINE INDENT min_index = 0 NEW_LINE max_index = n NEW_LINE while ( min_index <= max_index ) : NEW_LINE INDENT i = ( min_index + max_index ) // 2 NEW_LINE j = ( ( n + m + 1 ) // 2 ) - i NEW_LINE if ( i < n and j > 0 and b [ j - 1 ] > a [ i ] ) : NEW_LINE INDENT min_index = i + 1 NEW_LINE DEDENT elif ( i > 0 and j < m and b [ j ] < a [ i - 1 ] ) : NEW_LINE INDENT max_index = i - 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return b [ j - 1 ] NEW_LINE DEDENT if ( j == 0 ) : NEW_LINE INDENT return a [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return maximum ( a [ i - 1 ] , b [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT print ( " ERROR ! ! ! ▁ " , " returning " ) NEW_LINE return 0 NEW_LINE DEDENT def maximum ( a , b ) : NEW_LINE INDENT return a if a > b else b NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 900 ] NEW_LINE b = [ 10 , 13 , 14 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if ( n < m ) : NEW_LINE INDENT print ( " The ▁ median ▁ is : ▁ " , findMedianSortedArrays ( a , n , b , m ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ median ▁ is : ▁ " , findMedianSortedArrays ( b , m , a , n ) ) NEW_LINE DEDENT DEDENT
Print uncommon elements from two sorted arrays | Python 3 program to find uncommon elements of two sorted arrays ; If not common , print smaller ; Skip common element ; printing remaining elements ; Driver code
def printUncommon ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE while ( i < n1 and j < n2 ) : NEW_LINE INDENT if ( arr1 [ i ] < arr2 [ j ] ) : NEW_LINE INDENT print ( arr1 [ i ] , end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE k = k + 1 NEW_LINE DEDENT elif ( arr2 [ j ] < arr1 [ i ] ) : NEW_LINE INDENT print ( arr2 [ j ] , end = " ▁ " ) NEW_LINE k = k + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT while ( i < n1 ) : NEW_LINE INDENT print ( arr1 [ i ] , end = " ▁ " ) NEW_LINE i = i + 1 NEW_LINE k = k + 1 NEW_LINE DEDENT while ( j < n2 ) : NEW_LINE INDENT print ( arr2 [ j ] , end = " ▁ " ) NEW_LINE j = j + 1 NEW_LINE k = k + 1 NEW_LINE DEDENT DEDENT arr1 = [ 10 , 20 , 30 ] NEW_LINE arr2 = [ 20 , 25 , 30 , 40 , 50 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE n2 = len ( arr2 ) NEW_LINE printUncommon ( arr1 , arr2 , n1 , n2 ) NEW_LINE
Least frequent element in an array | Python 3 program to find the least frequent element in an array . ; Sort the array ; find the min frequency using linear traversal ; If last element is least frequent ; Driver program
def leastFrequent ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE min_count = n + 1 NEW_LINE res = - 1 NEW_LINE curr_count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT curr_count = curr_count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( curr_count < min_count ) : NEW_LINE INDENT min_count = curr_count NEW_LINE res = arr [ i - 1 ] NEW_LINE DEDENT curr_count = 1 NEW_LINE DEDENT DEDENT if ( curr_count < min_count ) : NEW_LINE INDENT min_count = curr_count NEW_LINE res = arr [ n - 1 ] NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( leastFrequent ( arr , n ) ) NEW_LINE
Least frequent element in an array | Python3 program to find the most frequent element in an array . ; Insert all elements in Hash . ; find the max frequency ; Driver Code
import math as mt NEW_LINE def leastFrequent ( arr , n ) : NEW_LINE INDENT Hash = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in Hash . keys ( ) : NEW_LINE INDENT Hash [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Hash [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT min_count = n + 1 NEW_LINE res = - 1 NEW_LINE for i in Hash : NEW_LINE INDENT if ( min_count >= Hash [ i ] ) : NEW_LINE INDENT res = i NEW_LINE min_count = Hash [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( leastFrequent ( arr , n ) ) NEW_LINE