text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Find the only missing number in a sorted array | PYTHON 3 program to find the only missing element . ; If this is the first element which is not index + 1 , then missing element is mid + 1 ; if this is not the first missing element search in left side ; if it follows index + 1 property then search in right side ; if no... | def findmissing ( ar , N ) : NEW_LINE INDENT l = 0 NEW_LINE r = N - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) / 2 NEW_LINE mid = int ( mid ) NEW_LINE if ( ar [ mid ] != mid + 1 and ar [ mid - 1 ] == mid ) : NEW_LINE INDENT return ( mid + 1 ) NEW_LINE DEDENT elif ( ar [ mid ] != mid + 1 ) : NEW_LINE ... |
Find index of first occurrence when an unsorted array is sorted | Python3 program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ; ; Driver Code | import math NEW_LINE def findFirst ( arr , n , x ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ptr = lowerBound ( arr , 0 , n , x ) NEW_LINE return 1 if ( ptr != x ) else ( ptr - arr ) NEW_LINE DEDENT def lowerBound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = low + ( hig... |
Find index of first occurrence when an unsorted array is sorted | Python 3 program to find index of first occurrence of x when array is sorted . ; Driver Code | def findFirst ( arr , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE isX = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == x ) : NEW_LINE INDENT isX = True NEW_LINE DEDENT elif ( arr [ i ] < x ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return - 1 if ( isX == False ) else count NEW_LINE ... |
Find duplicate in an array in O ( n ) and by using O ( 1 ) extra space | Function to find duplicate ; Find the intersection point of the slow and fast . ; Find the " entrance " to the cycle . ; Driver code | def findDuplicate ( arr ) : NEW_LINE INDENT slow = arr [ 0 ] NEW_LINE fast = arr [ 0 ] NEW_LINE while True : NEW_LINE INDENT slow = arr [ slow ] NEW_LINE fast = arr [ arr [ fast ] ] NEW_LINE if slow == fast : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT ptr1 = arr [ 0 ] NEW_LINE ptr2 = slow NEW_LINE while ptr1 != ptr2 ... |
Number of Larger Elements on right side in a string | Python3 program to count greater characters on right side of every character . ; Arrays to store result and character counts . ; start from right side of string ; Driver code | MAX_CHAR = 26 ; NEW_LINE def printGreaterCount ( str1 ) : NEW_LINE INDENT len1 = len ( str1 ) ; NEW_LINE ans = [ 0 ] * len1 ; NEW_LINE count = [ 0 ] * MAX_CHAR ; NEW_LINE for i in range ( len1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE for j in range ( ord ( str1 [ ... |
Print all pairs with given sum | Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to sum ; Store counts of all elements in a dictionary ; Traverse through all the elements ; Search if a pair can be formed with arr [ i ] ; Driver code | def printPairs ( arr , n , sum ) : NEW_LINE INDENT mydict = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = sum - arr [ i ] NEW_LINE if temp in mydict : NEW_LINE INDENT count = mydict [ temp ] NEW_LINE for j in range ( count ) : NEW_LINE INDENT print ( " ( " , temp , " , β " , arr [ i ] , " ) " , sep = ... |
Maximum product quadruple ( sub | A O ( n ) Python 3 program to find maximum quadruple inan array . ; Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Initialize Maximum , second maximum , third maximum and fourth maximum element ; Initial... | import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxA = - sys . maxsize - 1 NEW_LINE maxB = - sys . maxsize - 1 NEW_LINE maxC = - sys . maxsize - 1 NEW_LINE maxD = - sys . maxsize - 1 NEW_LINE minA = sys . maxsize NEW_LINE minB = sys . maxsize NE... |
Ways to choose three points with distance between the most distant points <= L | Returns the number of triplets with distance between farthest points <= L ; sort to get ordered triplets so that we can find the distance between farthest points belonging to a triplet ; generate and check for all possible triplets : { arr... | def countTripletsLessThanL ( n , L , arr ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ways = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT mostDistantDistance = arr [ k ] - arr [ i ] NEW_LINE if ( mostDistantDistance <= L )... |
Triplets in array with absolute difference less than k | Return the lower bound i . e smallest index of element having value greater or equal to value ; Return the number of triplet indices satisfies the three constraints ; sort the array ; for each element from index 2 to n - 1. ; finding the lower bound of arr [ i ] ... | def binary_lower ( value , arr , n ) : NEW_LINE INDENT start = 0 NEW_LINE end = n - 1 NEW_LINE ans = - 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( arr [ mid ] >= value ) : NEW_LINE INDENT end = mid - 1 NEW_LINE ans = mid NEW_LINE DEDENT else : NEW_LINE INDENT start = mid... |
Minimize the sum of roots of a given polynomial | Python3 program to find minimum sum of roots of a given polynomial ; resultant list ; a lis that store indices of the positive elements ; a list that store indices of the negative elements ; Case - 1 : ; Case - 2 : ; Case - 3 : ; Case - 4 : ; Driver code | import sys NEW_LINE def getMinimumSum ( arr , n ) : NEW_LINE INDENT res = [ ] NEW_LINE pos = [ ] NEW_LINE neg = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT elif ( arr [ i ] < 0 ) : NEW_LINE INDENT neg . append ( i ) NEW_LINE DEDENT DEDENT... |
Longest Palindromic Substring using Palindromic Tree | Set 3 | Python3 code for Longest Palindromic substring using Palindromic Tree data structure ; store start and end indexes of current Node inclusively ; Stores length of substring ; stores insertion Node for all characters a - z ; stores the Maximum Palindromic Suf... | class Node : NEW_LINE INDENT def __init__ ( self , length = None , suffixEdge = None ) : NEW_LINE INDENT self . start = None NEW_LINE self . end = None NEW_LINE self . length = length NEW_LINE self . insertionEdge = [ 0 ] * 26 NEW_LINE self . suffixEdge = suffixEdge NEW_LINE DEDENT tree = [ Node ( ) for i in range ( MA... |
Find the one missing number in range | Find the missing number in a range ; here we xor of all the number ; xor last number ; Driver method | def missingNum ( arr , n ) : NEW_LINE INDENT minvalue = min ( arr ) NEW_LINE xornum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT xornum ^= ( minvalue ) ^ arr [ i ] NEW_LINE minvalue = minvalue + 1 NEW_LINE DEDENT return xornum ^ minvalue NEW_LINE DEDENT arr = [ 13 , 12 , 11 , 15 ] NEW_LINE n = len ( arr ) NE... |
Find last index of a character in a string | Returns last index of x if it is present . Else returns - 1. ; String in which char is to be found ; char whose index is to be found | def findLastIndex ( str , x ) : NEW_LINE INDENT index = - 1 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if str [ i ] == x : NEW_LINE INDENT index = i NEW_LINE DEDENT DEDENT return index NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE x = ' e ' NEW_LINE index = findLastIndex ( str , x ) NEW_LINE if in... |
Find last index of a character in a string | Returns last index of x if it is present . Else returns - 1. ; Traverse from right ; Driver code | def findLastIndex ( str , x ) : NEW_LINE INDENT for i in range ( len ( str ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == x ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE x = ' e ' NEW_LINE index = findLastIndex ( str , x ) NEW_LINE if ( index ==... |
Smallest number whose set bits are maximum in a given range | Returns smallest number whose set bits are maximum in given range . ; driver code | def countMaxSetBits ( left , right ) : NEW_LINE INDENT while ( left | ( left + 1 ) ) <= right : NEW_LINE INDENT left |= left + 1 NEW_LINE DEDENT return left NEW_LINE DEDENT l = 1 NEW_LINE r = 5 NEW_LINE print ( countMaxSetBits ( l , r ) ) NEW_LINE l = 1 NEW_LINE r = 10 NEW_LINE print ( countMaxSetBits ( l , r ) ) NEW_L... |
Largest number less than or equal to N in BST ( Iterative Approach ) | Python3 code to find the largest value smaller than or equal to N ; To create new BST Node ; To insert a new node in BST ; If tree is empty return new node ; If key is less then or greater then node value then recur down the tree ; Return the ( unch... | class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . key = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if ( key < node . key ... |
Find if given number is sum of first n natural numbers | Function to find no . of elements to be added to get s ; Apply Binary search ; Find mid ; find sum of 1 to mid natural numbers using formula ; If sum is equal to n return mid ; If greater than n do r = mid - 1 ; else do l = mid + 1 ; If not possible , return - 1 ... | def findS ( s ) : NEW_LINE INDENT l = 1 NEW_LINE r = int ( s / 2 ) + 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = int ( ( l + r ) / 2 ) NEW_LINE sum = int ( mid * ( mid + 1 ) / 2 ) NEW_LINE if ( sum == s ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( sum > s ) : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT... |
Search in an array of strings where non | Compare two string equals are not ; Main function to find string location ; Move mid to the middle ; If mid is empty , find closest non - empty string ; If mid is empty , search in both sides of mid and find the closest non - empty string , and set mid accordingly . ; If str is... | def compareStrings ( str1 , str2 ) : NEW_LINE INDENT i = 0 NEW_LINE while i < len ( str1 ) - 1 and str1 [ i ] == str2 [ i ] : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if str1 [ i ] > str2 [ i ] : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return str1 [ i ] < str2 [ i ] NEW_LINE DEDENT def searchStr ( arr , string , first... |
Rearrange array elements to maximize the sum of MEX of all prefix arrays | Function to find the maximum sum of MEX of prefix arrays for any arrangement of the given array ; Stores the final arrangement ; Sort the array in increasing order ; Iterate over the array arr [ ] ; Iterate over the array , arr [ ] and push the ... | def maximumMex ( arr , N ) : NEW_LINE INDENT ans = [ ] NEW_LINE arr = sorted ( arr ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i == 0 or arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT ans . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( i > 0 and arr [ i ] == arr [ i ... |
Sort an array using Bubble Sort without using loops | Function to implement bubble sort without using loops ; Base Case : If array contains a single element ; Base Case : If array contains two elements ; Store the first two elements of the list in variables a and b ; Store remaining elements in the list bs ; Store the ... | def bubble_sort ( ar ) : NEW_LINE INDENT if len ( ar ) <= 1 : NEW_LINE INDENT return ar NEW_LINE DEDENT if len ( ar ) == 2 : NEW_LINE INDENT return ar if ar [ 0 ] < ar [ 1 ] else [ ar [ 1 ] , ar [ 0 ] ] NEW_LINE DEDENT a , b = ar [ 0 ] , ar [ 1 ] NEW_LINE bs = ar [ 2 : ] NEW_LINE res = [ ] NEW_LINE if a < b : NEW_LINE ... |
Modify a given matrix by placing sorted boundary elements in clockwise manner | Function to print the elements of the matrix in row - wise manner ; Function to sort boundary elements of a matrix starting from the outermost to the innermost boundary and place them in a clockwise manner ; k - starting row index m - endin... | def printMatrix ( a ) : NEW_LINE INDENT for x in a : NEW_LINE INDENT for y in x : NEW_LINE INDENT print ( y , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def sortBoundaryWise ( a ) : NEW_LINE INDENT k = 0 NEW_LINE l = 0 NEW_LINE m = len ( a ) NEW_LINE n = len ( a [ 0 ] ) NEW_LINE n_k = 0 NEW_LINE n_l... |
Minimum sum of absolute differences between pairs of a triplet from an array | Python 3 Program for the above approach ; Function to find minimum sum of absolute differences of pairs of a triplet ; Sort the array ; Stores the minimum sum ; Traverse the array ; Update the minimum sum ; Print the minimum sum ; Driver Cod... | import sys NEW_LINE def minimum_sum ( A , N ) : NEW_LINE INDENT A . sort ( reverse = False ) NEW_LINE sum = sys . maxsize NEW_LINE for i in range ( N - 2 ) : NEW_LINE INDENT sum = min ( sum , abs ( A [ i ] - A [ i + 1 ] ) + abs ( A [ i + 1 ] - A [ i + 2 ] ) ) NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ ==... |
Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters | Function to check if all characters of the string can be made the same ; Sort the string ; Calculate ASCII value of the median character ; Stores the minimum number of operations required to make all chara... | def sameChar ( S , N ) : NEW_LINE INDENT S = ' ' . join ( sorted ( S ) ) NEW_LINE mid = ord ( S [ N // 2 ] ) NEW_LINE total_operations = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT total_operations += abs ( ord ( S [ i ] ) - mid ) NEW_LINE DEDENT print ( total_operations ) NEW_LINE DEDENT S = " geeks " NEW_LINE N... |
Maximum score possible from an array with jumps of at most length K | Python program for the above approach ; Function to count the maximum score of an index ; Base Case ; If the value for the current index is pre - calculated ; Calculate maximum score for all the steps in the range from i + 1 to i + k ; Score for inde... | import sys NEW_LINE def maxScore ( i , A , K , N , dp ) : NEW_LINE INDENT if ( i >= N - 1 ) : NEW_LINE INDENT return A [ N - 1 ] ; NEW_LINE DEDENT if ( dp [ i ] != - 1 ) : NEW_LINE INDENT return dp [ i ] ; NEW_LINE DEDENT score = 1 - sys . maxsize ; NEW_LINE for j in range ( 1 , K + 1 ) : NEW_LINE INDENT score = max ( ... |
Count triplets from an array which can form quadratic equations with real roots | Function to find the count of triplets ( a , b , c ) Such that the equations ax ^ 2 + bx + c = 0 has real roots ; store count of triplets ( a , b , c ) such that ax ^ 2 + bx + c = 0 has real roots ; base case ; Generate all possible tripl... | def getcount ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE if ( N < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for b in range ( 0 , N ) : NEW_LINE INDENT for a in range ( 0 , N ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT continue NEW_LINE DEDENT for c in range ( 0 , N ) : NEW_LINE INDENT if ( c == a or c... |
Check if all array elements can be reduced to less than X | Function to check if all array elements can be reduced to less than X or not ; Checks if all array elements are already a X or not ; Traverse every possible pair ; Calculate GCD of two array elements ; If gcd is a 1 ; If gcd is a X , then a pair is present to ... | def findAns ( A , N , X ) : NEW_LINE INDENT if ( check ( A , X ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE gcd = GCD ( A [ i ] , A [ j ] ) NEW_LINE if ( gcd != 1 ) : NEW_LINE INDENT if ( gcd <= X ) : NEW_LINE return True NEW_LINE DEDEN... |
Check if X and Y elements can be selected from two arrays respectively such that the maximum in X is less than the minimum in Y | Function to check if it is possible to choose X and Y elements from a [ ] and b [ ] such that maximum element among X element is less than minimum element among Y elements ; Check if there a... | def check ( a , b , Na , Nb , k , m ) : NEW_LINE INDENT if ( Na < k or Nb < m ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT a . sort ( ) NEW_LINE a . sort ( ) NEW_LINE if ( a [ k - 1 ] < b [ Nb - m ] ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT arr1 = [ 1 , 2 , 3 ] NEW_LINE arr2 ... |
Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum | Function to split the array into two subset such that the Bitwise XOR between the maximum of one subset and minimum of other is minimum ; Sort the array in increasing order ; Calculating the min Bitwise XOR between consecutive... | def splitArray ( arr , N ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE result = 10 ** 9 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT result = min ( result , arr [ i ] ^ arr [ i - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 2 , 6 , 4 ] ... |
Sort an array by left shifting digits of array elements | Function to check if an array is sorted in increasing order or not ; Traverse the array ; Function to sort the array by left shifting digits of array elements ; Stores previous array element ; Traverse the array arr [ ] ; Stores current element ; Stores current ... | def isIncreasing ( arr ) : NEW_LINE INDENT for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT if arr [ i ] > arr [ i + 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def sortArr ( arr ) : NEW_LINE INDENT prev = - 1 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT optEle... |
Activity selection problem with K persons | Python3 program for the above approach ; Function to find maximum shops that can be visited by K persons ; Store opening and closing time of shops ; Sort the pair of array ; Stores the result ; Stores current number of persons visiting some shop with their ending time ; Check... | from bisect import bisect_left NEW_LINE def maximumShops ( opening , closing , n , k ) : NEW_LINE INDENT a = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] [ 0 ] = opening [ i ] NEW_LINE a [ i ] [ 1 ] = closing [ i ] NEW_LINE DEDENT a = sorted ( a ) NEW_LINE count = 1 NEW_LIN... |
Maximize maximum possible subarray sum of an array by swapping with elements from another array | Function to find the maximum subarray sum possible by swapping elements from array arr [ ] with that from array brr [ ] ; Stores elements from the arrays arr [ ] and brr [ ] ; Store elements of array arr [ ] and brr [ ] in... | def maxSum ( arr , brr , N , K ) : NEW_LINE INDENT crr = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT crr . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( K ) : NEW_LINE INDENT crr . append ( brr [ i ] ) NEW_LINE DEDENT crr = sorted ( crr ) [ : : - 1 ] NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_... |
Count pairs with Bitwise XOR greater than both the elements of the pair | Function that counts the pairs whose Bitwise XOR is greater than both the elements of pair ; Stores the count of pairs ; Generate all possible pairs ; Find the Bitwise XOR ; Find the maximum of two ; If xo < mx , increment count ; Print the value... | def countPairs ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT xo = ( A [ i ] ^ A [ j ] ) NEW_LINE mx = max ( A [ i ] , A [ j ] ) NEW_LINE if ( xo > mx ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NE... |
Possible arrangement of persons waiting to sit in a hall | Function to find the arrangement of seating ; Stores the row in which the ith person sits ; Stores the width of seats along with their index or row number ; Sort the array ; Store the seats and row for boy 's seat ; Stores the index of row upto which boys have ... | def findTheOrder ( arr , s , N ) : NEW_LINE INDENT ans = [ ] NEW_LINE A = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT A [ i ] = [ arr [ i ] , i + 1 ] NEW_LINE DEDENT A = sorted ( A ) NEW_LINE q = [ ] NEW_LINE index = 0 NEW_LINE for i in range ( 2 * N ) : NEW_LINE INDENT if ( s [ i ] == ... |
Difference between sum of K maximum even and odd array elements | Function to find the absolute difference between sum of first K maximum even and odd numbers ; Stores index from where odd number starts ; Segregate even and odd number ; If current element is even ; Sort in decreasing order even part ; Sort in decreasin... | def evenOddDiff ( a , n , k ) : NEW_LINE INDENT j = - 1 NEW_LINE even = [ ] NEW_LINE odd = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT even . append ( a [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT odd . append ( a [ i ] ) NEW_LINE DEDENT DEDENT j += 1 NEW_LINE even .... |
Rearrange array to make product of prefix sum array non zero | Function to rearrange array that satisfies the given condition ; Stores sum of elements of the given array ; Calculate totalSum ; If the totalSum is equal to 0 ; No possible way to rearrange array ; If totalSum exceeds 0 ; Rearrange the array in descending ... | def rearrangeArr ( arr , N ) : NEW_LINE INDENT totalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT if ( totalSum == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT elif ( totalSum > 0 ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE print ( * arr , sep = ' β ... |
Split array into two equal length subsets such that all repetitions of a number lies in a single subset | Python3 program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store freque... | from collections import defaultdict NEW_LINE def findSubsets ( arr ) : NEW_LINE INDENT M = defaultdict ( int ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 NEW_LINE DEDENT subsets = [ 0 ] * len ( M ) NEW_LINE i = 0 NEW_LINE for j in M : NEW_LINE INDENT subsets [ i ] = M [ j ] NEW_LINE ... |
Count ways to distribute exactly one coin to each worker | Python3 program for the above approach ; Function to find number of way to distribute coins giving exactly one coin to each person ; Sort the given arrays ; Start from bigger salary ; Increment the amount ; Reduce amount of valid coins by one each time ; Return... | MOD = 1000000007 NEW_LINE def solve ( values , salary ) : NEW_LINE INDENT ret = 1 NEW_LINE amt = 0 NEW_LINE values = sorted ( values ) NEW_LINE salary = sorted ( salary ) NEW_LINE while ( len ( salary ) > 0 ) : NEW_LINE INDENT while ( ( len ( values ) and values [ - 1 ] >= salary [ - 1 ] ) ) : NEW_LINE INDENT amt += 1 ... |
Count of index pairs with equal elements in an array | Set 2 | Function that counts the pair in the array arr [ ] ; Sort the array ; Initialize two pointers ; Add all valid pairs to answer ; Return the answer ; Driver Code ; Given array arr [ ] ; Function call | def countPairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE arr . sort ( ) NEW_LINE left = 0 NEW_LINE right = 1 ; NEW_LINE while ( right < n ) : NEW_LINE INDENT if ( arr [ left ] == arr [ right ] ) : NEW_LINE INDENT ans += right - left ; NEW_LINE DEDENT else : NEW_LINE INDENT left = right ; NEW_LINE DEDENT right += 1... |
Maximize the Sum of the given array using given operations | Comparator to sort the array in ascending order ; Function to maximise the sum of the given array ; Stores { A [ i ] , B [ i ] } pairs ; Sort in descending order of the values in the array A [ ] ; Stores the maximum sum ; If B [ i ] is equal to 0 ; Simply add... | def compare ( p1 , p2 ) : NEW_LINE INDENT return p1 [ 0 ] > p2 [ 0 ] NEW_LINE DEDENT def maximiseScore ( A , B , K , N ) : NEW_LINE INDENT pairs = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pairs . append ( [ A [ i ] , B [ i ] ] ) NEW_LINE DEDENT pairs . sort ( key = lambda x : x [ 0 ] , reverse = True ) NEW_L... |
Minimize Cost to sort a String in Increasing Order of Frequencies of Characters | Python3 program to implement the above approach ; For a single character ; Stores count of repetitions of a character ; If repeating character ; Otherwise ; Store frequency ; Reset count ; Insert the last character block ; Sort the freque... | def sortString ( S ) : NEW_LINE INDENT sorted1 = [ ] NEW_LINE original = [ ] NEW_LINE insert = False NEW_LINE if ( len ( S ) == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT curr = 1 NEW_LINE for i in range ( len ( S ) - 1 ) : NEW_LINE INDENT if ( S [ i ] == S [ i + 1 ] ) : NEW_LINE INDENT curr += 1 NEW_LINE insert... |
Sort numbers based on count of letters required to represent them in words | letters [ i ] stores the count of letters required to represent the digit i ; Function to return the sum of letters required to represent N ; Function to sort the array according to the sum of letters to represent n ; List to store the digit s... | letters = [ 4 , 3 , 3 , 3 , 4 , 4 , 3 , 5 , 5 , 4 ] NEW_LINE def sumOfLetters ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += letters [ n % 10 ] NEW_LINE n = n // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] NEW_LINE for i in range ( ... |
Divide a sorted array in K parts with sum of difference of max and min minimized in each part | Function to find the minimum sum of differences possible for the given array when the array is divided into K subarrays ; Array to store the differences between two adjacent elements ; Iterating through the array ; Appending... | def calculate_minimum_split ( a , k ) : NEW_LINE INDENT p = [ ] NEW_LINE n = len ( a ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT p . append ( a [ i ] - a [ i - 1 ] ) NEW_LINE DEDENT p . sort ( reverse = True ) NEW_LINE min_sum = sum ( p [ : k - 1 ] ) NEW_LINE res = a [ n - 1 ] - a [ 0 ] - min_sum NEW_LINE ret... |
Sort an Array of dates in ascending order using Custom Comparator | Python3 implementation to sort the array of dates in the form of " DD - MM - YYYY " using custom comparator ; Comparator to sort the array of dates ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function tha... | from functools import cmp_to_key NEW_LINE def myCompare ( date1 , date2 ) : NEW_LINE INDENT day1 = date1 [ 0 : 2 ] NEW_LINE month1 = date1 [ 3 : 3 + 2 ] NEW_LINE year1 = date1 [ 6 : 6 + 4 ] NEW_LINE day2 = date2 [ 0 : 2 ] NEW_LINE month2 = date2 [ 3 : 3 + 2 ] NEW_LINE year2 = date2 [ 6 : 6 + 4 ] NEW_LINE if ( year1 < y... |
Sort an Array of Strings according to the number of Vowels in them | Function to check the Vowel ; Returns count of vowels in str ; Check for vowel ; Function to sort the array according to the number of the vowels ; Vector to store the number of vowels with respective elements ; Inserting number of vowels with respect... | def isVowel ( ch ) : NEW_LINE INDENT ch = ch . upper ( ) ; NEW_LINE return ( ch == ' A ' or ch == ' E ' or ch == ' I ' or ch == ' O ' or ch == ' U ' ) ; NEW_LINE DEDENT def countVowels ( string ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( isVowel ( string [ i ] ) ) :... |
Find the minimum cost to cross the River | Function to return the minimum cost ; Sort the price array ; Calculate minimum price of n - 2 most costly person ; Both the ways as discussed above ; Calculate the minimum price of the two cheapest person ; Driver code | def minimumCost ( price , n ) : NEW_LINE INDENT price = sorted ( price ) NEW_LINE totalCost = 0 NEW_LINE for i in range ( n - 1 , 1 , - 2 ) : NEW_LINE INDENT if ( i == 2 ) : NEW_LINE INDENT totalCost += price [ 2 ] + price [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT price_first = price [ i ] + price [ 0 ] + 2 * price ... |
Minimize the sum of differences of consecutive elements after removing exactly K elements | Python3 implementation of the above approach . ; states of DP ; function to find minimum sum ; base - case ; if state is solved before , return ; marking the state as solved ; recurrence relation ; driver function ; input values... | import numpy as np NEW_LINE N = 100 NEW_LINE INF = 1000000 NEW_LINE dp = np . zeros ( ( N , N ) ) ; NEW_LINE vis = np . zeros ( ( N , N ) ) ; NEW_LINE def findSum ( arr , n , k , l , r ) : NEW_LINE INDENT if ( ( l ) + ( n - 1 - r ) == k ) : NEW_LINE INDENT return arr [ r ] - arr [ l ] ; NEW_LINE DEDENT if ( vis [ l ] [... |
Find Kth element in an array containing odd elements first and then even elements | Function to return the kth element in the modified array ; Finding the index from where the even numbers will be stored ; Return the kth element ; Driver code | def getNumber ( n , k ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT pos = n // 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT pos = ( n // 2 ) + 1 ; NEW_LINE DEDENT if ( k <= pos ) : NEW_LINE INDENT return ( k * 2 - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( k - pos ) * 2 ) ; NEW_LINE DEDENT DEDENT i... |
All unique combinations whose sum equals to K | Function to find all unique combination of given elements such that their sum is K ; If a unique combination is found ; For all other combinations ; Check if the sum exceeds K ; Check if it is repeated or not ; Take the element into the combination ; Recursive call ; Remo... | def unique_combination ( l , sum , K , local , A ) : NEW_LINE INDENT if ( sum == K ) : NEW_LINE INDENT print ( " { " , end = " " ) NEW_LINE for i in range ( len ( local ) ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT print ( local [ i ] , end = " " ) NEW_LINE if ( i != ... |
Find the longest string that can be made up of other strings from the array | Function that returns true if string s can be made up of by other two string from the array after concatenating one after another ; If current string has been processed before ; If current string is found in the map and it is not the string u... | def canbuildword ( s , isoriginalword , mp ) : NEW_LINE INDENT if s in mp and mp [ s ] == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if s in mp and mp [ s ] == 1 and isoriginalword == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT left = s [ : i ] NEW_LINE right... |
Find a triplet in an array whose sum is closest to a given number | Python3 implementation of the above approach ; Function to return the sum of a triplet which is closest to x ; To store the closest sum ; Run three nested loops each loop for each element of triplet ; Update the closestSum ; Return the closest sum foun... | import sys NEW_LINE def solution ( arr , x ) : NEW_LINE INDENT closestSum = sys . maxsize NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT for k in range ( j + 1 , len ( arr ) ) : NEW_LINE INDENT if ( abs ( x - closestSum ) > abs ( x - ( arr [ i ] + arr ... |
Build original array from the given sub | Python3 implementation of the approach ; Function to add edge to graph ; Function to calculate indegrees of all the vertices ; If there is an edge from i to x then increment indegree of x ; Function to perform topological sort ; Push every node to the queue which has no incomin... | from collections import deque NEW_LINE adj = [ [ ] for i in range ( 100 ) ] NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE DEDENT def getindeg ( V , indeg ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT for x in adj [ i ] : NEW_LINE INDENT indeg [ x ] += 1 NEW_LINE DEDENT ... |
Sum of Semi | Vector to store the primes ; Create a boolean array " prime [ 0 . . n ] " ; Initialize along prime values to be true ; If prime [ p ] is not changed then it is a prime ; Update amultiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already bee... | pr = [ ] NEW_LINE prime = [ 1 for i in range ( 10000000 + 1 ) ] NEW_LINE def sieve ( n ) : NEW_LINE INDENT for p in range ( 2 , n ) : NEW_LINE INDENT if p * p > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = Fal... |
Compress the array into Ranges | Function to compress the array ranges ; start iteration from the ith array element ; loop until arr [ i + 1 ] == arr [ i ] and increment j ; if the program do not enter into the above while loop this means that ( i + 1 ) th element is not consecutive to i th element ; increment i for ne... | def compressArr ( arr , n ) : NEW_LINE INDENT i = 0 ; NEW_LINE j = 0 ; NEW_LINE arr . sort ( ) ; NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i ; NEW_LINE while ( ( j + 1 < n ) and ( arr [ j + 1 ] == arr [ j ] + 1 ) ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT print ( arr [ i ] , end =... |
Remove elements to make array sorted | Function to sort the array by removing misplaced elements ; brr [ ] is used to store the sorted array elements ; Print the sorted array ; Driver code | def removeElements ( arr , n ) : NEW_LINE INDENT brr = [ 0 ] * n ; l = 1 ; NEW_LINE brr [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( brr [ l - 1 ] <= arr [ i ] ) : NEW_LINE INDENT brr [ l ] = arr [ i ] ; NEW_LINE l += 1 ; NEW_LINE DEDENT DEDENT for i in range ( l ) : NEW_LINE INDENT prin... |
Remove elements to make array sorted | Function to sort the array by removing misplaced elements ; l stores the index ; Print the sorted array ; Driver code | def removeElements ( arr , n ) : NEW_LINE INDENT l = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ l - 1 ] <= arr [ i ] ) : NEW_LINE INDENT arr [ l ] = arr [ i ] NEW_LINE l += 1 NEW_LINE DEDENT DEDENT for i in range ( l ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if _... |
Find number from its divisors | Python3 implementation of the approach Function that returns X ; Function that returns X ; Sort the given array ; Get the possible X ; Container to store divisors ; Find the divisors of x ; Check if divisor ; sort the vec because a is sorted and we have to compare all the elements ; if s... | import math NEW_LINE def findX ( list , int ) : NEW_LINE INDENT list . sort ( ) NEW_LINE x = list [ 0 ] * list [ int - 1 ] NEW_LINE vec = [ ] NEW_LINE i = 2 NEW_LINE while ( i * i <= x ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT vec . append ( i ) NEW_LINE if ( ( x // i ) != i ) : NEW_LINE INDENT vec . appe... |
Program to print an array in Pendulum Arrangement with constant space | Function to print the Pendulum arrangement of the given array ; Sort the array ; pos stores the index of the last element of the array ; odd stores the last odd index in the array ; Move all odd index positioned elements to the right ; Shift the el... | def pendulumArrangement ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE pos = n - 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT odd = n - 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd = n - 2 NEW_LINE DEDENT while ( odd > 0 ) : NEW_LINE INDENT temp = arr [ odd ] NEW_LINE in1 = odd NEW_LINE while (... |
Find all the pairs with given sum in a BST | Set 2 | A binary tree node ; Function to append a node to the BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Function to find the target pairs ; LeftList which stores the left side values ; RightList which stores the right side values ; cu... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def AddNode ( root , data ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT root = Node ( data ) NEW_LINE return root NEW_LINE DEDENT if ( ... |
Minimum number greater than the maximum of array which cannot be formed using the numbers in the array | Function that returns the minimum number greater than Maximum of the array that cannot be formed using the elements of the array ; Sort the given array ; Maximum number in the array ; table [ i ] will store the mini... | def findNumber ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE Max = arr [ n - 1 ] NEW_LINE table = [ 10 ** 9 for i in range ( ( 2 * Max ) + 1 ) ] NEW_LINE table [ 0 ] = 0 NEW_LINE ans = - 1 NEW_LINE for i in range ( 1 , 2 * Max + 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] <... |
Product of all Subsequences of size K except the minimum and maximum Elements | Python 3 program to find product of all Subsequences of size K except the minimum and maximum Elements ; 2D array to store value of combinations nCr ; Function to pre - calculate value of all combinations nCr ; Function to calculate product... | MOD = 1000000007 NEW_LINE max = 101 NEW_LINE C = [ [ 0 for i in range ( max ) ] for j in range ( max ) ] NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % MOD NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % MOD NEW_LINE DEDENT y = y >> 1 NEW_LINE x = (... |
Bitwise AND of N binary strings | this function takes two unequal sized bit strings , converts them to same length by adding leading 0 s in the smaller string . Returns the the new length ; Return len_b which is highest . No need to proceed further ! ; Return len_a which is greater or equal to len_b ; The main function... | def makeEqualLength ( a , b ) : NEW_LINE INDENT len_a = len ( a ) NEW_LINE len_b = len ( b ) NEW_LINE num_zeros = abs ( len_a - len_b ) NEW_LINE if ( len_a < len_b ) : NEW_LINE INDENT for i in range ( num_zeros ) : NEW_LINE INDENT a = '0' + a NEW_LINE DEDENT return len_b , a , b NEW_LINE DEDENT else : NEW_LINE INDENT f... |
Maximum number of segments that can contain the given points | Function to return the maximum number of segments ; Sort both the vectors ; Initially pointing to the first element of b [ ] ; Try to find a match in b [ ] ; The segment ends before b [ j ] ; The point lies within the segment ; The segment starts after b [ ... | def countPoints ( n , m , a , b , x , y ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE j , count = 0 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT while j < m : NEW_LINE INDENT if a [ i ] + y < b [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT if ( b [ j ] >= a [ i ] - x and b [ j ] <= a [ i ] ... |
Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ) | Python3 program to merge K sorted arrays ; Merge and sort k arrays ; Put the elements in sorted array . ; Sort the output array ; Driver Function ; Input 2D - array ; Number of arrays ; Output array ; Print merged array | N = 4 NEW_LINE def merge_and_sort ( output , arr , n , k ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT output [ i * n + j ] = arr [ i ] [ j ] ; NEW_LINE DEDENT DEDENT output . sort ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 5 , 7 ,... |
Minimum operations of given type to make all elements of a matrix equal | Function to return the minimum number of operations required ; Create another array to store the elements of matrix ; will not work for negative elements , so . . adding this ; adding this to handle negative elements too . ; Sort the array to get... | def minOperations ( n , m , k , matrix ) : NEW_LINE INDENT arr = [ ] NEW_LINE if ( matrix [ 0 ] [ 0 ] < 0 ) : NEW_LINE INDENT mod = k - ( abs ( matrix [ 0 ] [ 0 ] ) % k ) NEW_LINE DEDENT else : NEW_LINE INDENT mod = matrix [ 0 ] [ 0 ] % k NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW... |
Smallest subarray containing minimum and maximum values | Python3 implementation of above approach ; Function to return length of smallest subarray containing both maximum and minimum value ; find maximum and minimum values in the array ; iterate over the array and set answer to smallest difference between position of ... | import sys NEW_LINE def minSubarray ( A , n ) : NEW_LINE INDENT minValue = min ( A ) NEW_LINE maxValue = max ( A ) NEW_LINE pos_min , pos_max , ans = - 1 , - 1 , sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] == minValue : NEW_LINE INDENT pos_min = i NEW_LINE DEDENT if A [ i ] == maxValue ... |
Minimum number of consecutive sequences that can be formed in an array | Python3 program find the minimum number of consecutive sequences in an array ; Driver program ; function call to print required answer | def countSequences ( arr , n ) : NEW_LINE INDENT count = 1 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] + 1 != arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 7 , ... |
Minimum number of increment / decrement operations such that array contains all elements from 1 to N | Function to find the minimum operations ; Sort the given array ; Count operations by assigning a [ i ] = i + 1 ; Driver Code | def minimumMoves ( a , n ) : NEW_LINE INDENT operations = 0 NEW_LINE a . sort ( reverse = False ) NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT operations = operations + abs ( a [ i ] - ( i + 1 ) ) NEW_LINE DEDENT return operations NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , ... |
Print a case where the given sorting algorithm fails | Function to print a case where the given sorting algorithm fails ; only case where it fails ; Driver Code | def printCase ( n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE printCase ( n ) NEW_LINE DEDENT |
Find the missing elements from 1 to M in given N ranges | Function to find missing elements from given Ranges ; First of all sort all the given ranges ; store ans in a different vector ; prev is use to store end of last range ; j is used as a counter for ranges ; for last segment ; finally print all answer ; Driver Cod... | def findMissingNumber ( ranges , m ) : NEW_LINE INDENT ranges . sort ( ) NEW_LINE ans = [ ] NEW_LINE prev = 0 NEW_LINE for j in range ( len ( ranges ) ) : NEW_LINE INDENT start = ranges [ j ] [ 0 ] NEW_LINE end = ranges [ j ] [ 1 ] NEW_LINE for i in range ( prev + 1 , start ) : NEW_LINE INDENT ans . append ( i ) NEW_LI... |
Check whether it is possible to make both arrays equal by modifying a single element | Function to check if both sequences can be made equal ; Sorting both the arrays ; Flag to tell if there are more than one mismatch ; To stores the index of mismatched element ; If there is more than one mismatch then return False ; I... | def check ( n , k , a , b ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE fl = False NEW_LINE ind = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT if ( fl == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT fl = True NEW_LINE ind = i NEW_LINE DEDENT ... |
Sum of width ( max and min diff ) of all Subsequences | Function to return sum of width of all subsets ; Sort the array ; Driver program | def SubseqWidths ( A ) : NEW_LINE INDENT MOD = 10 ** 9 + 7 NEW_LINE N = len ( A ) NEW_LINE A . sort ( ) NEW_LINE pow2 = [ 1 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pow2 . append ( pow2 [ - 1 ] * 2 % MOD ) NEW_LINE DEDENT ans = 0 NEW_LINE for i , x in enumerate ( A ) : NEW_LINE INDENT ans = ( ans + ( pow2 ... |
Covering maximum array elements with given value | Function to find value for covering maximum array elements ; sort the students in ascending based on the candies ; To store the number of happy students ; To store the running sum ; If the current student can 't be made happy ; increment the count if we can make the it... | def maxArrayCover ( a , n , x ) : NEW_LINE INDENT a . sort ( ) NEW_LINE cc = 0 NEW_LINE s = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += a [ i ] NEW_LINE if ( s > x ) : NEW_LINE INDENT break NEW_LINE DEDENT cc += 1 NEW_LINE DEDENT if ( sum ( a ) == x ) : NEW_LINE INDENT return n NEW_LINE DEDENT else : NEW_LIN... |
Check if a Linked List is Pairwise Sorted | Linked List node ; Function to check if linked list is pairwise sorted ; Traverse further only if there are at - least two nodes left ; Function to add a node at the beginning of Linked List ; allocate node ; put in the data ; link the old list off the new node ; move the hea... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT start = None NEW_LINE def isPairWiseSorted ( head ) : NEW_LINE INDENT flag = True NEW_LINE temp = head NEW_LINE while ( temp != None and temp . next != None ) : NEW_LINE INDE... |
Maximum Sum of Products of Two Arrays | Function that calculates maximum sum of products of two arrays ; Variable to store the sum of products of array elements ; length of the arrays ; Sorting both the arrays ; Traversing both the arrays and calculating sum of product ; Driver code | def maximumSOP ( a , b ) : NEW_LINE INDENT sop = 0 NEW_LINE n = len ( a ) NEW_LINE a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT sop += a [ i ] * b [ i ] NEW_LINE DEDENT return sop NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 ] NEW_LINE B = [ 4 ,... |
Count number of triplets with product equal to given number | Set 2 | Function to count such triplets ; Sort the array ; three pointer technique ; Calculate the product of a triplet ; Check if that product is greater than m , decrement mid ; Check if that product is smaller than m , increment start ; Check if that prod... | def countTriplets ( arr , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for end in range ( n - 1 , 1 , - 1 ) : NEW_LINE INDENT start = 0 NEW_LINE mid = end - 1 NEW_LINE while ( start < mid ) : NEW_LINE INDENT prod = ( arr [ end ] * arr [ start ] * arr [ mid ] ) NEW_LINE if ( prod > m ) : NEW_LINE... |
Equally divide into two sets such that one set has maximum distinct elements | Python3 program to equally divide n elements into two sets such that second set has maximum distinct elements . ; Insert all the resources in the set There will be unique resources in the set ; return minimum of distinct resources and n / 2 ... | def distribution ( arr , n ) : NEW_LINE INDENT resources = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT resources . add ( arr [ i ] ) ; NEW_LINE DEDENT return min ( len ( resources ) , n // 2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 3 , 4 ] ; NEW_LINE n = ... |
Sort 3 numbers | Python3 program to sort an array of size 3 ; Insert arr [ 1 ] ; Insert arr [ 2 ] ; Driver code | def sort3 ( arr ) : NEW_LINE INDENT if ( arr [ 1 ] < arr [ 0 ] ) : NEW_LINE INDENT arr [ 0 ] , arr [ 1 ] = arr [ 1 ] , arr [ 0 ] NEW_LINE DEDENT if ( arr [ 2 ] < arr [ 1 ] ) : NEW_LINE INDENT arr [ 1 ] , arr [ 2 ] = arr [ 2 ] , arr [ 1 ] NEW_LINE if ( arr [ 1 ] < arr [ 0 ] ) : NEW_LINE INDENT arr [ 1 ] , arr [ 0 ] = ar... |
Merge Sort with O ( 1 ) extra space merge and O ( n lg n ) time [ Unsigned Integers Only ] | Python3 program to sort an array using merge sort such that merge operation takes O ( 1 ) extra space . ; Obtaining actual values ; Recursive merge sort with extra parameter , naxele ; This functions finds max element and calls... | def merge ( arr , beg , mid , end , maxele ) : NEW_LINE INDENT i = beg NEW_LINE j = mid + 1 NEW_LINE k = beg NEW_LINE while ( i <= mid and j <= end ) : NEW_LINE INDENT if ( arr [ i ] % maxele <= arr [ j ] % maxele ) : NEW_LINE INDENT arr [ k ] = arr [ k ] + ( arr [ i ] % maxele ) * maxele NEW_LINE k += 1 NEW_LINE i += ... |
Print triplets with sum less than k | Python3 program to print triplets with sum smaller than a given value ; Sort input array ; 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 ; I... | def printTriplets ( arr , n , sum ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT ( j , k ) = ( i + 1 , n - 1 ) NEW_LINE while ( j < k ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT for x in range... |
Sort string of characters using Stack | function to print the characters in sorted order ; primary stack ; secondary stack ; append first character ; iterate for all character in string ; i - th character ASCII ; stack 's top element ASCII ; if greater or equal to top element then push to stack ; if smaller , then push... | def printSorted ( s , l ) : NEW_LINE INDENT stack = [ ] NEW_LINE tempstack = [ ] NEW_LINE stack . append ( s [ 0 ] ) NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT a = ord ( s [ i ] ) NEW_LINE b = ord ( stack [ - 1 ] ) NEW_LINE if ( ( a - b ) >= 1 or ( a == b ) ) : NEW_LINE INDENT stack . append ( s [ i ] ) NEW_LI... |
Check whether an array can be fit into another array rearranging the elements in the array | Returns true if the array A can be fit into array B , otherwise false ; Sort both the arrays ; Iterate over the loop and check whether every array element of A is less than or equal to its corresponding array element of B ; Dri... | def checkFittingArrays ( A , B , N ) : NEW_LINE INDENT A = sorted ( A ) NEW_LINE B = sorted ( B ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] > B [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT A = [ 7 , 5 , 3 , 2 ] NEW_LINE B = [ 5 , 4 , 8 , 7 ] NEW_LINE N = l... |
Maximise the number of toys that can be purchased with amount K | This functions returns the required number of toys ; sort the cost array ; Check if we can buy ith toy or not ; Increment the count variable ; Driver Code | def maximum_toys ( cost , N , K ) : NEW_LINE INDENT count = 0 NEW_LINE sum = 0 NEW_LINE cost . sort ( reverse = False ) NEW_LINE for i in range ( 0 , N , 1 ) : NEW_LINE INDENT if ( sum + cost [ i ] <= K ) : NEW_LINE INDENT sum = sum + cost [ i ] NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if... |
Find if k bookings possible with given arrival and departure times | Python Code Implementation of the above approach ; Driver Code | def areBookingsPossible ( A , B , K ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if i + K < len ( A ) and A [ i + K ] < B [ i ] : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LI... |
Insertion Sort by Swapping Elements | Recursive python program to sort an array by swapping elements ; Utility function to print a Vector ; Function to perform Insertion Sort recursively ; General Case Sort V till second last element and then insert last element into V ; Insertion step ; Insert V [ i ] into list 0. . i... | import math NEW_LINE def printVector ( V ) : NEW_LINE INDENT for i in V : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT print ( " β " ) NEW_LINE DEDENT def insertionSortRecursive ( V , N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT insertionSortRecursive ( V , N - 1 ) NEW_LIN... |
Check if given array is almost sorted ( elements are at | Function for checking almost sort ; One by one compare adjacents . ; check whether resultant is sorted or not ; Is resultant is sorted return true ; Driver Code | def almostSort ( A , n ) : NEW_LINE INDENT i = 0 NEW_LINE while i < n - 1 : NEW_LINE INDENT if A [ i ] > A [ i + 1 ] : NEW_LINE INDENT A [ i ] , A [ i + 1 ] = A [ i + 1 ] , A [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if A [ i ] > A [ i + 1 ] : NEW_LINE I... |
Efficiently merging two sorted arrays with O ( 1 ) extra space | Function to find next gap . ; comparing elements in the first array . ; comparing elements in both arrays . ; comparing elements in the second array . ; Driver code ; Function Call | def nextGap ( gap ) : NEW_LINE INDENT if ( gap <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( gap // 2 ) + ( gap % 2 ) NEW_LINE DEDENT def merge ( arr1 , arr2 , n , m ) : NEW_LINE INDENT gap = n + m NEW_LINE gap = nextGap ( gap ) NEW_LINE while gap > 0 : NEW_LINE INDENT i = 0 NEW_LINE while i + gap < n : NE... |
Merge two sorted arrays | Merge arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] into arr3 [ 0. . n1 + n2 - 1 ] ; Traverse both array ; Check if current element of first array is smaller than current element of second array . If yes , store first array element and increment first array index . Otherwise do same with secon... | def mergeArrays ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT arr3 = [ None ] * ( n1 + n2 ) NEW_LINE 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 arr3 [ k ] = arr1 [ i ] NEW_LINE k = k + 1 NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_... |
Sort array after converting elements to their squares | Function to sort an square array ; First convert each array elements into its square ; Sort an array using " inbuild β sort β function " in Arrays class ; Driver code | def sortSquare ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] * arr [ i ] NEW_LINE DEDENT arr . sort ( ) NEW_LINE DEDENT arr = [ - 6 , - 3 , - 1 , 2 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Before β sort " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print (... |
Sort an array when two halves are sorted | Merge two sorted halves of Array into single sorted array ; Starting index of second half ; Temp Array store sorted resultant array ; First Find the point where array is divide into two half ; If Given array is all - ready sorted ; Merge two sorted arrays in single sorted arra... | def mergeTwoHalf ( A , n ) : NEW_LINE INDENT half_i = 0 NEW_LINE temp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( A [ i ] > A [ i + 1 ] ) : NEW_LINE INDENT half_i = i + 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( half_i == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT i = 0 NEW... |
Chocolate Distribution Problem | arr [ 0. . n - 1 ] represents sizes of packets m is number of students . Returns minimum difference between maximum and minimum values of distribution . ; if there are no chocolates or number of students is 0 ; Sort the given packets ; Number of students cannot be more than number of pa... | def findMinDiff ( arr , n , m ) : NEW_LINE INDENT if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr . sort ( ) NEW_LINE if ( n < m ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT min_diff = arr [ n - 1 ] - arr [ 0 ] NEW_LINE for i in range ( len ( arr ) - m + 1 ) : NEW_LINE INDENT min_diff = min ( m... |
Absolute distinct count in a sorted array | This function returns number of distinct absolute values among the elements of the array ; set keeps all unique elements ; Driver Code | def distinctCount ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( abs ( arr [ i ] ) ) NEW_LINE DEDENT return len ( s ) NEW_LINE DEDENT arr = [ - 2 , - 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Count β of β absolute β distinct β values : " , distinctC... |
Absolute distinct count in a sorted array | The function returns return number of distinct absolute values among the elements of the array ; initialize count as number of elements ; Remove duplicate elements from the left of the current window ( i , j ) and also decrease the count ; Remove duplicate elements from the r... | def distinctCount ( arr , n ) : NEW_LINE INDENT count = n ; NEW_LINE i = 0 ; j = n - 1 ; sum = 0 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT while ( i != j and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT count = count - 1 ; NEW_LINE i = i + 1 ; NEW_LINE DEDENT while ( i != j and arr [ j ] == arr [ j - 1 ] ) : NEW_L... |
Pancake sorting | Reverses arr [ 0. . i ] ; Returns index of the maximum element in arr [ 0. . n - 1 ] ; The main function that sorts given array using flip operations ; Start from the complete array and one by one reduce current size by one ; Find index of the maximum element in arr [ 0. . curr_size - 1 ] ; Move the m... | def flip ( arr , i ) : NEW_LINE INDENT start = 0 NEW_LINE while start < i : NEW_LINE INDENT temp = arr [ start ] NEW_LINE arr [ start ] = arr [ i ] NEW_LINE arr [ i ] = temp NEW_LINE start += 1 NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT def findMax ( arr , n ) : NEW_LINE INDENT mi = 0 NEW_LINE for i in range ( 0 , n ) : NE... |
Lexicographically smallest numeric string having odd digit counts | Function to construct lexicographically smallest numeric string having an odd count of each characters ; Stores the resultant string ; If N is even ; Otherwise ; Driver code | def genString ( N ) : NEW_LINE INDENT ans = " " NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT ans = " " . join ( "1" for i in range ( N - 1 ) ) NEW_LINE ans = ans + "2" NEW_LINE DEDENT else : NEW_LINE INDENT ans = " " . join ( "1" for i in range ( N ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ mai... |
Count of values chosen for X such that N is reduced to 0 after given operations | Function to check if the value of X reduces N to 0 or not ; Update the value of N as N - x ; Check if x is a single digit integer ; Function to find the number of values X such that N can be reduced to 0 after performing the given operati... | def check ( x , N ) : NEW_LINE INDENT while True : NEW_LINE INDENT N -= x NEW_LINE if len ( str ( x ) ) == 1 : NEW_LINE INDENT break NEW_LINE DEDENT x = sum ( list ( map ( int , str ( x ) ) ) ) NEW_LINE DEDENT if len ( str ( x ) ) == 1 and N == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def c... |
Maximize subarrays count containing the maximum and minimum Array element after deleting at most one element | Returns the count of subarrays which contains both the maximum and minimum elements in the given vector ; Initialize the low and high of array ; If current element is less than least element ; If current eleme... | def proc ( v ) : NEW_LINE INDENT n = len ( v ) ; NEW_LINE low = v [ n - 1 ] NEW_LINE high = v [ n - 1 ] NEW_LINE p1 = n NEW_LINE p2 = n ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT x = v [ i ] ; NEW_LINE if ( x < low ) : NEW_LINE low = x ; NEW_LINE ans = 0 ; NEW_LINE elif ( x > h... |
Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2 | Function to find the minimum number of increment and decrement of pairs required to make all array elements equal ; Stores the sum of the array ; If sum is not divisible by N ; Update sum ; Store the minimum number of ... | def find ( arr , N ) : NEW_LINE INDENT Sum = sum ( arr ) NEW_LINE if Sum % N : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = Sum // N NEW_LINE ans = 0 NEW_LINE i = 0 NEW_LINE while i < N : NEW_LINE INDENT ans = ans + abs ( k - arr [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT return ans // 2 NEW_LINE ... |
Convert A into B by incrementing or decrementing 1 , 2 , or 5 any number of times | Function to find minimum number of moves required to convert A into B ; Stores the minimum number of moves required ; Stores the absolute difference ; FInd the number of moves ; Return cnt ; Input ; Function call | def minimumSteps ( a , b ) : NEW_LINE INDENT cnt = 0 NEW_LINE a = abs ( a - b ) NEW_LINE cnt = ( a // 5 ) + ( a % 5 ) // 2 + ( a % 5 ) % 2 NEW_LINE return cnt NEW_LINE DEDENT A = 3 NEW_LINE B = 9 NEW_LINE print ( minimumSteps ( A , B ) ) NEW_LINE |
Lexicographically smallest string which is not a subsequence of given string | Function to find lexicographically smallest string that is not a subsequence of S ; Variable to store frequency of a ; Calculate frequency of a ; Initialize string consisting of freq number of a ; Change the last digit to b ; Add another ' a... | def smallestNonSubsequence ( S , N ) : NEW_LINE INDENT freq = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == ' a ' ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT DEDENT ans = " " NEW_LINE for i in range ( freq ) : NEW_LINE INDENT ans += ' a ' NEW_LINE DEDENT if ( freq == N ) : NEW_LINE INDENT ans = an... |
Print all numbers that can be obtained by adding A or B to N exactly M times | Function to find all possible numbers that can be obtained by adding A or B to N exactly M times ; For maintaining increasing order ; Smallest number that can be obtained ; If A and B are equal , then only one number can be obtained , i . e ... | def possibleNumbers ( N , M , A , B ) : NEW_LINE INDENT if ( A > B ) : NEW_LINE INDENT temp = A NEW_LINE A = B NEW_LINE B = temp NEW_LINE DEDENT number = N + M * A NEW_LINE print ( number , end = " β " ) NEW_LINE if ( A != B ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT number = number - A + B NEW_LINE pri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.