text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count pairs from two arrays having sum equal to K | Function to return the count of pairs having sum equal to K ; Initialize pairs to 0 ; Create dictionary of elements of array A1 ; count total pairs ; Every element can be part of at most one pair ; return total pairs ; Driver Code ; function call to print required ans...
def countPairs ( A1 , A2 , n1 , n2 , K ) : NEW_LINE INDENT res = 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT if A1 [ i ] not in m . keys ( ) : NEW_LINE INDENT m [ A1 [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ A1 [ i ] ] = m [ A1 [ i ] ] + 1 NEW_LINE DEDENT DEDENT for i in ra...
Count pairs in an array such that frequency of one is at least value of other | Python3 program to find the number of ordered pairs ; Function to find count of Ordered pairs ; Initialize pairs to 0 ; Store frequencies ; Count total Ordered_pairs ; Driver Code
from collections import defaultdict NEW_LINE def countOrderedPairs ( A , n ) : NEW_LINE INDENT orderedPairs = 0 NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT m [ A [ i ] ] += 1 NEW_LINE DEDENT for X , Y in m . items ( ) : NEW_LINE INDENT for j in range ( 1 , Y + 1 ) : NEW_L...
Longest subarray with elements having equal modulo K | function to find longest sub - array whose elements gives same remainder when divided with K ; Iterate in the array ; check if array element greater then X or not ; Driver code
def LongestSubarray ( arr , n , k ) : NEW_LINE INDENT count = 1 NEW_LINE max_lenght = 1 NEW_LINE prev_mod = arr [ 0 ] % k NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_mod = arr [ i ] % k NEW_LINE if curr_mod == prev_mod : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT max_lenght = max ( m...
Search in a sorted 2D matrix ( Stored in row major order ) | Python 3 program to find whether a given element is present in the given 2 - D matrix ; Basic binary search to find an element in a 1 - D array ; if element found return true ; if middle less than K then skip the left part of the array else skip the right par...
M = 3 NEW_LINE N = 4 NEW_LINE def binarySearch1D ( arr , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = N - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + int ( ( high - low ) / 2 ) NEW_LINE if ( arr [ mid ] == K ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( arr [ mid ] < K ) : NEW_LINE INDENT low...
Program to find Nth term divisible by a or b | Python 3 program to find nth term divisible by a or b ; Function to return gcd of a and b ; Function to calculate how many numbers from 1 to num are divisible by a or b ; calculate number of terms divisible by a and by b then , remove the terms which are divisible by both ...
import sys NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def divTermCount ( a , b , lcm , num ) : NEW_LINE INDENT return num // a + num // b - num // lcm NEW_LINE DEDENT def findNthTerm ( a , b , n ) : NEW_LINE INDENT low = 1 ;...
Replace all occurrences of pi with 3.14 in a given string | Function to replace all occurrences of pi in a given with 3.14 ; Iterate through second last element of the string ; If current and current + 1 alphabets form the word ' pi ' append 3.14 to output ; Append the current letter ; Return the output string ; Driver...
def replacePi ( input ) : NEW_LINE INDENT output = " " ; NEW_LINE size = len ( input ) ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( i + 1 < size and input [ i ] == ' p ' and input [ i + 1 ] == ' i ' ) : NEW_LINE INDENT output += "3.14" ; NEW_LINE i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT output += in...
Number of elements that can be seen from right side | Python3 program to find number of elements that can be seen from right side ; Driver code
def numberOfElements ( height , n ) : NEW_LINE INDENT max_so_far = 0 NEW_LINE coun = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if height [ i ] > max_so_far : NEW_LINE INDENT max_so_far = height [ i ] NEW_LINE coun = coun + 1 NEW_LINE DEDENT DEDENT return coun NEW_LINE DEDENT if __name__ == ' _ _...
Check if a pair with given product exists in Linked list | Link list node ; Push a new node on the front of the list . ; Checks if pair with given product exists in the list or not ; Check if pair exits ; Driver Code ; Start with the empty list ; Use push ( ) to construct linked list ; function to print the result
class Node : NEW_LINE INDENT def __init__ ( self , data , next ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node =...
Largest element in the array that is repeated exactly k times | Function that finds the largest element which is repeated ' k ' times ; sort the array ; if the value of ' k ' is 1 and the largest appears only once in the array ; counter to count the repeated elements ; check if the element at index ' i ' is equal to th...
def solve ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE if ( k == 1 and arr [ n - 2 ] != arr [ n - 1 ] ) : NEW_LINE INDENT print ( arr [ n - 1 ] ) NEW_LINE return NEW_LINE DEDENT count = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT cou...
Largest element in the array that is repeated exactly k times | Python implementation of above approach ; Function that finds the largest element that occurs exactly ' k ' times ; store the frequency of each element ; to store the maximum element ; if current element has frequency ' k ' and current maximum hasn 't been...
import sys NEW_LINE def solve ( arr , n , k ) : NEW_LINE INDENT m = { } ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] in m . keys ( ) ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr [ i ] ] = 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT max = sys . ma...
Sum and Product of minimum and maximum element of an Array | Function to find minimum element ; Function to find maximum element ; Function to get Sum ; Function to get product ; Driver Code ; Sum of min and max element ; Product of min and max element
def getMin ( arr , n ) : NEW_LINE INDENT res = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = min ( res , arr [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def getMax ( arr , n ) : NEW_LINE INDENT res = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = max ( res , arr [ i ] )...
Count the number of pop operations on stack to get each element of the array | Function to find the count ; Hashmap to store all the elements which are popped once . ; Check if the number is present in the hashmap Or in other words been popped out from the stack before . ; Keep popping the elements while top is not equ...
def countEle ( s , a , N ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT num = a [ i ] NEW_LINE if num in mp : NEW_LINE INDENT print ( "0" , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT cnt = 0 NEW_LINE while s [ - 1 ] != num : NEW_LINE INDENT mp [ s . pop ( ) ] = True NEW_LINE ...
Queries to check whether a given digit is present in the given Range | Python3 program to answer Queries to check whether a given digit is present in the given range ; Segment Tree with set at each node ; Funtiom to build the segment tree ; Left child node ; Right child node ; Merging child nodes to get parent node . S...
N = 6 NEW_LINE Tree = [ 0 ] * ( 6 * N ) NEW_LINE for i in range ( 6 * N ) : NEW_LINE INDENT Tree [ i ] = set ( ) NEW_LINE DEDENT def buildTree ( arr : list , idx : int , s : int , e : int ) -> None : NEW_LINE INDENT global Tree NEW_LINE if s == e : NEW_LINE INDENT Tree [ idx ] . add ( arr [ s ] ) NEW_LINE return NEW_LI...
Count characters with same neighbors | Function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; Traverse the string ; Increment the count if the previous and next character is same ; Return count ; Driver code
def countChar ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n <= 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT count = 2 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ =...
First strictly smaller element in a sorted array in Java | Python3 program to find first element that is strictly smaller than given target ; Minimum size of the array should be 1 ; If target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; Move to the left side...
def next ( arr , target ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = len ( arr ) - 1 ; NEW_LINE if ( end == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( target > arr [ end ] ) : NEW_LINE INDENT return end ; NEW_LINE DEDENT ans = - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) ...
First strictly greater element in a sorted array in Java | Python program to find first element that is strictly greater than given target . ; Move to right side if target is greater . ; Move left side . ; Driver code
def next ( arr , target ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = len ( arr ) - 1 ; NEW_LINE ans = - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE if ( arr [ mid ] <= target ) : NEW_LINE INDENT start = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = mid ; NEW_LI...
Reallocation of elements based on Locality of Reference | A function to perform sequential search . ; Linearly search the element ; If not found ; Shift elements before one position ; Driver Code
def search ( arr , n , x ) : NEW_LINE INDENT res = - 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( x == arr [ i ] ) : NEW_LINE INDENT res = i NEW_LINE DEDENT DEDENT if ( res == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT temp = arr [ res ] NEW_LINE i = res NEW_LINE while ( i > 0 ) : NEW_LINE I...
Probability of a key K present in array | Function to find the probability ; find probability upto 2 decimal places ; Driver Code
def kPresentProbability ( a , n , k ) : NEW_LINE INDENT count = a . count ( k ) NEW_LINE return round ( count / n , 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 4 , 7 , 2 , 0 , 8 , 7 , 5 ] NEW_LINE K = 2 NEW_LINE N = len ( A ) NEW_LINE print ( kPresentProbability ( A , N , K ) ) NEW_LINE ...
Largest subarray having sum greater than k | Comparison function used to sort preSum vector . ; Function to find index in preSum vector upto which all prefix sum values are less than or equal to val . ; Starting and ending index of search space . ; To store required index value . ; If middle value is less than or equal...
def compare ( a , b ) : NEW_LINE INDENT if a [ 0 ] == b [ 0 ] : NEW_LINE INDENT return a [ 1 ] < b [ 1 ] NEW_LINE DEDENT return a [ 0 ] < b [ 0 ] NEW_LINE DEDENT def findInd ( preSum , n , val ) : NEW_LINE INDENT l , h = 0 , n - 1 NEW_LINE ans = - 1 NEW_LINE while l <= h : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE ...
Find the slope of the given number | function to find slope of a number ; to store slope of the given number 'num ; loop from the 2 nd digit up to the 2 nd last digit of the given number 'num ; if the digit is a maxima ; if the digit is a minima ; required slope ; Driver Code
def slopeOfNum ( num , n ) : NEW_LINE ' NEW_LINE INDENT slope = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( num [ i ] > num [ i - 1 ] and num [ i ] > num [ i + 1 ] ) : NEW_LINE INDENT slope += 1 NEW_LINE DEDENT elif ( num [ i ] < num [ i - 1 ] and num [ i ] < num [ i + 1 ] ) ...
Sudo Placement | Beautiful Pairs | Python3 code for finding required pairs ; The function to check if beautiful pair exists ; Set for hashing ; Traversing the first array ; Traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; If such x exists then we return true ; Hash ...
from typing import List NEW_LINE def pairExists ( arr1 : List [ int ] , m : int , arr2 : List [ int ] , n : int ) -> bool : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( arr2 [ 2 ] - arr1 [ 2 ] ) not in s : NEW_LINE INDENT return True NEW_LINE DE...
Sudo Placement | Placement Tour | Python Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array whic...
value = 0 NEW_LINE def canBeOptimalValue ( K : int , arr : list , N : int , B : int ) -> bool : NEW_LINE INDENT global value NEW_LINE tmp = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) NEW_LINE DEDENT tmp . sort ( ) NEW_LINE value = 0 NEW_LINE for i in range ( K ) ...
Previous greater element | Python 3 program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ ...
def prevGreater ( arr , n ) : NEW_LINE INDENT print ( " - 1" , end = " , ▁ " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] < arr [ j ] : NEW_LINE INDENT print ( arr [ j ] , end = " , ▁ " ) NEW_LINE flag = 1 NEW_LINE break NEW_...
Previous greater element | Python3 program to print previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements fro...
import math as mt NEW_LINE def prevGreater ( arr , n ) : NEW_LINE INDENT s = list ( ) ; NEW_LINE s . append ( arr [ 0 ] ) NEW_LINE print ( " - 1 , ▁ " , end = " " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while ( len ( s ) > 0 and s [ - 1 ] < arr [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if len ...
Duplicates in an array in O ( n ) time and by using O ( 1 ) extra space | Set | Function to find repeating elements ; Flag variable used to represent whether repeating element is found or not . ; Check if current element is repeating or not . If it is repeating then value will be greater than or equal to n . ; Check if...
def printDuplicates ( arr , n ) : NEW_LINE INDENT fl = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ arr [ i ] % n ] >= n ) : NEW_LINE INDENT if ( arr [ arr [ i ] % n ] < 2 * n ) : NEW_LINE INDENT print ( arr [ i ] % n , end = " ▁ " ) NEW_LINE fl = 1 ; NEW_LINE DEDENT DEDENT arr [ arr [ i ] % n ] +...
Find the smallest positive number missing from an unsorted array | Set 2 | Function to find smallest positive missing number . ; to store next array element in current traversal ; if value is negative or greater than array size , then it cannot be marked in array . So move to next element . ; traverse the array until w...
def findMissingNo ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] <= 0 or arr [ i ] > n ) : NEW_LINE INDENT continue NEW_LINE DEDENT val = arr [ i ] NEW_LINE while ( arr [ val - 1 ] != val ) : NEW_LINE INDENT nextval = arr [ val - 1 ] NEW_LINE arr [ val - 1 ] = val NEW_LINE val = nex...
Print all triplets with given sum | Prints all triplets in arr [ ] with given sum ; Driver code
def findTriplets ( arr , n , sum ) : NEW_LINE INDENT for i in range ( 0 , n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] + arr [ k ] == sum ) : NEW_LINE INDENT print ( arr [ i ] , " ▁ " , arr [ j ] , " ▁ " , arr [ k ...
Print all triplets with given sum | Python3 program to find triplets in a given array whose Sum is equal to given sum . ; function to print triplets with given sum ; Find all pairs with Sum equals to " Sum - arr [ i ] " ; Driver code
import math as mt NEW_LINE def findTriplets ( arr , n , Sum ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT s = dict ( ) NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT x = Sum - ( arr [ i ] + arr [ j ] ) NEW_LINE if x in s . keys ( ) : NEW_LINE INDENT print ( x , arr [ i ] , arr [ j ] ) NEW_LINE...
Maximum product quadruple ( sub | Python3 program to find a maximum product of a quadruple in array of integers ; 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 ; will contain max product ; Driver Code
import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT max_product = - sys . maxsize ; NEW_LINE for i in range ( n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in ...
Maximum product quadruple ( sub | 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 ; Sort the array in ascending order ; Return the maximum of x , y and z ; Driver Code
def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT arr . sort ( ) NEW_LINE x = ( arr [ n - 1 ] * arr [ n - 2 ] * arr [ n - 3 ] * arr [ n - 4 ] ) NEW_LINE y = arr [ 0 ] * arr [ 1 ] * arr [ 2 ] * arr [ 3 ] NEW_LINE z = ( arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] * arr [ n -...
Minimum value of " max ▁ + ▁ min " in a subarray | Python 3 program to find sum of maximum and minimum in any subarray of an array of positive numbers . ; Driver code
def maxSum ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = arr [ 0 ] + arr [ 1 ] NEW_LINE for i in range ( 1 , n - 1 , 1 ) : NEW_LINE INDENT ans = min ( ans , ( arr [ i ] + arr [ i + 1 ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LI...
Stella Octangula Number | Returns value of n * ( 2 * n * n - 1 ) ; Finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; Returns true if x isStella octangula number . Else returns false . ; Find ' high ' for binary search by repeated doubling ; If condition is satisfied for a power of 2. ;...
def f ( n ) : NEW_LINE INDENT return n * ( 2 * n * n - 1 ) ; NEW_LINE DEDENT def binarySearch ( low , high , x ) : NEW_LINE INDENT while ( low <= high ) : NEW_LINE INDENT mid = int ( ( low + high ) // 2 ) ; NEW_LINE if ( f ( mid ) < x ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT elif ( f ( mid ) > x ) : NEW_LINE...
Sort the given string using character search | Python 3 implementation to sort the given string without using any sorting technique ; A character array to store the no . of occurrences of each character between ' a ' to 'z ; to store the final sorted string ; To store each occurrence of character by relative indexing ;...
def sortString ( st , n ) : NEW_LINE ' NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE new_str = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ ord ( st [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT while ( arr [ i ] > 0 ) : NEW_LINE INDENT new_str += chr ( i + ord ( ' a ' ...
Maximum occurring character in a linked list | Link list node ; Storing element 's frequencies in a hash table. ; Calculating the first maximum element ; Push a node to linked list . Note that this function changes the head ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = ' ' NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def maxChar ( head ) : NEW_LINE INDENT p = head NEW_LINE hash = [ 0 for i in range ( 256 ) ] NEW_LINE while ( p != None ) : NEW_LINE hash [ ord ( p . data ) ] += 1 NEW_LINE p = p . n...
Maximum sum of elements from each row in the matrix | Python Program to find row - wise maximum element sum considering elements in increasing order . ; Function to perform given task ; Getting the maximum element from last row ; Comparing it with the elements of above rows ; Maximum of current row . ; If we could not ...
N = 3 NEW_LINE def getGreatestSum ( a ) : NEW_LINE INDENT prev_max = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( prev_max < a [ N - 1 ] [ j ] ) : NEW_LINE INDENT prev_max = a [ N - 1 ] [ j ] NEW_LINE DEDENT DEDENT sum = prev_max NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT curr_max = - 214...
Find the number of times every day occurs in a month | Python program to count occurrence of days in a month ; function to find occurrences ; stores days in a week ; Initialize all counts as 4. ; find index of the first day ; number of days whose occurrence will be 5 ; mark the occurrence to be 5 of n - 28 days ; print...
import math NEW_LINE def occurrenceDays ( n , firstday ) : NEW_LINE INDENT days = [ " Monday " , " Tuesday " , " Wednesday " , " Thursday " , " Friday " , " Saturday " , " Sunday " ] NEW_LINE count = [ 4 for i in range ( 0 , 7 ) ] NEW_LINE pos = - 1 NEW_LINE for i in range ( 0 , 7 ) : NEW_LINE INDENT if ( firstday == d...
Value of k | Python3 code to find k - th element after append and insert middle operations ; ans = n Middle element of the sequence ; length of the resulting sequence . ; Updating the middle element of next sequence ; Moving to the left side of the middle element . ; Moving to the right side of the middle element . ; D...
import math NEW_LINE def findElement ( n , k ) : NEW_LINE INDENT left = 1 NEW_LINE right = math . pow ( 2 , n ) - 1 NEW_LINE while 1 : NEW_LINE INDENT mid = int ( ( left + right ) / 2 ) NEW_LINE if k == mid : NEW_LINE INDENT print ( ans ) NEW_LINE break NEW_LINE DEDENT ans -= 1 NEW_LINE if k < mid : NEW_LINE INDENT rig...
First common element in two linked lists | Python3 program to find first common element in two unsorted linked list ; Link list node ; A utility function to insert a node at the beginning of a linked list ; Returns the first repeating element in linked list ; Traverse through every node of first list ; If current node ...
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref N...
Print pair with maximum AND value in an array | Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Find the eleme...
def checkBit ( pattern , arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( pattern & arr [ i ] ) == pattern ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def maxAND ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for bit in range ( 31 , ...
Probability of choosing a random pair with maximum sum in an array | Function to get max first and second ; If current element is smaller than first , then update both first and second ; If arr [ i ] is in between first and second then update second ; cnt1 += 1 frequency of first maximum ; cnt2 += 1 frequency of second...
def countMaxSumPairs ( a , n ) : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = a [ i ] NEW_LINE DEDENT elif ( a [ i ] > second and a [ i ] != first ) : NEW_LINE INDENT second = a [ i ] NEW_LINE DEDEN...
Find if given number is sum of first n natural numbers | Function to find no . of elements to be added from 1 to get n ; Start adding numbers from 1 ; If sum becomes equal to s return n ; Driver code
def findS ( s ) : NEW_LINE INDENT _sum = 0 NEW_LINE n = 1 NEW_LINE while ( _sum < s ) : NEW_LINE INDENT _sum += n NEW_LINE n += 1 NEW_LINE DEDENT n -= 1 NEW_LINE if _sum == s : NEW_LINE INDENT return n NEW_LINE DEDENT return - 1 NEW_LINE DEDENT s = 15 NEW_LINE n = findS ( s ) NEW_LINE if n == - 1 : NEW_LINE INDENT prin...
Find if given number is sum of first n natural numbers | Python3 program of the above approach ; Function to check if the s is the sum of first N natural number ; Solution of Quadratic Equation ; Condition to check if the solution is a integer ; Driver Code ; Function Call
import math NEW_LINE def isvalid ( s ) : NEW_LINE INDENT k = ( - 1 + math . sqrt ( 1 + 8 * s ) ) / 2 NEW_LINE if ( math . ceil ( k ) == math . floor ( k ) ) : NEW_LINE INDENT return int ( k ) NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT s = 15 NEW_LINE print ( isvalid ( s ) ) NEW_LINE
Save from Bishop in chessboard | python program to find total safe position to place your Bishop ; function to calc total safe position ; i , j denotes row and column of position of bishop ; calc distance in four direction ; calc total sum of distance + 1 for unsafe positions ; return total safe positions ; driver func...
import math NEW_LINE def calcSafe ( pos ) : NEW_LINE INDENT j = pos % 10 NEW_LINE i = pos / 10 NEW_LINE dis_11 = min ( abs ( 1 - i ) , abs ( 1 - j ) ) NEW_LINE dis_18 = min ( abs ( 1 - i ) , abs ( 8 - j ) ) NEW_LINE dis_81 = min ( abs ( 8 - i ) , abs ( 1 - j ) ) NEW_LINE dis_88 = min ( abs ( 8 - i ) , abs ( 8 - j ) ) N...
Count number of elements between two given elements in array | Function to count number of elements occurs between the elements . ; Find num1 ; If num1 is not present or present at end ; Find num2 ; If num2 is not present ; return number of elements between the two elements . ; Driver Code
def getCount ( arr , n , num1 , num2 ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == num1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for j in range ( n - 1 , i + 1 , - 1 ) : NEW_LINE INDENT if ( arr [ j ] == num2 ) : NEW...
Best meeting point in 2D binary array | Python program to find best meeting point in 2D array ; Find all members home 's position ; Sort positions so we can find most beneficial point ; middle position will always beneficial for all group members but it will be sorted which we have already done ; Now find total distanc...
ROW = 3 NEW_LINE COL = 5 NEW_LINE def minTotalDistance ( grid : list ) -> int : NEW_LINE INDENT if ROW == 0 or COL == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT vertical = [ ] NEW_LINE horizontal = [ ] NEW_LINE for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 ...
Count numbers with difference between number and its digit sum greater than specific value | Utility method to get sum of digits of K ; loop until K is not zero ; method returns count of numbers smaller than N , satisfying difference condition ; binary search while loop ; if difference between number and its sum of dig...
def sumOfDigit ( K ) : NEW_LINE INDENT sod = 0 NEW_LINE while ( K ) : NEW_LINE INDENT sod = sod + K % 10 NEW_LINE K = K // 10 NEW_LINE DEDENT return sod NEW_LINE DEDENT def totalNumbersWithSpecificDifference ( N , diff ) : NEW_LINE INDENT low = 1 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ...
Randomized Binary Search Algorithm | To generate random number between x and y ie . . [ x , y ] ; A iterative randomized binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; Check if x...
from random import randint NEW_LINE def getRandom ( x , y ) : NEW_LINE INDENT return randint ( x , y ) NEW_LINE DEDENT def randomizedBinarySearch ( arr , l , r , x ) : NEW_LINE INDENT while ( l <= r ) : NEW_LINE INDENT m = getRandom ( l , r ) NEW_LINE if ( arr [ m ] == x ) : NEW_LINE INDENT return m NEW_LINE DEDENT if ...
Number of buildings facing the sun | Returns count buildings that can see sunlight ; Initialuze result ( Note that first building always sees sunlight ) ; Start traversing element ; If curr_element is maximum or current element is equal , update maximum and increment count ; Driver code
def countBuildings ( arr , n ) : NEW_LINE INDENT count = 1 NEW_LINE curr_max = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > curr_max or arr [ i ] == curr_max ) : NEW_LINE INDENT count += 1 NEW_LINE curr_max = arr [ i ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 7 , 4 ,...
Find index of an extra element present in one sorted array | Returns index of extra . element in arr1 [ ] n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; Driver code ; Solve is passed both arrays
def findExtra ( arr1 , arr2 , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT arr1 = [ 2 , 4 , 6 , 8 , 10 , 12 , 13 ] NEW_LINE arr2 = [ 2 , 4 , 6 , 8 , 10 , 12 ] NEW_LINE n = len ( arr2 ) NEW_LINE...
Find index of an extra element present in one sorted array | Returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; left and right are end points denoting the current range . ; If middle element is same of both arrays , it means that extra element is after mid so we update lef...
def findExtra ( arr1 , arr2 , n ) : NEW_LINE INDENT left = 0 NEW_LINE right = n - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( int ) ( ( left + right ) / 2 ) NEW_LINE if ( arr2 [ mid ] == arr1 [ mid ] ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT index = mid NEW_LINE right = ...
Make all array elements equal with minimum cost | Utility method to compute cost , when all values of array are made equal to X ; Method to find minimum cost to make all elements equal ; Setting limits for ternary search by smallest and largest element ; loop until difference between low and high become less than 3 , b...
def computeCost ( arr , N , X ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cost += abs ( arr [ i ] - X ) NEW_LINE DEDENT return cost NEW_LINE DEDENT def minCostToMakeElementEqual ( arr , N ) : NEW_LINE INDENT low = high = arr [ 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( low...
Minimum number of jumps required to sort numbers placed on a number line | Function to find the minimum number of jumps required to sort the array ; Base Case ; Store the required result ; Stores the current position of elements and their respective maximum jump ; Used to check if a position is already taken by another...
def minJumps ( w , l , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE pos = { } NEW_LINE jump = { } NEW_LINE filled = { } NEW_LINE a = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pos [ w [ i ] ] = i NEW_LINE filled [ i ] ...
Make an array strictly increasing by repeatedly subtracting and adding arr [ i | Function to check if an array can be made strictly increasing ; Traverse the given array arr [ ] ; Update the value of p , arr [ i ] , and arr [ i - 1 ] ; Traverse the given array ; Check if the array arr [ ] is strictly increasing or not ...
def check ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i - 1 ] >= ( i - 1 ) ) : NEW_LINE INDENT p = arr [ i - 1 ] - ( i - 1 ) NEW_LINE arr [ i ] += p NEW_LINE arr [ i - 1 ] -= p NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] <= arr [ i - 1 ] ) : N...
Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | Function to reverse the bits of a number ; Stores the reversed number ; Divide rev by 2 ; If the value of N is odd ; Update the value of N ; Return the final value of rev ; Function for rearranging the array elemen...
def keyFunc ( n ) : NEW_LINE INDENT rev = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT rev = rev << 1 NEW_LINE if ( n & 1 == 1 ) : NEW_LINE INDENT rev = rev ^ 1 NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT return rev NEW_LINE DEDENT def getNew ( arr ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in arr : NEW_LINE INDENT an...
Minimize maximum array element by splitting array elements into powers of two at most K times | Function to find the minimum value of the maximum element of the array by splitting at most K array element into perfect powers of 2 ; Sort the array element in the ascending order ; Reverse the array ; If count of 0 is equa...
def minimumSize ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arr . reverse ( ) NEW_LINE zero = arr . count ( 0 ) NEW_LINE if zero == N : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT elif K >= N : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ K ] ) NEW_LINE DEDENT DEDENT ar...
Check if removal of a subsequence of non | Function to check if it is possible to sort the array or not ; Stores the index if there are two consecutive 1 's in the array ; Traverse the given array ; Check adjacent same elements having values 1 s ; If there are no two consecutive 1 s , then always remove all the 1 s fro...
def isPossibleToSort ( arr , N ) : NEW_LINE INDENT idx = - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] == 1 and arr [ i - 1 ] == 1 ) : NEW_LINE INDENT idx = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( idx == - 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return NEW_LINE DEDENT for i in ran...
Maximize ropes of consecutive length possible by connecting given ropes | Function to find maximized count of ropes of consecutive length ; Stores the maximum count of ropes of consecutive length ; Sort the ropes by their length ; Traverse the array ; If size of the current rope is less than or equal to current maximum...
def maxConsecutiveRopes ( ropes , N ) : NEW_LINE INDENT curSize = 0 NEW_LINE ropes = sorted ( ropes ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ropes [ i ] <= curSize + 1 ) : NEW_LINE INDENT curSize = curSize + ropes [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return curSize NEW...
Maximum ranges that can be uniquely represented by any integer from the range | Function to find the maximum number of ranges where each range can be uniquely represented by an integer ; Sort the ranges in ascending order ; Stores the count of ranges ; Stores previously assigned range ; Traverse the vector arr [ ] ; Sk...
def maxRanges ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 1 NEW_LINE prev = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT last = arr [ i - 1 ] NEW_LINE current = arr [ i ] NEW_LINE if ( last [ 0 ] == current [ 0 ] and last [ 1 ] == current [ 1 ] and current [ 1 ] == current [ 0 ] ) : N...
Sort a string lexicographically by reversing a substring | Function to find the substring in S required to be reversed ; Stores the size of the string ; Stores the starting point of the substring ; Iterate over the string S while i < N ; Increment the value of i ; Stores the ending index of the substring ; If start <= ...
def adjust ( S , i , start , end ) : NEW_LINE INDENT N = len ( S ) NEW_LINE start = i - 1 NEW_LINE while ( i < N and S [ i ] < S [ i - 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT end = i - 1 NEW_LINE if ( start <= 0 and i >= N ) : NEW_LINE INDENT return True , start , i , end NEW_LINE DEDENT if ( start >= 1 and i <=...
Split array into K non | Function find maximum sum of minimum and maximum of K subsets ; Stores the result ; Sort the array arr [ ] in decreasing order ; Traverse the range [ 0 , K ] ; Sort the array S [ ] in ascending order ; Traverse the array S [ ] ; If S { i ] is 1 ; Stores the index of the minimum element of the i...
def maximumSum ( arr , S , N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE arr = sorted ( arr ) [ : : - 1 ] NEW_LINE for i in range ( K ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT S = sorted ( S ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT if ( S [ i ] == 1 ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT ...
Modify an array by sorting after reversal of bits of each array element | Function to convert binary number to equivalent decimal ; Set base value to 1 , i . e 2 ^ 0 ; Function to convert a decimal to equivalent binary representation ; Stores the binary representation ; Since ASCII value of '0' , '1' are 48 and 49 ; As...
def binaryToDecimal ( n ) : NEW_LINE INDENT num = n NEW_LINE dec_value = 0 NEW_LINE base = 1 NEW_LINE length = len ( num ) NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( num [ i ] == '1' ) : NEW_LINE INDENT dec_value += base NEW_LINE DEDENT base = base * 2 NEW_LINE DEDENT return dec_value NEW...
Check if sequence of removed middle elements from an array is sorted or not | Function to check if sequence of removed middle elements from an array is sorted or not ; Points toa the ends of the array ; Iterate l + 1 < r ; If the element at index L and R is greater than ( L + 1 ) - th and ( R - 1 ) - th elements ; If t...
def isSortedArray ( arr , n ) : NEW_LINE INDENT l = 0 NEW_LINE r = ( n - 1 ) NEW_LINE while ( ( l + 1 ) < r ) : NEW_LINE INDENT if ( arr [ l ] >= max ( arr [ l + 1 ] , arr [ r - 1 ] ) and arr [ r ] >= max ( arr [ r - 1 ] , arr [ l + 1 ] ) ) : NEW_LINE INDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT...
Length of longest strictly increasing subset with each pair of adjacent elements satisfying the condition 2 * A [ i ] Γ’ ‰Β₯ A [ i + 1 ] | Function to find the length of the longest subset satisfying given conditions ; Sort the array in ascending order ; Stores the starting index and maximum length of the required subset...
def maxLenSubset ( a , n ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE index = 0 NEW_LINE maxlen = - 1 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i NEW_LINE len1 = 1 NEW_LINE while ( j < n - 1 ) : NEW_LINE INDENT if ( 2 * a [ j ] >= a [ j + 1 ] ) : NEW_LINE INDENT len1 += 1 NEW_LINE DEDEN...
Maximize count of intersecting line segments | Python3 program for the above approach ; Function to find the maximum number of intersecting line segments possible ; Stores pairs of line segments { X [ i ] , Y [ i ] ) ; Push { X [ i ] , Y [ i ] } into p ; Sort p in ascending order of points on X number line ; Stores the...
from bisect import bisect_left NEW_LINE def solve ( N , X , Y ) : NEW_LINE INDENT p = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT p . append ( [ X [ i ] , Y [ i ] ] ) NEW_LINE DEDENT p = sorted ( p ) NEW_LINE s = { } NEW_LINE s [ p [ 0 ] [ 1 ] ] = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr = list ( s...
Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K | Function to check if an array can be reduced to single element by removing maximum element among any chosen pairs ; Sort the array in descending order ; Traverse the array ; If the absolute differe...
def canReduceArray ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i + 1 ] > K ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT...
Lexicographically smallest string possible by merging two sorted strings | Function to find lexicographically smallest possible by merging two sorted strings ; Stores length of s1 ; Stores length of s2 ; Pointer to beginning of string1 i . e . , s1 ; Pointer to beginning of string2 i . e . , s2 ; Stores the final strin...
def mergeStrings ( s1 , s2 ) : NEW_LINE INDENT len1 = len ( s1 ) NEW_LINE len2 = len ( s2 ) NEW_LINE pntr1 = 0 NEW_LINE pntr2 = 0 NEW_LINE ans = " " NEW_LINE while ( pntr1 < len1 and pntr2 < len2 ) : NEW_LINE INDENT if ( s1 [ pntr1 ] < s2 [ pntr2 ] ) : NEW_LINE INDENT ans += s1 [ pntr1 ] NEW_LINE pntr1 += 1 NEW_LINE DE...
Sort a string without altering the position of vowels | Function to sort the string leaving the vowels unchanged ; Length of string S ; Traverse the string S ; Sort the string temp ; Pointer to traverse the sorted string of consonants ; Traverse the string S ; Driver Code
def sortStr ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE temp = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] != ' a ' and S [ i ] != ' e ' and S [ i ] != ' i ' and S [ i ] != ' o ' and S [ i ] != ' u ' ) : NEW_LINE INDENT temp += S [ i ] NEW_LINE DEDENT DEDENT if ( len ( temp ) ) : NEW_LINE INDENT...
Count pairs from an array whose quotient of division of larger number by the smaller number does not exceed K | Python3 program for the above approach ; Function to count the number having quotient of division of larger element by the smaller element in the pair not exceeding K ; Sort the array in ascending order ; Sto...
from bisect import bisect_right NEW_LINE def countPairs ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT high = bisect_right ( arr , k * arr [ i ] ) NEW_LINE ans += high - i - 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 2 , 3 , 9 , 5 ] NEW...
Kth highest XOR of diagonal elements from a Matrix | Function to find K - th maximum XOR of any diagonal in the matrix ; Number or rows ; Number of columns ; Store XOR of diagonals ; Traverse each diagonal ; Starting column of diagonal ; Count total elements in the diagonal ; Store XOR of current diagonal ; Push XOR of...
def findXOR ( mat , K ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE digXOR = [ ] NEW_LINE for l in range ( 1 , N + M , 1 ) : NEW_LINE INDENT s_col = max ( 0 , l - N ) NEW_LINE count = min ( [ l , ( M - s_col ) , N ] ) NEW_LINE currXOR = 0 NEW_LINE for j in range ( count ) : NEW_LINE INDENT...
Maximum sum of absolute differences between distinct pairs of a triplet from an array | Function to find the maximum sum of absolute differences between distinct pairs of triplet in array ; Stores the maximum sum ; Sort the array in ascending order ; Sum of differences between pairs of the triplet ; Print the sum ; Dri...
def maximumSum ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE sum = ( arr [ N - 1 ] - arr [ 0 ] ) + ( arr [ N - 2 ] - arr [ 0 ] ) + ( arr [ N - 1 ] - arr [ N - 2 ] ) ; NEW_LINE print ( sum ) NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE maximumSum ( arr , N ) NEW_LINE
Maximum and minimum sum of Bitwise XOR of pairs from an array | Python3 program for the above approach ; c [ int , [ a , b ] ] Function to find the required sum ; Keeps the track of the visited array elements ; Stores the result ; Keeps count of visited elements ; Traverse the vector , V ; If n elements are visited , b...
v = [ ] NEW_LINE def findSum ( n ) : NEW_LINE INDENT global v NEW_LINE um = { } NEW_LINE res = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( cnt == n ) : NEW_LINE INDENT break NEW_LINE DEDENT x = v [ i ] [ 1 ] [ 0 ] NEW_LINE y = v [ i ] [ 1 ] [ 1 ] NEW_LINE xorResult = v [ i ] [ 0 ] NE...
Lexicographically smallest permutation having maximum sum of differences between adjacent elements | Function to find the lexicographically smallest permutation of an array such that the sum of the difference between adjacent elements is maximum ; Stores the size of the array ; Sort the given array in increasing order ...
def maximumSumPermutation ( arr ) : NEW_LINE INDENT N = len ( arr ) ; NEW_LINE arr . sort ( ) ; NEW_LINE temp = arr [ 0 ] ; NEW_LINE arr [ 0 ] = arr [ N - 1 ] ; NEW_LINE arr [ N - 1 ] = temp ; NEW_LINE for i in arr : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NE...
Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | Python3 program to implement the above approach ; Function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; Sort the array in ascending order ; Store the cou...
import math NEW_LINE def findMaxNumbers ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT opr = math . ceil ( math . log2 ( arr [ i ] ) ) NEW_LINE k -= opr NEW_LINE if ( k < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT cnt += 1 NEW_LINE DEDENT print ( cnt )...
Mean of given array after removal of K percent of smallest and largest array elements | Function to calculate the mean of a given array after removal of Kth percent of smallest and largest array elements ; Sort the array ; Find the K - th percent of the array size ; Traverse the array ; Skip the first K - th percent & ...
def meanOfRemainingElements ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE kthPercent = ( N * K ) / 100 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i >= kthPercent and i < ( N - kthPercent ) ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT mean = sum / ( N - 2 * kthPercen...
Make the array elements equal by performing given operations minimum number of times | Function to calculate the minimum operations of given type required to make the array elements equal ; Stores the total count of operations ; Traverse the array ; Update difference between pairs of adjacent elements ; Store the maxim...
def minOperation ( a , N ) : NEW_LINE INDENT totOps = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT totOps += abs ( a [ i ] - a [ i + 1 ] ) NEW_LINE DEDENT maxOps = max ( abs ( a [ 0 ] - a [ 1 ] ) , abs ( a [ N - 1 ] - a [ N - 2 ] ) ) NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT maxOps = max ( maxOps...
Count swaps required to sort an array using Insertion Sort | Stores the sorted array elements ; Function to count the number of swaps required to merge two sorted subarray in a sorted form ; Stores the count of swaps ; Function to count the total number of swaps required to sort the array ; Stores the total count of sw...
temp = [ 0 ] * 100000 NEW_LINE def merge ( A , left , mid , right ) : NEW_LINE INDENT swaps = 0 NEW_LINE i , j , k = left , mid , left NEW_LINE while ( i < mid and j <= right ) : NEW_LINE INDENT if ( A [ i ] <= A [ j ] ) : NEW_LINE INDENT temp [ k ] = A [ i ] NEW_LINE k , i = k + 1 , i + 1 NEW_LINE DEDENT else : NEW_LI...
Maximum removals possible from an array such that sum of its elements is greater than or equal to that of another array | Function to maximize the count of elements required to be removed from arr [ ] such that the sum of arr [ ] is greater than or equal to sum of the array brr [ ] ; Sort the array arr [ ] ; Stores ind...
def maxCntRemovedfromArray ( arr , N , brr , M ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE i = 0 NEW_LINE sumArr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sumArr += arr [ i ] NEW_LINE DEDENT sumBrr = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT sumBrr += brr [ i ] NEW_LINE DEDENT cntRemEl...
Find any two pairs ( a , b ) and ( c , d ) such that a d | Function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; If no such pair is found ; Driver Code
def findPair ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT a , b = arr [ i ] [ 0 ] , arr [ i ] [ 1 ] NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT c , d = arr [ j ] [ 0 ] , arr [ j ] [ 1 ] NEW_LINE if ( a < c and b > d ) : NEW_LINE INDENT print ( " ( " , a , b , " ) , ▁ ( " , c , d , " ...
Find any two pairs ( a , b ) and ( c , d ) such that a d | Function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; Sort the array in increasing order of first element of pairs ; Traverse the array ; If no such pair found ; Driver Code
def findPair ( arr , N ) : NEW_LINE INDENT arr . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT b = arr [ i - 1 ] [ 1 ] NEW_LINE d = arr [ i ] [ 1 ] NEW_LINE if ( b > d ) : NEW_LINE INDENT print ( " ( " , arr [ i - 1 ] [ 0 ] , b , " ) , ▁ ( " , arr [ i ] [ 0 ] , d , " ) " ) NEW_LI...
Print indices in non | Function to print the order of array elements generating non - decreasing quotient after division by X ; Stores the quotient and the order ; Traverse the array ; Sort the vector ; Print the order ; Driver Code
def printOrder ( order , N , X ) : NEW_LINE INDENT vect = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( order [ i ] % X == 0 ) : NEW_LINE INDENT vect . append ( [ order [ i ] // X , i + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT vect . append ( [ order [ i ] // X + 1 , i + 1 ] ) NEW_LINE DEDENT DEDENT vect...
Shuffle 2 n integers as a1 | Function to reverse the array from the position ' start ' to position 'end ; Stores mid of start and end ; Traverse the array in the range [ start , end ] ; Stores arr [ start + i ] ; Update arr [ start + i ] ; Update arr [ end - i ] ; Utility function to shuffle the given array in the of f...
' NEW_LINE def reverse ( arr , start , end ) : NEW_LINE INDENT mid = ( end - start + 1 ) // 2 NEW_LINE for i in range ( mid ) : NEW_LINE INDENT temp = arr [ start + i ] NEW_LINE arr [ start + i ] = arr [ end - i ] NEW_LINE arr [ end - i ] = temp NEW_LINE DEDENT return arr NEW_LINE DEDENT def shuffleArrayUtil ( arr , st...
Reduce sum of same | Function to check if elements of B can be rearranged such that A [ i ] + B [ i ] <= X ; Checks the given condition ; Sort A in ascending order ; Sort B in descending order ; Traverse the arrays A and B ; If A [ i ] + B [ i ] exceeds X ; Rearrangement not possible , set flag to false ; If flag is tr...
def rearrange ( A , B , N , X ) : NEW_LINE INDENT flag = True NEW_LINE A = sorted ( A ) NEW_LINE B = sorted ( B ) [ : : - 1 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] + B [ i ] > X ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) ...
Minimum increments or decrements by D required to make all array elements equal | Function to find minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Sort the array ; Traverse the array ; If difference between two consecutive elements are not divi...
def numOperation ( arr , N , D ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( ( arr [ i + 1 ] - arr [ i ] ) % D != 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT DEDENT count = 0 NEW_LINE mid = arr [ N // 2 ] NEW_LINE for i in range ( N ) : NEW_LINE I...
Maximize sum of second minimums of each K length partitions of the array | Function to find the maximum sum of second smallest of each partition of size K ; Sort the array A in ascending order ; Store the maximum sum of second smallest of each partition of size K ; Select every ( K - 1 ) th element as second smallest e...
def findSum ( A , N , K ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( N // K , N , K - 1 ) : NEW_LINE INDENT sum += A [ i ] ; NEW_LINE DEDENT print ( sum ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 4 ; NEW_LINE A = [ 2 , 3 , 1 , 4 , 7 , 5 , 6 , 1 ] ; NEW_L...
Minimize remaining array element by removing pairs and replacing them with their average | Function to find the smallest element left in the array by removing pairs and inserting their average ; Stores array elements such that the largest element present at top of PQ ; Traverse the array ; Insert arr [ i ] into PQ ; It...
def findSmallestNumLeft ( arr , N ) : NEW_LINE INDENT PQ = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT PQ . append ( arr [ i ] ) NEW_LINE DEDENT PQ = sorted ( PQ ) NEW_LINE while ( len ( PQ ) > 1 ) : NEW_LINE INDENT top1 = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE top2 = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW...
Find the array element from indices not divisible by K having largest composite product of digits | Python3 program to implement the above approach ; Function to check if a number is a composite number or not ; Corner cases ; Check if number is divisible by 2 or 3 ; Check if number is a multiple of any other prime numb...
from math import ceil , sqrt NEW_LINE def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 5 , ceil ( sqrt ( n ) ) ,...
Split array into K | Function to find the minimum sum of 2 nd smallest elements of each subset ; Sort the array ; Stores minimum sum of second elements of each subset ; Traverse first K 2 nd smallest elements ; Update their sum ; Prthe sum ; Driver Code ; Given Array ; Given size of the array ; Given subset lengths
def findMinimum ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , 2 * ( N // K ) , 2 ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 20 , 5 , 7 , 8 , 14 , 2 , 17 , 16 , 1...
Find two non | Function to check if two non - intersecting subarrays with equal sum exists or not ; Sort the given array ; Traverse the array ; Check for duplicate elements ; If no duplicate element is present in the array ; Driver code ; Given array ; Size of array
def findSubarrays ( arr , N ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE i = 0 ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT print ( " NO " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_...
Selection Sort VS Bubble Sort | Function for bubble sort ; Iterate from 1 to n - 1 ; Iterate from 0 to n - i - 1 ; Driver Code
def Bubble_Sort ( arr , n ) : NEW_LINE INDENT flag = True NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT flag = False NEW_LINE for j in range ( n - i ) : NEW_LINE INDENT if ( arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ] NEW_LINE flag = True NEW_LINE DEDENT DED...
Print all array elements appearing more than N / K times | Function to prall array elements whose frequency is greater than N / K ; Sort the array , arr [ ] ; Traverse the array ; Stores frequency of arr [ i ] ; Traverse array elements which is equal to arr [ i ] ; Update cnt ; Update i ; If frequency of arr [ i ] is g...
def NDivKWithFreq ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE i = 0 NEW_LINE while i < N : NEW_LINE INDENT cnt = 1 NEW_LINE while ( ( i + 1 ) < N and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( cnt > ( N // K ) ) : NEW_LINE INDENT print ( arr [ i ] , ...
Sort M elements of given circular array starting from index K | Function to print the circular array ; Print the array ; Function to sort m elements of diven circular array starting from index k ; Traverse M elements ; Iterate from index k to k + m - 1 ; Check if the next element in the circular array is less than the ...
def printCircularArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def sortCircularArray ( arr , n , k , m ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( k , k + m - 1 ) : NEW_LINE INDENT if ( arr [ j % n ] > ...
Minimize cost required to complete all processes | Function to find minimum cost required to complete all the process ; Sort the array on descending order of Y ; Stores length of array ; Stores minimum cost required to complete all the process ; Stores minimum cost to initiate any process ; Traverse the array ; If minC...
def minimumCostReqToCompthePrcess ( arr ) : NEW_LINE INDENT arr . sort ( key = lambda x : x [ 0 ] - x [ 1 ] ) NEW_LINE n = len ( arr ) NEW_LINE minCost = 0 NEW_LINE minCostInit = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] [ 1 ] > minCostInit : NEW_LINE INDENT minCost += ( arr [ i ] [ 1 ] - minCostIn...
Split array into equal length subsets with maximum sum of Kth largest element of each subset | Function to find the maximum sum of Kth largest element of M equal length partition ; Stores sum of K_th largest element of equal length partitions ; If N is not divisible by M ; Stores length of each partition ; If K is grea...
def maximumKthLargestsumPart ( arr , N , M , K ) : NEW_LINE INDENT maxSum = 0 NEW_LINE if ( N % M != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT sz = ( N / M ) NEW_LINE if ( K > sz ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE for i in range ( 0 , N // 2 ) : NEW_LINE INDENT t = arr [...
Minimize difference between maximum and minimum array elements by exactly K removals | Function to minimize the difference of the maximum and minimum array elements by removing K elements ; Base Condition ; Sort the array ; Initialize left and right pointers ; Iterate for K times ; Removing right element to reduce the ...
def minimumRange ( arr , N , K ) : NEW_LINE INDENT if ( K >= N ) : NEW_LINE INDENT print ( 0 , end = ' ' ) ; NEW_LINE return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE left = 0 ; right = N - 1 ; NEW_LINE for i in range ( K ) : NEW_LINE INDENT if ( arr [ right - 1 ] - arr [ left ] < arr [ right ] - arr [ left + 1 ] ) :...
Split array into K subsets to maximize sum of their second largest elements | Function to split array into K subsets having maximum sum of their second maximum elements ; Sort the array ; Stores the maximum possible sum of second maximums ; Add second maximum of current subset ; Proceed to the second maximum of next su...
def splitArray ( arr , n , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = n - 1 NEW_LINE result = 0 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT result += arr [ i - 1 ] NEW_LINE i -= 2 NEW_LINE K -= 1 NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 1 ,...
Count subsequences for every array element in which they are the maximum | Function to merge the subarrays arr [ l . . m ] and arr [ m + 1 , . . r ] based on indices [ ] ; If a [ indices [ l ] ] is less than a [ indices [ j ] ] , add indice [ l ] to temp ; Else add indices [ j ] ; Add remaining elements ; Add remaingin...
def merge ( indices , a , l , mid , r ) : NEW_LINE INDENT temp_ind = [ 0 ] * ( r - l + 1 ) NEW_LINE j = mid + 1 NEW_LINE i = 0 NEW_LINE temp_l = l NEW_LINE while ( l <= mid and j <= r ) : NEW_LINE INDENT if ( a [ indices [ l ] ] < a [ indices [ j ] ] ) : NEW_LINE INDENT temp_ind [ i ] = indices [ l ] NEW_LINE i += 1 NE...
Maximize cost to empty given array by repetitively removing K array elements | Function to find the maximum cost to remove all array elements ; Stores maximum cost to remove array elements ; Sort array in ascending order ; Traverse the array ; Update maxCost ; Driver Code
def maxCostToRemove ( arr , N , K ) : NEW_LINE INDENT maxCost = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE for i in range ( 0 , N , K ) : NEW_LINE INDENT maxCost += arr [ i + 1 ] NEW_LINE DEDENT return maxCost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 ] NEW_LI...
Print all numbers up to N in words in lexicographical order | Function to convert a number to words ; Stores the digits ; Base cases ; Stores strings of unit place ; Stores strings for corner cases ; Stores strings for ten 's place digits ; Stores strings for powers of 10 ; If given number contains a single digit ; Ite...
def convert_to_words ( n ) : NEW_LINE INDENT num = str ( n ) NEW_LINE length = len ( num ) NEW_LINE ans = " " NEW_LINE if ( length == 0 ) : NEW_LINE INDENT ans += " Empty ▁ String " NEW_LINE return ans NEW_LINE DEDENT single_digits = [ " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven "...
Minimize cost to convert all array elements to 0 | Python3 program for the above approach ; Function to calculate the minimum cost of converting all array elements to 0 s ; Stores subarrays of 0 s only ; Traverse the array ; If consecutive 0 s occur ; Increment if needed ; Push the current length of consecutive 0 s in ...
import sys NEW_LINE def minimumCost ( binary , n , a , b ) : NEW_LINE INDENT groupOfZeros = [ ] NEW_LINE length = 0 NEW_LINE i = 0 NEW_LINE increment_need = True NEW_LINE while ( i < n ) : NEW_LINE INDENT increment_need = True NEW_LINE while ( i < n and binary [ i ] == 0 ) : NEW_LINE INDENT length += 1 NEW_LINE i += 1 ...
Reduce array to longest sorted array possible by removing either half of given array in each operation | Function to check if the subarray arr [ i . . j ] is a sorted subarray or not ; Traverse all elements of the subarray arr [ i ... j ] ; If the previous element of the subarray exceeds current element ; Return 0 ; Re...
def isSortedparitions ( arr , i , j ) : NEW_LINE INDENT for k in range ( i + 1 , j + 1 ) : NEW_LINE INDENT if ( arr [ k ] < arr [ k - 1 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def partitionsArr ( arr , i , j ) : NEW_LINE INDENT if ( i >= j ) : NEW_LINE INDENT return 1 NEW_LINE DED...