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 ...
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...
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 ...
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 ...
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 ...
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 element...
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...
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 element...
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 ] ...
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 ; NE...
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 ) ...
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 s...
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...
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...
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 i...
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 ] ,...
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 =...
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 l...
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_...
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 ...
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 ,...
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 _ _ ' :...
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 el...
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 ; ...
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 , upda...
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 NE...
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 num...
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 ...
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 o...
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 = ...
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 ( findM...
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 ; Dr...
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 (...
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...
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 r...
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 NE...
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_p...
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 +=...
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 no...
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 ...
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 ...
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 t...
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 ] ...
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 ;...
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 & - ...
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...
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 la...
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...
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 ,...
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 ...
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_...
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...
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 minim...
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 eli...
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 dist...
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 e...
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 . ; Driv...
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 (...
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 l...
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_LIN...
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 ...
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 ] ...
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 , ...
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...
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 ...
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 ret...
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 = l...
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...
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 IND...
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 ...
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...
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 ...
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 i...
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...
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 . ; Driv...
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 ] : N...
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 elemen...
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 ...
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 ...
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 ...
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 D...
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 ...
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 ] ;...
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_LIN...
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 ; ...
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...
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 DEDEN...
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 ( countOccu...
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...
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 re...
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 ther...
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 ]...
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...
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 mi...
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 ]...
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 =...
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 ] ) ) N...
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 tw...
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 - ...
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...
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 p...
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 (...
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 element...
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 sum...
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...
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 ] !...
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 ,...
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_...
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 f...
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 INDEN...
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...
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...
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 it...
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 ) :...
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 cod...
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...
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 ▁ D...
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 i...
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 eli...
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 e...
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...
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 : ▁ " , g...
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 - ...
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_LI...
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 , " ...
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 t...
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 ...
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 ...
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...
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 ...
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...
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 elem...
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 ...
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 prog...
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 ) ...
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 ( righ...
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 ...
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 ,...
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...
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...
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 w...
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 ...
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...
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 ( l...
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 betwee...
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 ...
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 Eleme...
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 ...
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 ...
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...
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 ...
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 ...
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_...