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 element is missing ; Driver code
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 INDENT r = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return ( - 1 ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT ar = [ 1 , 2 , 3 , 4 , 5 , 7 , 8 ] NEW_LINE N = len ( ar ) NEW_LINE res = findmissing ( ar , N ) NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
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 + ( high - low ) // 2 NEW_LINE if ( element > a [ middle ] ) : NEW_LINE INDENT low = middle + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = middle NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 20 NEW_LINE arr = [ 10 , 30 , 20 , 50 , 20 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findFirst ( arr , n , x ) ) NEW_LINE DEDENT
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 DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 20 NEW_LINE arr = [ 10 , 30 , 20 , 50 , 20 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findFirst ( arr , n , x ) ) NEW_LINE DEDENT
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 : NEW_LINE INDENT ptr1 = arr [ ptr1 ] NEW_LINE ptr2 = arr [ ptr2 ] NEW_LINE DEDENT return ptr1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 1 ] NEW_LINE print ( findDuplicate ( arr ) ) NEW_LINE DEDENT
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 [ i ] ) - ord ( ' a ' ) + 1 , MAX_CHAR ) : NEW_LINE INDENT ans [ i ] += count [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( len1 ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT str1 = " abcd " ; NEW_LINE printGreaterCount ( str1 ) ; NEW_LINE
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 = " " , end = ' ' ) NEW_LINE DEDENT DEDENT if arr [ i ] in mydict : NEW_LINE INDENT mydict [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mydict [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 7 , - 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE printPairs ( arr , n , sum ) NEW_LINE DEDENT
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 ; Initialize Minimum , second minimum , third minimum and fourth minimum element ; Update Maximum , second maximum , third maximum and fourth maximum element ; Update second maximum , third maximum and fourth maximum element ; Update third maximum and fourth maximum element ; Update fourth maximum element ; Update Minimum , second minimum third minimum and fourth minimum element ; Update second minimum , third minimum and fourth minimum element ; Update third minimum and fourth minimum element ; Update fourth minimum element ; Return the maximum of x , y and z ; Driver program to test above function
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 NEW_LINE minC = sys . maxsize NEW_LINE minD = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > maxA ) : NEW_LINE INDENT maxD = maxC NEW_LINE maxC = maxB NEW_LINE maxB = maxA NEW_LINE maxA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxB ) : NEW_LINE INDENT maxD = maxC NEW_LINE maxC = maxB NEW_LINE maxB = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxC ) : NEW_LINE INDENT maxD = maxC NEW_LINE maxC = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxD ) : NEW_LINE INDENT maxD = arr [ i ] NEW_LINE DEDENT if ( arr [ i ] < minA ) : NEW_LINE INDENT minD = minC NEW_LINE minC = minB NEW_LINE minB = minA NEW_LINE minA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < minB ) : NEW_LINE INDENT minD = minC NEW_LINE minC = minB NEW_LINE minB = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < minC ) : NEW_LINE INDENT minD = minC NEW_LINE minC = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < minD ) : NEW_LINE INDENT minD = arr [ i ] NEW_LINE DEDENT DEDENT x = maxA * maxB * maxC * maxD NEW_LINE y = minA * minB * minC * minD NEW_LINE z = minA * minB * maxA * maxB NEW_LINE return max ( x , max ( y , z ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , - 4 , 3 , - 6 , 7 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE max1 = maxProduct ( arr , n ) NEW_LINE if ( max1 == - 1 ) : NEW_LINE INDENT print ( " No ▁ Quadruple ▁ Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum ▁ product ▁ is " , max1 ) NEW_LINE DEDENT DEDENT
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 [ i ] , arr [ j ] , arr [ k ] } ; Since the array is sorted the farthest points will be a [ i ] and a [ k ] ; ; Driver Code ; set of n points on the X axis
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 ) : NEW_LINE INDENT ways += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ways NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE L = 3 NEW_LINE ans = countTripletsLessThanL ( n , L , arr ) NEW_LINE print ( " Total ▁ Number ▁ of ▁ ways ▁ = " , ans ) NEW_LINE DEDENT
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 ] - k . ; If there are at least two elements between lower bound and current element . ; increment the count by lb - i C 2. ; Driver code
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 + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def countTriplet ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT cur = ( binary_lower ( arr [ i ] - k , arr , n ) ) NEW_LINE if ( cur <= i - 2 ) : NEW_LINE INDENT count += ( ( i - cur ) * ( i - cur - 1 ) ) // 2 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 3 ] NEW_LINE k = 1 NEW_LINE n = len ( arr ) NEW_LINE print ( countTriplet ( arr , n , k ) ) NEW_LINE DEDENT
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 if ( len ( pos ) >= 2 and len ( neg ) >= 2 ) : NEW_LINE INDENT posMax = - sys . maxsize - 1 NEW_LINE posMaxIdx = - 1 NEW_LINE posMin = sys . maxsize NEW_LINE posMinIdx = - 1 NEW_LINE negMax = - sys . maxsize - 1 NEW_LINE negMaxIdx = - 1 NEW_LINE negMin = sys . maxsize NEW_LINE negMinIdx = - 1 NEW_LINE for i in range ( len ( pos ) ) : NEW_LINE INDENT if ( arr [ pos [ i ] ] > posMax ) : NEW_LINE INDENT posMaxIdx = pos [ i ] NEW_LINE posMax = arr [ posMaxIdx ] NEW_LINE DEDENT DEDENT for i in range ( len ( pos ) ) : NEW_LINE INDENT if ( arr [ pos [ i ] ] < posMin and pos [ i ] != posMaxIdx ) : NEW_LINE INDENT posMinIdx = pos [ i ] NEW_LINE posMin = arr [ posMinIdx ] NEW_LINE DEDENT DEDENT for i in range ( len ( neg ) ) : NEW_LINE INDENT if ( abs ( arr [ neg [ i ] ] ) > negMax ) : NEW_LINE INDENT negMaxIdx = neg [ i ] NEW_LINE negMax = abs ( arr [ negMaxIdx ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( neg ) ) : NEW_LINE INDENT if ( abs ( arr [ neg [ i ] ] ) < negMin and neg [ i ] != negMaxIdx ) : NEW_LINE INDENT negMinIdx = neg [ i ] NEW_LINE negMin = abs ( arr [ negMinIdx ] ) NEW_LINE DEDENT DEDENT posVal = ( - 1.0 * posMax / posMin ) NEW_LINE negVal = ( - 1.0 * negMax / negMin ) NEW_LINE if ( posVal < negVal ) : NEW_LINE INDENT res . append ( arr [ posMinIdx ] ) NEW_LINE res . append ( arr [ posMaxIdx ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != posMinIdx and i != posMaxIdx ) : NEW_LINE INDENT res . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT res . append ( arr [ negMinIdx ] ) NEW_LINE res . append ( arr [ negMaxIdx ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != negMinIdx and i != negMaxIdx ) : NEW_LINE INDENT resal . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT elif ( len ( pos ) >= 2 ) : NEW_LINE INDENT posMax = - sys . maxsize NEW_LINE posMaxIdx = - 1 NEW_LINE posMin = sys . maxsize NEW_LINE posMinIdx = - 1 NEW_LINE for i in range ( len ( pos ) ) : NEW_LINE INDENT if ( arr [ pos [ i ] ] > posMax ) : NEW_LINE INDENT posMaxIdx = pos [ i ] NEW_LINE posMax = arr [ posMaxIdx ] NEW_LINE DEDENT DEDENT for i in range ( len ( pos ) ) : NEW_LINE INDENT if ( arr [ pos [ i ] ] < posMin and pos [ i ] != posMaxIdx ) : NEW_LINE INDENT posMinIdx = pos [ i ] NEW_LINE posMin = arr [ posMinIdx ] NEW_LINE DEDENT DEDENT res . append ( arr [ posMinIdx ] ) NEW_LINE res . append ( arr [ posMaxIdx ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != posMinIdx and i != posMaxIdx ) : NEW_LINE INDENT res . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT elif ( len ( neg ) >= 2 ) : NEW_LINE INDENT negMax = - sys . maxsize NEW_LINE negMaxIdx = - 1 NEW_LINE negMin = sys . maxsize NEW_LINE negMinIdx = - 1 NEW_LINE for i in range ( len ( neg ) ) : NEW_LINE INDENT if ( abs ( arr [ neg [ i ] ] ) > negMax ) : NEW_LINE INDENT negMaxIdx = neg [ i ] NEW_LINE negMax = abs ( arr [ negMaxIdx ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( neg ) ) : NEW_LINE INDENT if ( abs ( arr [ neg [ i ] ] ) < negMin and neg [ i ] != negMaxIdx ) : NEW_LINE INDENT negMinIdx = neg [ i ] NEW_LINE negMin = abs ( arr [ negMinIdx ] ) NEW_LINE DEDENT DEDENT res . append ( arr [ negMinIdx ] ) NEW_LINE res . append ( arr [ negMaxIdx ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != negMinIdx and i != negMaxIdx ) : NEW_LINE INDENT res . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ swap ▁ required " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 4 , 1 , 6 , - 3 , - 2 , - 1 ] NEW_LINE n = len ( arr ) NEW_LINE getMinimumSum ( arr , n ) NEW_LINE 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 Suffix Node for the current Node ; Stores Node information for constant time access ; Keeps track the Current Node while insertion ; Function to insert edge in tree ; Finding X , such that s [ currIndex ] + X + s [ currIndex ] is palindrome . ; Check if s [ currIndex ] + X + s [ currIndex ] is already Present in tree . ; Else Create new node ; Setting suffix edge for newly Created Node . ; Longest Palindromic suffix for a string of length 1 is a Null string . ; Else ; Driver code ; Imaginary root 's suffix edge points to itself, since for an imaginary string of length = -1 has an imaginary suffix string. Imaginary root. ; NULL root 's suffix edge points to Imaginary root, since for a string of length = 0 has an imaginary suffix string. ; last will be the index of our last substring
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 ( MAXN ) ] NEW_LINE currNode , ptr = 1 , 2 NEW_LINE tree [ 1 ] = root1 NEW_LINE tree [ 2 ] = root2 NEW_LINE s = " forgeeksskeegfor " NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT insert ( i ) NEW_LINE DEDENT DEDENT def insert ( currIndex ) : NEW_LINE INDENT global currNode , ptr NEW_LINE temp = currNode NEW_LINE while True : NEW_LINE INDENT currLength = tree [ temp ] . length NEW_LINE if ( currIndex - currLength >= 1 and ( s [ currIndex ] == s [ currIndex - currLength - 1 ] ) ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = tree [ temp ] . suffixEdge NEW_LINE DEDENT if tree [ temp ] . insertionEdge [ ord ( s [ currIndex ] ) - ord ( ' a ' ) ] != 0 : NEW_LINE INDENT currNode = tree [ temp ] . insertionEdge [ ord ( s [ currIndex ] ) - ord ( ' a ' ) ] NEW_LINE return NEW_LINE DEDENT ptr += 1 NEW_LINE tree [ temp ] . insertionEdge [ ord ( s [ currIndex ] ) - ord ( ' a ' ) ] = ptr NEW_LINE tree [ ptr ] . end = currIndex NEW_LINE tree [ ptr ] . length = tree [ temp ] . length + 2 NEW_LINE tree [ ptr ] . start = ( tree [ ptr ] . end - tree [ ptr ] . length + 1 ) NEW_LINE currNode = ptr NEW_LINE temp = tree [ temp ] . suffixEdge NEW_LINE if tree [ currNode ] . length == 1 : NEW_LINE INDENT tree [ currNode ] . suffixEdge = 2 NEW_LINE return NEW_LINE DEDENT while True : NEW_LINE INDENT currLength = tree [ temp ] . length NEW_LINE if ( currIndex - currLength >= 1 and s [ currIndex ] == s [ currIndex - currLength - 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = tree [ temp ] . suffixEdge NEW_LINE DEDENT tree [ currNode ] . suffixEdge = tree [ temp ] . insertionEdge [ ord ( s [ currIndex ] ) - ord ( ' a ' ) ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT MAXN = 1000 NEW_LINE root1 = Node ( - 1 , 1 ) NEW_LINE root2 = Node ( 0 , 1 ) NEW_LINE last = ptr NEW_LINE for i in range ( tree [ last ] . start , tree [ last ] . end + 1 ) : NEW_LINE INDENT print ( s [ i ] , end = " " ) NEW_LINE DEDENT DEDENT
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 ) NEW_LINE print ( missingNum ( arr , n ) ) NEW_LINE
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 index == - 1 : NEW_LINE INDENT print ( " Character ▁ not ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' Last ▁ index ▁ is ' , index ) NEW_LINE DEDENT
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 == - 1 ) : NEW_LINE INDENT print ( " Character ▁ not ▁ found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Last ▁ index ▁ is ▁ " , index ) NEW_LINE DEDENT
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_LINE
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 ( unchanged ) node pointer ; Returns largest value smaller than or equal to key . If key is smaller than the smallest , it returns - 1. ; Driver code
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 ) : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif ( key > node . key ) : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def findFloor ( root , key ) : NEW_LINE INDENT curr = root NEW_LINE ans = None NEW_LINE while ( curr ) : NEW_LINE INDENT if ( curr . key <= key ) : NEW_LINE INDENT ans = curr NEW_LINE curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT curr = curr . left NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT return ans . key NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE root = None NEW_LINE root = insert ( root , 19 ) NEW_LINE insert ( root , 2 ) NEW_LINE insert ( root , 1 ) NEW_LINE insert ( root , 3 ) NEW_LINE insert ( root , 12 ) NEW_LINE insert ( root , 9 ) NEW_LINE insert ( root , 21 ) NEW_LINE insert ( root , 19 ) NEW_LINE insert ( root , 25 ) NEW_LINE print ( findFloor ( root , N ) ) NEW_LINE DEDENT
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 ; Drivers code
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 else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT s = 15 NEW_LINE n = findS ( s ) NEW_LINE if ( n == - 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) 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 found at mid ; If str is greater than mid ; If str is smaller than mid ; Driver Code ; Input arr of Strings . ; input Search String
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 , last ) : NEW_LINE INDENT if first > last : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( last + first ) // 2 NEW_LINE if len ( arr [ mid ] ) == 0 : NEW_LINE INDENT left , right = mid - 1 , mid + 1 NEW_LINE while True : NEW_LINE INDENT if left < first and right > last : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if right <= last and len ( arr [ right ] ) != 0 : NEW_LINE INDENT mid = right NEW_LINE break NEW_LINE DEDENT if left >= first and len ( arr [ left ] ) != 0 : NEW_LINE INDENT mid = left NEW_LINE break NEW_LINE DEDENT right += 1 NEW_LINE left -= 1 NEW_LINE DEDENT DEDENT if compareStrings ( string , arr [ mid ] ) == 0 : NEW_LINE INDENT return mid NEW_LINE DEDENT if compareStrings ( string , arr [ mid ] ) < 0 : NEW_LINE INDENT return searchStr ( arr , string , mid + 1 , last ) NEW_LINE DEDENT return searchStr ( arr , string , first , mid - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " for " , " " , " " , " " , " geeks " , " ide " , " " , " practice " , " " , " " , " quiz " , " " , " " ] NEW_LINE string = " quiz " NEW_LINE n = len ( arr ) NEW_LINE print ( searchStr ( arr , string , 0 , n - 1 ) ) NEW_LINE DEDENT
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 remaining occurrences of the elements into ans [ ] ; Prthe array , ans [ ] ; Driver Code ; Given array ; Store the size of the array ; Function Call
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 - 1 ] ) : NEW_LINE INDENT ans . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE maximumMex ( arr , N ) NEW_LINE DEDENT
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 list after each recursive call ; If a < b ; Otherwise , if b >= a ; Recursively call for the list less than the last element and and return the newly formed list ; Driver Code ; Print the array
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 INDENT res = [ a ] + bubble_sort ( [ b ] + bs ) NEW_LINE DEDENT else : NEW_LINE INDENT res = [ b ] + bubble_sort ( [ a ] + bs ) NEW_LINE DEDENT return bubble_sort ( res [ : - 1 ] ) + res [ - 1 : ] NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 5 , 6 , 2 ] NEW_LINE res = bubble_sort ( arr ) NEW_LINE print ( * res ) 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 - ending row index l - starting column index n - ending column index i - iterator ; Stores the current boundary elements ; Push the first row ; Push the last column ; Push the last row ; Push the first column ; Sort the boundary elements ; Update the first row ; Update the last column ; Update the last row ; Update the first column ; Print the resultant matrix ; Driver Code ; Given matrix
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 = 0 NEW_LINE n_m = m NEW_LINE n_n = n NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT boundary = [ ] NEW_LINE for i in range ( l , n ) : NEW_LINE INDENT boundary . append ( a [ k ] [ i ] ) NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m ) : NEW_LINE INDENT boundary . append ( a [ i ] [ n - 1 ] ) NEW_LINE DEDENT n -= 1 NEW_LINE if ( k < m ) : NEW_LINE INDENT for i in range ( n - 1 , l - 1 , - 1 ) : NEW_LINE INDENT boundary . append ( a [ m - 1 ] [ i ] ) NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if ( l < n ) : NEW_LINE INDENT for i in range ( m - 1 , k - 1 , - 1 ) : NEW_LINE INDENT boundary . append ( a [ i ] [ l ] ) NEW_LINE DEDENT l += 1 NEW_LINE DEDENT boundary . sort ( ) NEW_LINE ind = 0 NEW_LINE for i in range ( n_l , n_n ) : NEW_LINE INDENT a [ n_k ] [ i ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_k += 1 NEW_LINE for i in range ( n_k , n_m ) : NEW_LINE INDENT a [ i ] [ n_n - 1 ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_n -= 1 NEW_LINE if ( n_k < n_m ) : NEW_LINE INDENT for i in range ( n_n - 1 , n_l - 1 , - 1 ) : NEW_LINE INDENT a [ n_m - 1 ] [ i ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_m -= 1 NEW_LINE DEDENT if ( n_l < n_n ) : NEW_LINE INDENT for i in range ( n_m - 1 , n_k - 1 , - 1 ) : NEW_LINE INDENT a [ i ] [ n_l ] = boundary [ ind ] NEW_LINE ind += 1 NEW_LINE DEDENT n_l += 1 NEW_LINE DEDENT DEDENT printMatrix ( a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 9 , 7 , 4 , 5 ] , [ 1 , 6 , 2 , - 6 ] , [ 12 , 20 , 2 , 0 ] , [ - 5 , - 6 , 7 , - 2 ] ] NEW_LINE sortBoundaryWise ( matrix ) NEW_LINE DEDENT
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 Code ; Input ; Function call to find minimum sum of absolute differences of pairs in a triplet
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__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE minimum_sum ( A , N ) NEW_LINE DEDENT
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 characters equal ; Traverse the string ; Calculate absolute value of current character and median character ; Print the minimum number of operations required ; Driver Code
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 = len ( S ) NEW_LINE sameChar ( S , N ) NEW_LINE
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 index ( i + j ) ; Update dp [ i ] and return the maximum value ; Function to get maximum score possible from the array A ; Array to store memoization ; Initialize dp with - 1 ; Driver Code
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 ( score , maxScore ( i + j , A , K , N , dp ) ) ; NEW_LINE DEDENT dp [ i ] = score + A [ i ] ; NEW_LINE return dp [ i ] ; NEW_LINE DEDENT def getScore ( A , N , K ) : NEW_LINE INDENT dp = [ 0 ] * N ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] = - 1 ; NEW_LINE DEDENT print ( maxScore ( 0 , A , K , N , dp ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 100 , - 30 , - 50 , - 15 , - 20 , - 30 ] ; NEW_LINE K = 3 ; NEW_LINE N = len ( A ) ; NEW_LINE getScore ( A , N , K ) ; NEW_LINE DEDENT
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 triplets ( a , b , c ) ; if the coefficient of X ^ 2 and x are equal ; if coefficient of X ^ 2 or x are equal to the constant ; condition for having real roots ; Driver code ; Function Call
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 == b ) : NEW_LINE INDENT continue NEW_LINE DEDENT d = arr [ b ] * arr [ b ] // 4 NEW_LINE if ( arr [ a ] * arr ) <= d : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getcount ( arr , N ) ) NEW_LINE
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 reduce all array elements to a X ; If no pair is present with gcd is a X ; Function to check if all array elements area X ; Function to calculate gcd of two numbers ; Driver Code
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 DEDENT DEDENT return False NEW_LINE DEDENT def check ( A , X ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] > X ) : NEW_LINE return False NEW_LINE DEDENT return True NEW_LINE DEDENT def GCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT X = 4 NEW_LINE A = [ 2 , 1 , 5 , 3 , 6 ] NEW_LINE N = 5 NEW_LINE print ( findAns ( A , N , X ) ) NEW_LINE
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 are atleast X elements in arr1 [ ] and atleast Y elements in arr2 [ ] ; Sort arrays in ascending order ; Check if ( X - 1 ) - th element in arr1 [ ] is less than from M - Yth element in arr2 [ ] ; Return false ; Driver Code ; Function Call
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 = [ 3 , 4 , 5 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE X = 2 NEW_LINE Y = 1 NEW_LINE print ( check ( arr1 , arr2 , N , M , X , Y ) ) NEW_LINE
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 elements ; Return the final minimum Bitwise XOR ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
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 ] NEW_LINE N = len ( arr ) NEW_LINE print ( splitArray ( arr , N ) ) NEW_LINE DEDENT
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 element in string format ; Left - shift digits of current element in all possible ways ; Left - shift digits of current element by idx ; If temp greater than or equal to prev and temp less than optEle ; Update arr [ i ] ; Update prev ; If arr is in increasing order ; Otherwise ; Driver Code
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 = arr [ i ] NEW_LINE strEle = str ( arr [ i ] ) NEW_LINE for idx in range ( len ( strEle ) ) : NEW_LINE INDENT temp = int ( strEle [ idx : ] + strEle [ : idx ] ) NEW_LINE if temp >= prev and temp < optEle : NEW_LINE INDENT optEle = temp NEW_LINE DEDENT DEDENT arr [ i ] = optEle NEW_LINE prev = arr [ i ] NEW_LINE DEDENT if isIncreasing ( arr ) : NEW_LINE INDENT return arr NEW_LINE DEDENT else : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 511 , 321 , 323 , 432 , 433 ] NEW_LINE res = sortArr ( arr ) NEW_LINE for i in res : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 if current shop can be assigned to a person who 's already visiting any other shop ; Checks if there is any person whose closing time <= current shop opening time ; Erase previous shop visited by the person satisfying the condition ; Insert new closing time of current shop for the person satisfying a1he condition ; Increment the count by one ; In case if no person have closing time <= current shop opening time but there are some persons left ; Finally pr the ans ; Driver Code ; Given starting and ending time ; Given K and N ; Function call
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_LINE st = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT flag = False NEW_LINE if ( len ( st ) == 0 ) : NEW_LINE INDENT ar = list ( st . keys ( ) ) NEW_LINE it = bisect_left ( ar , a [ i ] [ 0 ] ) NEW_LINE if ( it != 0 ) : NEW_LINE INDENT it -= 1 NEW_LINE if ( ar [ it ] <= a [ i ] [ 0 ] ) : NEW_LINE INDENT del st [ it ] NEW_LINE st [ a [ i ] [ 1 ] ] = 1 NEW_LINE count += 1 NEW_LINE flag = True NEW_LINE DEDENT DEDENT DEDENT if ( len ( st ) < k and flag == False ) : NEW_LINE INDENT st [ a [ i ] [ 1 ] ] = 1 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = [ 1 , 8 , 3 , 2 , 6 ] NEW_LINE E = [ 5 , 10 , 6 , 5 , 9 ] NEW_LINE K , N = 2 , len ( S ) NEW_LINE print ( maximumShops ( S , E , N , K ) ) NEW_LINE DEDENT
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 the vector crr ; Sort the vector crr in descending order ; Stores maximum sum ; Calculate the sum till the last index in crr [ ] which is less than N which contains a positive element ; Print the sum ; Driver code ; Given arrays and respective lengths ; Calculate maximum subarray sum
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_LINE INDENT if ( crr [ i ] > 0 ) : NEW_LINE INDENT sum += crr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 2 , - 1 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE brr = [ 1 , 2 , 3 , 2 ] NEW_LINE K = len ( brr ) NEW_LINE maxSum ( arr , brr , N , K ) NEW_LINE DEDENT
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 of count ; Driver Code ; Function Call
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 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT
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 taken seat ; Iterate the string ; Push the row number at index in vector and heap ; Increment the index to let the next boy in the next minimum width vacant row ; Otherwise ; If girl then take top of element of the max heap ; Pop from queue ; Print the values ; Driver Code ; Given N ; Given arr [ ] ; Given string ; Function Call
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 ] == '0' ) : NEW_LINE INDENT ans . append ( A [ index ] [ 1 ] ) NEW_LINE q . append ( A [ index ] ) NEW_LINE index += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( q [ - 1 ] [ 1 ] ) NEW_LINE del q [ - 1 ] NEW_LINE DEDENT q = sorted ( q ) NEW_LINE DEDENT for i in ans : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE arr = [ 2 , 1 , 3 ] NEW_LINE s = "001011" NEW_LINE findTheOrder ( arr , s , N ) NEW_LINE DEDENT
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 decreasing order odd part ; Calculate sum of k maximum even number ; Calculate sum of k maximum odd number ; Print the absolute difference ; Given array [ ] arr ; Size of array ; Function Call
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 . sort ( ) NEW_LINE even . reverse ( ) NEW_LINE odd . sort ( ) NEW_LINE odd . reverse ( ) NEW_LINE evenSum , oddSum = 0 , 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT evenSum += even [ i ] NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT oddSum += odd [ i ] NEW_LINE DEDENT print ( abs ( evenSum - oddSum ) ) NEW_LINE DEDENT arr = [ 1 , 8 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE evenOddDiff ( arr , N , K ) NEW_LINE
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 order ; Otherwise ; Rearrange the array in ascending order ; Driver Code
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 = ' ▁ ' ) NEW_LINE DEDENT else : NEW_LINE INDENT arr . sort ( ) NEW_LINE print ( * arr , sep = ' ▁ ' ) NEW_LINE DEDENT DEDENT arr = [ 1 , - 1 , - 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE rearrangeArr ( arr , N ) ; NEW_LINE
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 frequencies in subset [ ] array ; Return frequency array ; Function to check is sum N / 2 can be formed using some subset ; dp [ i ] [ j ] store the answer to form sum j using 1 st i elements ; Initialize dp [ ] [ ] with true ; Fill the subset table in the bottom up manner ; If current element is less than j ; Update current state ; Return the result ; Function to check if the given array can be split into required sets ; Store frequencies of arr [ ] ; If size of arr [ ] is odd then print " Yes " ; Check if answer is true or not ; Print the result ; Driver Code ; Given array arr ; Function Call
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 i += 1 NEW_LINE DEDENT return subsets NEW_LINE DEDENT def subsetSum ( subsets , target ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( target + 1 ) ] for y in range ( len ( subsets ) + 1 ) ] NEW_LINE for i in range ( len ( dp ) ) : NEW_LINE INDENT dp [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , len ( subsets ) + 1 ) : NEW_LINE INDENT for j in range ( 1 , target + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE if ( j >= subsets [ i - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] |= ( dp [ i - 1 ] [ j - subsets [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ len ( subsets ) ] [ target ] NEW_LINE DEDENT def divideInto2Subset ( arr ) : NEW_LINE INDENT subsets = findSubsets ( arr ) NEW_LINE if ( len ( arr ) % 2 == 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT isPossible = subsetSum ( subsets , len ( arr ) // 2 ) NEW_LINE if ( isPossible ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 2 , 3 ] NEW_LINE divideInto2Subset ( arr ) NEW_LINE DEDENT
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 the result ; Driver code ; Given two arrays ; Function call
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 NEW_LINE del values [ - 1 ] NEW_LINE DEDENT if ( amt == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ret *= amt NEW_LINE amt -= 1 NEW_LINE ret %= MOD NEW_LINE del salary [ - 1 ] NEW_LINE DEDENT return ret NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT values = [ 1 , 2 ] NEW_LINE salary = [ 2 ] NEW_LINE print ( solve ( values , salary ) ) NEW_LINE DEDENT
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 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 2 , 3 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT
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 A [ i ] to the sum ; Add the highest K numbers ; Subtract from the sum ; Return the sum ; Driver Code
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_LINE Sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( pairs [ i ] [ 1 ] == 0 ) : NEW_LINE INDENT Sum += pairs [ i ] [ 0 ] NEW_LINE DEDENT elif ( pairs [ i ] [ 1 ] == 1 ) : NEW_LINE INDENT if ( K > 0 ) : NEW_LINE INDENT Sum += pairs [ i ] [ 0 ] NEW_LINE K -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT Sum -= pairs [ i ] [ 0 ] NEW_LINE DEDENT DEDENT DEDENT return Sum NEW_LINE DEDENT A = [ 5 , 4 , 6 , 2 , 8 ] NEW_LINE B = [ 1 , 0 , 1 , 1 , 0 ] NEW_LINE K = 2 NEW_LINE N = len ( A ) NEW_LINE print ( maximiseScore ( A , B , K , N ) ) NEW_LINE
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 frequencies ; Stores the minimum cost of all operations ; Store the absolute difference of i - th frequencies of ordered and unordered sequences ; Return the minimum cost ; Driver Code
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 = False NEW_LINE DEDENT else : NEW_LINE INDENT sorted1 . append ( curr ) NEW_LINE original . append ( curr ) NEW_LINE curr = 1 NEW_LINE insert = True NEW_LINE DEDENT DEDENT if ( ( S [ ( len ( S ) - 1 ) ] != S [ ( len ( S ) - 2 ) ] ) or insert == False ) : NEW_LINE INDENT sorted1 . append ( curr ) NEW_LINE original . append ( curr ) NEW_LINE DEDENT sorted1 . sort ( ) NEW_LINE t_cost = 0 NEW_LINE for i in range ( len ( sorted1 ) ) : NEW_LINE INDENT t_cost += abs ( sorted1 [ i ] - original [ i ] ) NEW_LINE DEDENT return ( t_cost // 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aabbcccdeffffggghhhhhii " NEW_LINE print ( sortString ( S ) ) NEW_LINE DEDENT
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 sum with respective elements ; Inserting digit sum with elements in the list pair ; Making the vector pair ; Sort the list , this will sort the pair according to the sum of letters to represent n ; Print the sorted list content ; Driver code
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 ( n ) : NEW_LINE INDENT vp . append ( [ sumOfLetters ( arr [ i ] ) , arr [ i ] ] ) NEW_LINE DEDENT vp . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for i in vp : NEW_LINE INDENT print ( i [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 10 , 31 , 18 ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE DEDENT
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 differences to p ; Sorting p in descending order ; Sum of the first k - 1 values of p ; Computing the result ;
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 return res NEW_LINE DEDENT / * Driver code * / NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 8 , 15 , 16 , 23 , 42 ] NEW_LINE K = 3 NEW_LINE print ( calculate_minimum_split ( arr , K ) ) NEW_LINE DEDENT
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 that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver Code
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 < year2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( year1 > year2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( month1 < month2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( month1 > month2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( day1 < day2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( day1 > day2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT def printDatesAscending ( arr ) : NEW_LINE INDENT arr = sorted ( arr , key = cmp_to_key ( lambda a , b : myCompare ( a , b ) ) ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT DEDENT arr = [ ] NEW_LINE arr . append ( "25-08-1996" ) NEW_LINE arr . append ( "03-08-1970" ) NEW_LINE arr . append ( "09-04-1994" ) NEW_LINE arr . append ( "29-08-1996" ) NEW_LINE arr . append ( "14-02-1972" ) NEW_LINE printDatesAscending ( arr ) NEW_LINE
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 respective strings in the vector pair ; Sort the vector , this will sort the pair according to the number of vowels ; Print the sorted vector content ; Driver code
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 ] ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( ( countVowels ( arr [ i ] ) , arr [ i ] ) ) ; NEW_LINE DEDENT vp . sort ( ) NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT print ( vp [ i ] [ 1 ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " lmno " , " pqrst " , " aeiou " , " xyz " ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sortArr ( arr , n ) ; NEW_LINE DEDENT
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 [ 1 ] NEW_LINE price_second = price [ i ] + price [ i - 1 ] + 2 * price [ 0 ] NEW_LINE totalCost += min ( price_first , price_second ) NEW_LINE DEDENT DEDENT if ( n == 1 ) : NEW_LINE INDENT totalCost += price [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT totalCost += price [ 1 ] NEW_LINE DEDENT return totalCost NEW_LINE DEDENT price = [ 30 , 40 , 60 , 70 ] NEW_LINE n = len ( price ) NEW_LINE print ( minimumCost ( price , n ) ) NEW_LINE
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 ; calling the required function ;
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 ] [ r ] ) : NEW_LINE INDENT return dp [ l ] [ r ] ; NEW_LINE DEDENT vis [ l ] [ r ] = 1 ; NEW_LINE dp [ l ] [ r ] = min ( findSum ( arr , n , k , l , r - 1 ) , findSum ( arr , n , k , l + 1 , r ) ) ; NEW_LINE return dp [ l ] [ r ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 100 , 120 , 140 ] ; NEW_LINE k = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findSum ( arr , n , k , 0 , n - 1 ) ) ; NEW_LINE DEDENT
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 if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 ; k = 5 ; NEW_LINE print ( getNumber ( n , k ) ) ; NEW_LINE DEDENT
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 ; Remove element from the combination ; Function to find all combination of the given elements ; Sort the given elements ; ; Driver code ; Function call
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 != len ( local ) - 1 ) : NEW_LINE INDENT print ( " , ▁ " , end = " " ) NEW_LINE DEDENT DEDENT print ( " } " ) NEW_LINE return NEW_LINE DEDENT for i in range ( l , len ( A ) , 1 ) : NEW_LINE INDENT if ( sum + A [ i ] > K ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i > l and A [ i ] == A [ i - 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT local . append ( A [ i ] ) NEW_LINE unique_combination ( i + 1 , sum + A [ i ] , K , local , A ) NEW_LINE local . remove ( local [ len ( local ) - 1 ] ) NEW_LINE DEDENT DEDENT def Combination ( A , K ) : NEW_LINE INDENT A . sort ( reverse = False ) NEW_LINE DEDENT / * To store combination * / NEW_LINE INDENT local = [ ] NEW_LINE unique_combination ( 0 , 0 , K , local , A ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 10 , 1 , 2 , 7 , 6 , 1 , 5 ] NEW_LINE K = 8 NEW_LINE Combination ( A , K ) NEW_LINE DEDENT
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 under consideration ; Split the string into two contiguous sub - strings ; If left sub - string is found in the map and the right sub - string can be made from the strings from the given array ; If everything failed , we return false ; Function to return the longest string that can made be made up from the other string of the given array ; Put all the strings in the map ; Sort the string in decreasing order of their lengths ; Starting from the longest string ; If current string can be made up from other strings ; Driver code
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 = s [ i : ] NEW_LINE if left in mp and mp [ left ] == 1 and canbuildword ( right , 0 , mp ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT mp [ s ] = 0 NEW_LINE return False NEW_LINE DEDENT def printlongestword ( listofwords ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in listofwords : NEW_LINE INDENT mp [ i ] = 1 NEW_LINE DEDENT listofwords . sort ( key = lambda x : len ( x ) , reverse = True ) NEW_LINE for i in listofwords : NEW_LINE INDENT if canbuildword ( i , 1 , mp ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT listofwords = [ " geeks " , " for " , " geeksfor " , " geeksforgeeks " ] NEW_LINE print ( printlongestword ( listofwords ) ) NEW_LINE DEDENT
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 found ; Driver code
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 [ j ] + arr [ k ] ) ) ) : NEW_LINE INDENT closestSum = ( arr [ i ] + arr [ j ] + arr [ k ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return closestSum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , 1 , - 4 ] NEW_LINE x = 1 NEW_LINE print ( solution ( arr , x ) ) NEW_LINE DEDENT
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 incoming edge ; Since edge u is removed , update the indegrees of all the nodes which had an incoming edge from u ; Function to generate the array from the given sub - sequences ; Create the graph from the input sub - sequences ; Add edge between every two consecutive elements of the given sub - sequences ; Get the indegrees for all the vertices ; Get the topological order of the created graph ; Size of the required array ; Given sub - sequences of the array ; Get the resultant array as vector ; Printing the array
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 DEDENT DEDENT def topo ( V , indeg ) : NEW_LINE INDENT q = deque ( ) NEW_LINE for i in range ( V ) : NEW_LINE INDENT if ( indeg [ i ] == 0 ) : NEW_LINE INDENT q . appendleft ( i ) NEW_LINE DEDENT DEDENT res = [ ] NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT u = q . popleft ( ) NEW_LINE res . append ( u ) NEW_LINE for x in adj [ u ] : NEW_LINE INDENT indeg [ x ] -= 1 NEW_LINE if ( indeg [ x ] == 0 ) : NEW_LINE INDENT q . appendleft ( x ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT def makearray ( v , V ) : NEW_LINE INDENT for i in range ( len ( v ) ) : NEW_LINE INDENT for j in range ( len ( v [ i ] ) - 1 ) : NEW_LINE INDENT addEdge ( v [ i ] [ j ] , v [ i ] [ j + 1 ] ) NEW_LINE DEDENT DEDENT indeg = [ 0 for i in range ( V ) ] NEW_LINE getindeg ( V , indeg ) NEW_LINE res = topo ( V , indeg ) NEW_LINE return res NEW_LINE DEDENT n = 10 NEW_LINE subseqs = [ [ 9 , 1 , 2 , 8 , 3 ] , [ 6 , 1 , 2 ] , [ 9 , 6 , 3 , 4 ] , [ 5 , 2 , 7 ] , [ 0 , 9 , 5 , 4 ] ] NEW_LINE res = makearray ( subseqs , n ) NEW_LINE for x in res : NEW_LINE INDENT print ( x , end = " ▁ " ) 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 been marked ; Praprime numbers ; Function to return the semi - prime sum ; Variable to store the sum of semi - primes ; Iterate over the prime values ; Break the loop once the product exceeds N ; Add valid products which are less than or equal to N each product is a semi - prime number ; Driver code
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 ] = False NEW_LINE DEDENT DEDENT DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT pr . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def SemiPrimeSum ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( pr ) ) : NEW_LINE INDENT for j in range ( i , len ( pr ) ) : NEW_LINE INDENT if ( pr [ i ] * pr [ j ] > N ) : NEW_LINE INDENT break NEW_LINE DEDENT ans += pr [ i ] * pr [ j ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT N = 6 NEW_LINE sieve ( N ) NEW_LINE print ( SemiPrimeSum ( N ) ) NEW_LINE
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 next iteration ; print the consecutive range found ; move i jump directly to j + 1 ; Driver code
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 = " ▁ " ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] , " - " , arr [ j ] , end = " ▁ " ) ; NEW_LINE i = j + 1 ; NEW_LINE DEDENT DEDENT DEDENT n = 7 ; NEW_LINE arr = [ 1 , 3 , 4 , 5 , 6 , 9 , 10 ] ; NEW_LINE compressArr ( arr , n ) ; NEW_LINE
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 print ( brr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 12 , 9 , 10 , 2 , 13 , 14 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE removeElements ( arr , n ) ; NEW_LINE DEDENT
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 __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 12 , 9 , 10 , 2 , 13 , 14 ] NEW_LINE n = len ( arr ) NEW_LINE removeElements ( arr , n ) NEW_LINE DEDENT
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 size of both vectors is not same then we are sure that both vectors can 't be equal ; Check if a and vec have same elements in them ; Driver code ; Function call
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 . append ( x // i ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT vec . sort ( ) NEW_LINE if ( len ( vec ) != int ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT j = 0 NEW_LINE for it in range ( int ) : NEW_LINE INDENT if ( a [ j ] != vec [ it ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return x NEW_LINE DEDENT a = [ 2 , 5 , 4 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( findX ( a , n ) ) NEW_LINE
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 elements by one position from odd to pos ; Reverse the element from 0 to ( n - 1 ) / 2 ; Printing the pendulum arrangement ; Driver code
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 ( in1 != pos ) : NEW_LINE INDENT arr [ in1 ] = arr [ in1 + 1 ] NEW_LINE in1 += 1 NEW_LINE DEDENT arr [ in1 ] = temp NEW_LINE odd = odd - 2 NEW_LINE pos = pos - 1 NEW_LINE DEDENT start = 0 NEW_LINE end = int ( ( n - 1 ) / 2 ) NEW_LINE while ( start < end ) : NEW_LINE INDENT temp = arr [ start ] NEW_LINE arr [ start ] = arr [ end ] NEW_LINE arr [ end ] = temp NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 2 , 4 , 55 , 6 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE pendulumArrangement ( arr , n ) NEW_LINE DEDENT
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 ; curr_left pointer is used for left side execution and curr_right pointer is used for right side execution ; Storing the left side values into LeftList till leaf node not found ; Storing the right side values into RightList till leaf node not found ; Last node of LeftList ; Last node of RightList ; To prevent repetition like 2 , 6 and 6 , 2 ; Delete the last value of LeftList and make the execution to the right side ; Delete the last value of RightList and make the execution to the left side ; ( left value + right value ) = target then print the left value and right value Delete the last value of left and right list and make the left execution to right side and right side execution to left side ; Driver code
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 ( root . data < data ) : NEW_LINE INDENT root . right = AddNode ( root . right , data ) NEW_LINE DEDENT elif ( root . data > data ) : NEW_LINE INDENT root . left = AddNode ( root . left , data ) NEW_LINE DEDENT return root NEW_LINE DEDENT def TargetPair ( node , tar ) : NEW_LINE INDENT LeftList = [ ] NEW_LINE RightList = [ ] NEW_LINE curr_left = node NEW_LINE curr_right = node NEW_LINE while ( curr_left != None or curr_right != None or len ( LeftList ) > 0 and len ( RightList ) > 0 ) : NEW_LINE INDENT while ( curr_left != None ) : NEW_LINE INDENT LeftList . append ( curr_left ) NEW_LINE curr_left = curr_left . left NEW_LINE DEDENT while ( curr_right != None ) : NEW_LINE INDENT RightList . append ( curr_right ) NEW_LINE curr_right = curr_right . right NEW_LINE DEDENT LeftNode = LeftList [ - 1 ] NEW_LINE RightNode = RightList [ - 1 ] NEW_LINE leftVal = LeftNode . data NEW_LINE rightVal = RightNode . data NEW_LINE if ( leftVal >= rightVal ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( leftVal + rightVal < tar ) : NEW_LINE INDENT del LeftList [ - 1 ] NEW_LINE curr_left = LeftNode . right NEW_LINE DEDENT elif ( leftVal + rightVal > tar ) : NEW_LINE INDENT del RightList [ - 1 ] NEW_LINE curr_right = RightNode . left NEW_LINE DEDENT else : NEW_LINE INDENT print ( LeftNode . data , RightNode . data ) NEW_LINE del RightList [ - 1 ] NEW_LINE del LeftList [ - 1 ] NEW_LINE curr_left = LeftNode . right NEW_LINE curr_right = RightNode . left NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = AddNode ( root , 2 ) NEW_LINE root = AddNode ( root , 6 ) NEW_LINE root = AddNode ( root , 5 ) NEW_LINE root = AddNode ( root , 3 ) NEW_LINE root = AddNode ( root , 4 ) NEW_LINE root = AddNode ( root , 1 ) NEW_LINE root = AddNode ( root , 7 ) NEW_LINE sum = 8 NEW_LINE TargetPair ( root , sum ) NEW_LINE DEDENT
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 minimum number of elements from the array to form i ; Calculate the minimum number of elements from the array required to form the numbers from 1 to ( 2 * Max ) ; If there exists a number greater than the Maximum element of the array that can be formed using the numbers of array ; Driver code
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 ] <= i ) : NEW_LINE INDENT res = table [ i - arr [ j ] ] NEW_LINE if ( res != 10 ** 9 and res + 1 < table [ i ] ) : NEW_LINE INDENT table [ i ] = res + 1 NEW_LINE DEDENT DEDENT DEDENT if ( i > arr [ n - 1 ] and table [ i ] == 10 ** 9 ) : NEW_LINE INDENT ans = i NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 6 , 7 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findNumber ( arr , n ) ) NEW_LINE
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 of all subsequences except the minimum and maximum elements ; Sorting array so that it becomes easy to calculate the number of times an element will come in first or last place ; An element will occur ' powa ' times in total of which ' powla ' times it will be last element and ' powfa ' times it will be first element ; In total it will come powe = powa - powla - powfa times ; Multiplying a [ i ] powe times using Fermat Little Theorem under MODulo MOD for fast exponentiation ; Driver Code ; pre - calculation of all combinations
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 = ( x * x ) % MOD NEW_LINE DEDENT return res % MOD NEW_LINE DEDENT def combi ( n , k ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] % MOD + C [ i - 1 ] [ j ] % MOD ) % MOD NEW_LINE DEDENT DEDENT DEDENT DEDENT def product ( a , n , k ) : NEW_LINE INDENT ans = 1 NEW_LINE a . sort ( reverse = False ) NEW_LINE powa = C [ n - 1 ] [ k - 1 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT powla = C [ i ] [ k - 1 ] NEW_LINE powfa = C [ n - i - 1 ] [ k - 1 ] NEW_LINE powe = ( ( powa % MOD ) - ( powla + powfa ) % MOD + MOD ) % MOD NEW_LINE mul = power ( a [ i ] , powe ) % MOD NEW_LINE ans = ( ( ans % MOD ) * ( mul % MOD ) ) % MOD NEW_LINE DEDENT return ans % MOD NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT combi ( 100 , 100 ) NEW_LINE arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE ans = product ( arr , n , k ) NEW_LINE print ( ans ) NEW_LINE DEDENT
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 that performs AND operation of two - bit sequences and returns the resultant string ; Make both strings of same length with the maximum length of s1 & s2 . ; Initialize res as NULL string ; We start from left to right as we have made both strings of same length . ; Convert s1 [ i ] and s2 [ i ] to int and perform bitwise AND operation , append to " res " string ; Driver Code ; Check corner case : If there is just one binary string , then print it and return .
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 for i in range ( num_zeros ) : NEW_LINE INDENT b = '0' + b NEW_LINE DEDENT DEDENT return len_a , a , b NEW_LINE DEDENT def andOperationBitwise ( s1 , s2 ) : NEW_LINE INDENT length , s1 , s2 = makeEqualLength ( s1 , s2 ) NEW_LINE res = " " NEW_LINE for i in range ( length ) : NEW_LINE INDENT res = res + str ( int ( s1 [ i ] ) & int ( s2 [ i ] ) ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ "101" , "110110" , "111" ] NEW_LINE n = len ( arr ) NEW_LINE if ( n < 2 ) : NEW_LINE INDENT print ( arr [ n - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT result = andOperationBitwise ( result , arr [ i ] ) ; NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT
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 [ j ] ; Return the required count ; Driver code
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 ] + y ) : NEW_LINE INDENT count += 1 NEW_LINE j += 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x , y = 1 , 4 NEW_LINE a = [ 1 , 5 ] NEW_LINE n = len ( a ) NEW_LINE b = [ 1 , 1 , 2 ] NEW_LINE m = len ( b ) NEW_LINE print ( countPoints ( n , m , a , b , x , y ) ) NEW_LINE DEDENT
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 , 15 , 18 ] , [ 1 , 8 , 9 , 17 ] , [ 1 , 4 , 7 , 7 ] ] ; NEW_LINE n = N ; NEW_LINE k = len ( arr ) NEW_LINE output = [ 0 for i in range ( n * k ) ] NEW_LINE merge_and_sort ( output , arr , n , k ) ; NEW_LINE for i in range ( n * k ) : NEW_LINE INDENT print ( output [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT
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 median ; To count the minimum operations ; If there are even elements , then there are two medians . We consider the best of two as answer . ; changed here as in case of even elements there will be 2 medians ; Return minimum operations required ; Driver code
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_LINE INDENT arr . append ( matrix [ i ] [ j ] ) NEW_LINE val = matrix [ i ] [ j ] NEW_LINE if ( val < 0 ) : NEW_LINE INDENT res = k - ( abs ( val ) % k ) NEW_LINE if ( res != mod ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT foo = matrix [ i ] [ j ] NEW_LINE if ( foo % k != mod ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT arr . sort ( ) NEW_LINE median = arr [ ( n * m ) // 2 ] NEW_LINE minOperations = 0 NEW_LINE for i in range ( n * m ) : NEW_LINE INDENT minOperations += abs ( arr [ i ] - median ) // k NEW_LINE DEDENT if ( ( n * m ) % 2 == 0 ) : NEW_LINE INDENT median2 = arr [ ( ( n * m ) // 2 ) - 1 ] NEW_LINE minOperations2 = 0 NEW_LINE for i in range ( n * m ) : NEW_LINE INDENT minOperations2 += abs ( arr [ i ] - median2 ) / k NEW_LINE DEDENT minOperations = min ( minOperations , minOperations2 ) NEW_LINE DEDENT return minOperations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 2 , 4 , 6 ] , [ 8 , 10 , 12 ] , [ 14 , 16 , 18 ] , [ 20 , 22 , 24 ] ] NEW_LINE n = len ( matrix ) NEW_LINE m = len ( matrix [ 0 ] ) NEW_LINE k = 2 NEW_LINE print ( minOperations ( n , m , k , matrix ) ) NEW_LINE DEDENT
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 maximum and position of minimum value ; last occurrence of minValue ; last occurrence of maxValue ; Driver code
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 : NEW_LINE INDENT pos_max = i NEW_LINE DEDENT if pos_max != - 1 and pos_min != - 1 : NEW_LINE INDENT ans = min ( ans , abs ( pos_min - pos_max ) + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 1 , 5 , 9 , 7 , 1 , 9 , 4 ] NEW_LINE n = len ( A ) NEW_LINE print ( minSubarray ( A , n ) ) NEW_LINE
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 , 3 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countSequences ( arr , n ) ) NEW_LINE DEDENT
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 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minimumMoves ( arr , n ) ) NEW_LINE DEDENT
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 Code ; Store ranges in vector of pair
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_LINE DEDENT prev = end NEW_LINE DEDENT for i in range ( prev + 1 , m + 1 ) : NEW_LINE INDENT ans . append ( i ) NEW_LINE DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT if ans [ i ] <= m : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , M = 2 , 6 NEW_LINE ranges = [ ] NEW_LINE ranges . append ( [ 1 , 2 ] ) NEW_LINE ranges . append ( [ 4 , 5 ] ) NEW_LINE findMissingNumber ( ranges , M ) NEW_LINE DEDENT
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 ; If there is no mismatch or the difference between the mismatching elements is <= k then return true ; Driver code
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 DEDENT if ( ind == - 1 or abs ( a [ ind ] - b [ ind ] ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT n , k = 2 , 4 NEW_LINE a = [ 1 , 5 ] NEW_LINE b = [ 1 , 1 ] NEW_LINE if ( check ( n , k , a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) 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 [ i ] - pow2 [ N - 1 - i ] ) * x ) % MOD NEW_LINE DEDENT return ans NEW_LINE DEDENT A = [ 5 , 6 , 4 , 3 , 8 ] NEW_LINE print ( SubseqWidths ( A ) ) NEW_LINE
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 ith student happy ; If the sum = x then answer is n ; If the count is equal to n then the answer is n - 1 ; Driver function
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_LINE INDENT if ( cc == n ) : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return cc NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , x = 3 , 70 NEW_LINE a = [ 10 , 20 , 30 ] NEW_LINE print ( maxArrayCover ( a , n , x ) ) NEW_LINE DEDENT
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 head to point to the new node ; Driver Code ; The constructed linked list is : 10.15 . 9.9 .1 .5
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 INDENT if ( temp . data > temp . next . data ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT temp = temp . next . next NEW_LINE DEDENT return flag NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT global start NEW_LINE new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE start = head_ref NEW_LINE DEDENT start = None NEW_LINE push ( start , 5 ) NEW_LINE push ( start , 1 ) NEW_LINE push ( start , 9 ) NEW_LINE push ( start , 9 ) NEW_LINE push ( start , 15 ) NEW_LINE push ( start , 10 ) NEW_LINE if ( isPairWiseSorted ( start ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
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 , 5 , 1 ] NEW_LINE print ( maximumSOP ( A , B ) ) NEW_LINE DEDENT
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 product is equal to m , decrement mid , increment start and increment the count of pairs ; Drivers code
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 INDENT mid -= 1 NEW_LINE DEDENT elif ( prod < m ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT elif ( prod == m ) : NEW_LINE INDENT count += 1 NEW_LINE mid -= 1 NEW_LINE start += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE m = 1 NEW_LINE print ( countTriplets ( arr , n , m ) ) NEW_LINE DEDENT
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 ; Driver code
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 = len ( arr ) ; NEW_LINE print ( distribution ( arr , n ) , " " ) ; NEW_LINE DEDENT
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 ] = arr [ 0 ] , arr [ 1 ] NEW_LINE DEDENT DEDENT DEDENT a = [ 10 , 12 , 5 ] NEW_LINE sort3 ( a ) NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 recursive merge sort . ; Driver Code
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 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ k ] = arr [ k ] + ( arr [ j ] % maxele ) * maxele NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while ( i <= mid ) : NEW_LINE INDENT arr [ k ] = arr [ k ] + ( arr [ i ] % maxele ) * maxele NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( j <= end ) : NEW_LINE INDENT arr [ k ] = arr [ k ] + ( arr [ j ] % maxele ) * maxele NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( beg , end + 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i ] // maxele NEW_LINE DEDENT DEDENT def mergeSortRec ( arr , beg , end , maxele ) : NEW_LINE INDENT if ( beg < end ) : NEW_LINE INDENT mid = ( beg + end ) // 2 NEW_LINE mergeSortRec ( arr , beg , mid , maxele ) NEW_LINE mergeSortRec ( arr , mid + 1 , end , maxele ) NEW_LINE merge ( arr , beg , mid , end , maxele ) NEW_LINE DEDENT DEDENT def mergeSort ( arr , n ) : NEW_LINE INDENT maxele = max ( arr ) + 1 NEW_LINE mergeSortRec ( arr , 0 , n - 1 , maxele ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 999 , 612 , 589 , 856 , 56 , 945 , 243 ] NEW_LINE n = len ( arr ) NEW_LINE mergeSort ( arr , n ) NEW_LINE print ( " Sorted ▁ array " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there are total k - j third elements . ; Driver code
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 ( j + 1 , k + 1 ) : NEW_LINE INDENT print ( str ( arr [ i ] ) + " , ▁ " + str ( arr [ j ] ) + " , ▁ " + str ( arr [ x ] ) ) NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 1 , 3 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 12 NEW_LINE printTriplets ( arr , n , sum ) ; NEW_LINE DEDENT
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 all element to the temporary stack ; push all greater elements ; push operation ; push till the stack is not - empty ; push the i - th character ; push the tempstack back to stack ; print the stack in reverse order ; Driver Code
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_LINE DEDENT elif ( ( b - a ) >= 1 ) : NEW_LINE INDENT while ( ( b - a ) >= 1 ) : NEW_LINE INDENT tempstack . append ( stack . pop ( ) ) NEW_LINE if ( len ( stack ) > 0 ) : NEW_LINE INDENT b = ord ( stack [ - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT stack . append ( s [ i ] ) NEW_LINE while ( len ( tempstack ) > 0 ) : NEW_LINE INDENT stack . append ( tempstack . pop ( ) ) NEW_LINE DEDENT DEDENT DEDENT print ( ' ' . join ( stack ) ) NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE l = len ( s ) NEW_LINE printSorted ( s , l ) NEW_LINE
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 ; Driver Code
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 = len ( A ) NEW_LINE if ( checkFittingArrays ( A , B , N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
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 __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 50 NEW_LINE cost = [ 1 , 12 , 5 , 111 , 200 , 1000 , 10 , 9 , 12 , 15 ] NEW_LINE N = len ( cost ) NEW_LINE print ( maximum_toys ( cost , N , K ) ) NEW_LINE DEDENT
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_LINE INDENT arrival = [ 1 , 2 , 3 ] NEW_LINE departure = [ 2 , 3 , 4 ] NEW_LINE K = 1 NEW_LINE print areBookingsPossible ( arrival , departure , K ) NEW_LINE DEDENT
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 - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j ; Driver method
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_LINE j = N - 1 NEW_LINE while ( j > 0 and V [ j ] < V [ j - 1 ] ) : NEW_LINE INDENT temp = V [ j ] ; NEW_LINE V [ j ] = V [ j - 1 ] ; NEW_LINE V [ j - 1 ] = temp ; NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT A = [ 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 ] NEW_LINE n = len ( A ) NEW_LINE print ( " Array " ) NEW_LINE printVector ( A ) NEW_LINE print ( " After ▁ Sorting ▁ : " ) NEW_LINE insertionSortRecursive ( A , n ) NEW_LINE printVector ( A ) NEW_LINE
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 INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 3 , 2 , 4 , 6 , 5 ] NEW_LINE n = len ( A ) NEW_LINE if almostSort ( A , n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 : NEW_LINE INDENT if ( arr1 [ i ] > arr1 [ i + gap ] ) : NEW_LINE INDENT arr1 [ i ] , arr1 [ i + gap ] = arr1 [ i + gap ] , arr1 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT j = gap - n if gap > n else 0 NEW_LINE while i < n and j < m : NEW_LINE INDENT if ( arr1 [ i ] > arr2 [ j ] ) : NEW_LINE INDENT arr1 [ i ] , arr2 [ j ] = arr2 [ j ] , arr1 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT if ( j < m ) : NEW_LINE INDENT j = 0 NEW_LINE while j + gap < m : NEW_LINE INDENT if ( arr2 [ j ] > arr2 [ j + gap ] ) : NEW_LINE INDENT arr2 [ j ] , arr2 [ j + gap ] = arr2 [ j + gap ] , arr2 [ j ] NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT gap = nextGap ( gap ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a1 = [ 10 , 27 , 38 , 43 , 82 ] NEW_LINE a2 = [ 3 , 9 ] NEW_LINE n = len ( a1 ) NEW_LINE m = len ( a2 ) NEW_LINE merge ( a1 , a2 , n , m ) NEW_LINE print ( " First ▁ Array : ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( a1 [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE print ( " Second ▁ Array : ▁ " , end = " " ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT print ( a2 [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT
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 second array ; Store remaining elements of first array ; Store remaining elements of second array ; Driver code
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_LINE INDENT arr3 [ k ] = arr2 [ j ] NEW_LINE k = k + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT while i < n1 : NEW_LINE INDENT arr3 [ k ] = arr1 [ i ] ; NEW_LINE k = k + 1 NEW_LINE i = i + 1 NEW_LINE DEDENT while j < n2 : NEW_LINE INDENT arr3 [ k ] = arr2 [ j ] ; NEW_LINE k = k + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT print ( " Array ▁ after ▁ merging " ) NEW_LINE for i in range ( n1 + n2 ) : NEW_LINE INDENT print ( str ( arr3 [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr1 = [ 1 , 3 , 5 , 7 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE arr2 = [ 2 , 4 , 6 , 8 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE mergeArrays ( arr1 , arr2 , n1 , n2 ) ; NEW_LINE
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 ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " ) NEW_LINE sortSquare ( arr , n ) NEW_LINE print ( " After ▁ sort " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 array ; Copy the remaining elements of A [ i to half_ ! ] ; Copy the remaining elements of A [ half_ ! to n ] ; Driver code ; Print sorted Array
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_LINE j = half_i NEW_LINE k = 0 NEW_LINE while ( i < half_i and j < n ) : NEW_LINE INDENT if ( A [ i ] < A [ j ] ) : NEW_LINE INDENT temp [ k ] = A [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ k ] = A [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while i < half_i : NEW_LINE INDENT temp [ k ] = A [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( j < n ) : NEW_LINE INDENT temp [ k ] = A [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT A [ i ] = temp [ i ] NEW_LINE DEDENT DEDENT A = [ 2 , 3 , 8 , - 1 , 7 , 10 ] NEW_LINE n = len ( A ) NEW_LINE mergeTwoHalf ( A , n ) NEW_LINE print ( * A , sep = ' ▁ ' ) NEW_LINE
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 packets ; Largest number of chocolates ; Find the subarray of size m such that difference between last ( maximum in case of sorted ) and first ( minimum in case of sorted ) elements of subarray is minimum . ; Driver Code ; m = 7 Number of students
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 ( min_diff , arr [ i + m - 1 ] - arr [ i ] ) NEW_LINE DEDENT return min_diff NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 4 , 7 , 9 , 2 , 23 , 25 , 41 , 30 , 40 , 28 , 42 , 30 , 44 , 48 , 43 , 50 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ difference ▁ is " , findMinDiff ( arr , n , m ) ) NEW_LINE DEDENT
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 : " , distinctCount ( arr , n ) ) NEW_LINE
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 right of the current window ( i , j ) and also decrease the count ; break if only one element is left ; Now look for the zero sum pair in current window ( i , j ) ; decrease the count if ( positive , negative ) pair is encountered ; Driver code
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_LINE INDENT count = count - 1 ; NEW_LINE j = j - 1 ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT break ; NEW_LINE DEDENT sum = arr [ i ] + arr [ j ] ; NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT count = count - 1 ; NEW_LINE i = i + 1 ; NEW_LINE j = j - 1 ; NEW_LINE DEDENT elif ( sum < 0 ) : NEW_LINE INDENT i = i + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT j = j - 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT arr = [ - 2 , - 1 , 0 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( " Count ▁ of ▁ absolute ▁ distinct ▁ values ▁ : ▁ " , distinctCount ( arr , n ) ) ; NEW_LINE
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 maximum element to end of current array if it 's not already at the end ; To move at the end , first move maximum number to beginning ; Now move the maximum number to end by reversing current array ; A utility function to print an array of size n ; Driver program
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 ) : NEW_LINE INDENT if arr [ i ] > arr [ mi ] : NEW_LINE INDENT mi = i NEW_LINE DEDENT DEDENT return mi NEW_LINE DEDENT def pancakeSort ( arr , n ) : NEW_LINE INDENT curr_size = n NEW_LINE while curr_size > 1 : NEW_LINE INDENT mi = findMax ( arr , curr_size ) NEW_LINE if mi != curr_size - 1 : NEW_LINE INDENT flip ( arr , mi ) NEW_LINE flip ( arr , curr_size - 1 ) NEW_LINE DEDENT curr_size -= 1 NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( " % d " % ( arr [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 23 , 10 , 20 , 11 , 12 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE pancakeSort ( arr , n ) ; NEW_LINE print ( " Sorted ▁ Array ▁ " ) NEW_LINE printArray ( arr , n ) NEW_LINE
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__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE print ( genString ( N ) ) NEW_LINE DEDENT
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 operations ; Number of digits in N ; Stores the count of value of X ; Iterate over all possible value of X ; Check if x follow the conditions ; Return the total count ; Driver Code
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 countNoOfsuchX ( N ) : NEW_LINE INDENT k = len ( str ( N ) ) NEW_LINE count = 0 NEW_LINE for x in range ( N - k * ( k + 1 ) * 5 , N + 1 ) : NEW_LINE INDENT if check ( x , N ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 9939 NEW_LINE print ( countNoOfsuchX ( N ) ) NEW_LINE
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 element is more than highest element ; If current element is equal to low or high then update the pointers ; Update number of subarrays ; Return the result ; Function to find the maximum count of subarrays ; Iterate the array to find the maximum and minimum element ; Vector after removing the minimum element ; Using assignment operator to copy one vector to other ; Vector after removing the maximum element ; Given array ; Function Call
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 > high ) : NEW_LINE high = x ; NEW_LINE ans = 0 ; NEW_LINE if ( x == low ) : p1 = i ; NEW_LINE if ( x == high ) : p2 = i ; NEW_LINE ans += n - max ( p1 , p2 ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def subarray ( v ) : NEW_LINE INDENT n = len ( v ) ; NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT ans = proc ( v ) ; NEW_LINE low = v [ 0 ] NEW_LINE pos_low = 0 NEW_LINE high = v [ 0 ] NEW_LINE pos_high = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT x = v [ i ] ; NEW_LINE if ( x < low ) : NEW_LINE low = x ; NEW_LINE pos_low = i ; NEW_LINE elif ( x > high ) : NEW_LINE high = x ; NEW_LINE pos_high = i ; NEW_LINE DEDENT u = v [ : ] ; NEW_LINE del u [ pos_low ] ; NEW_LINE ans = max ( ans , proc ( u ) ) ; NEW_LINE w = v [ : ] ; NEW_LINE del w [ pos_high ] ; NEW_LINE return max ( ans , proc ( w ) ) ; NEW_LINE DEDENT v = [ ] ; NEW_LINE v . append ( 7 ) ; NEW_LINE v . append ( 2 ) ; NEW_LINE v . append ( 5 ) ; NEW_LINE v . append ( 4 ) ; NEW_LINE v . append ( 3 ) ; NEW_LINE v . append ( 1 ) ; NEW_LINE print ( subarray ( v ) ) ; NEW_LINE
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 operations ; Iterate while i is less than N ; Add absolute difference of current element with k to ans ; Increase i bye 1 ; Return the value in ans2 ; Driver Code ; Given Input ; Function Call
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 DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 1 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE print ( find ( arr , N ) ) NEW_LINE DEDENT
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 ' to the string ; Return tha answer string ; Driver code ; Input ; Function call
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 = ans . replace ( ans [ freq - 1 ] , ' b ' ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += ' a ' NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcdefghijklmnopqrstuvwxyz " NEW_LINE N = len ( S ) NEW_LINE print ( smallestNonSubsequence ( S , N ) ) NEW_LINE DEDENT
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 . N + M * A ; For finding others numbers , subtract A from number once and add B to number once ; Driver Code ; Given Input ; Function Call
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 print ( number , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 3 NEW_LINE A = 4 NEW_LINE B = 6 NEW_LINE possibleNumbers ( N , M , A , B ) NEW_LINE DEDENT