text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Maximum sum of increasing order elements from n arrays | Python3 program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Sort each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; j = - 1... | M = 4 ; NEW_LINE def maximumSum ( a , n ) : NEW_LINE INDENT global M ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT a [ i ] . sort ( ) ; NEW_LINE DEDENT sum = a [ n - 1 ] [ M - 1 ] ; NEW_LINE prev = a [ n - 1 ] [ M - 1 ] ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( M - 1 , -... |
Maximum sum of increasing order elements from n arrays | Python3 program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; max_smaller equals to INT... | M = 4 NEW_LINE def maximumSum ( a , n ) : NEW_LINE INDENT prev = max ( max ( a ) ) NEW_LINE Sum = prev NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT max_smaller = - 10 ** 9 NEW_LINE for j in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] [ j ] < prev and a [ i ] [ j ] > max_smaller ) : NEW... |
Pairs such that one is a power multiple of other | Program to find pairs count ; function to count the required pairs ; sort the given array ; for each A [ i ] traverse rest array ; count Aj such that Ai * k ^ x = Aj ; increase x till Ai * k ^ x <= largest element ; driver program | import math NEW_LINE def countPairs ( A , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE A . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT x = 0 NEW_LINE while ( ( A [ i ] * math . pow ( k , x ) ) <= A [ j ] ) : NEW_LINE INDENT if ( ( A [ i ] * math . pow ( k , ... |
Minimum distance between two occurrences of maximum | Function to return min distance ; case a ; case b ; case c ; driver program | def minDistance ( arr , n ) : NEW_LINE INDENT maximum_element = arr [ 0 ] NEW_LINE min_dis = n NEW_LINE index = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( maximum_element == arr [ i ] ) : NEW_LINE INDENT min_dis = min ( min_dis , ( i - index ) ) NEW_LINE index = i NEW_LINE DEDENT elif ( maximum_element ... |
Find final value if we double after every successful search in array | Function to Find the value of k ; Search for k . After every successful search , double k . ; Driver 's Code | def findValue ( arr , n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == k ) : NEW_LINE INDENT k = k * 2 NEW_LINE DEDENT DEDENT return k NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 8 , 1 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( findValue ( arr , n , k ) ) NEW_LINE |
Last duplicate element in a sorted array | Python3 code to print last duplicate element and its index in a sorted array ; if array is null or size is less than equal to 0 return ; compare elements and return last duplicate and its index ; If we reach here , then no duplicate found . ; Driver Code | def dupLastIndex ( arr , n ) : NEW_LINE INDENT if ( arr == None or n <= 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT print ( " Last β index : " , i , " Last " , β " duplicate item : " , arr [ i ] ) NEW_LINE return... |
Find an array element such that all elements are divisible by it | Function to find smallest num ; Traverse for all elements ; Stores the minimum if it divides all ; Driver code | def findSmallest ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( a [ j ] % a [ i ] ) >= 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == n - 1 ) : NEW_LINE INDENT return a [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT a = [ 2... |
Find an array element such that all elements are divisible by it | Function to find the smallest element ; Function to find smallest num ; Find the smallest element ; Check if all array elements are divisible by smallest . ; Driver code | def min_element ( a ) : NEW_LINE INDENT m = 10000000 NEW_LINE for i in range ( 0 , len ( a ) ) : NEW_LINE INDENT if ( a [ i ] < m ) : NEW_LINE INDENT m = a [ i ] NEW_LINE DEDENT DEDENT return m NEW_LINE DEDENT def findSmallest ( a , n ) : NEW_LINE INDENT smallest = min_element ( a ) NEW_LINE for i in range ( 1 , n ) : ... |
Maximum in array which is at | Function to find the index of Max element that satisfies the condition ; Finding index of max of the array ; Returns - 1 if the max element is not twice of the i - th element . ; Driver code | def findIndex ( arr ) : NEW_LINE INDENT maxIndex = 0 NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > arr [ maxIndex ] ) : NEW_LINE INDENT maxIndex = i NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT if ( maxIndex != i and arr [ maxIndex ] < ( 2 * arr [ i ] ) ) ... |
Consecutive steps to roof top | Python3 code to find maximum number of consecutive steps ; Function to count consecutive steps ; count the number of consecutive increasing height building ; Driver code | import math NEW_LINE def find_consecutive_steps ( arr , len ) : NEW_LINE INDENT count = 0 ; maximum = 0 NEW_LINE for index in range ( 1 , len ) : NEW_LINE INDENT if ( arr [ index ] > arr [ index - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT maximum = max ( maximum , count ) NEW_LINE count ... |
Maximum difference between groups of size two | Python 3 program to find minimum difference between groups of highest and lowest ; Sorting the whole array . ; Driver code | def CalculateMax ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE min_sum = arr [ 0 ] + arr [ 1 ] NEW_LINE max_sum = arr [ n - 1 ] + arr [ n - 2 ] NEW_LINE return abs ( max_sum - min_sum ) NEW_LINE DEDENT arr = [ 6 , 7 , 1 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CalculateMax ( arr , n ) ) NEW_LINE |
Minimum difference between groups of size two | Python3 program to find minimum difference between groups of highest and lowest sums . ; Sorting the whole array . ; Generating sum groups . ; Driver Code | def calculate ( a , n ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE s = [ ] ; NEW_LINE i = 0 ; NEW_LINE j = n - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT s . append ( ( a [ i ] + a [ j ] ) ) ; NEW_LINE i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT mini = min ( s ) ; NEW_LINE maxi = max ( s ) ; NEW_LINE return abs ( max... |
Closest numbers from a list of unsorted integers | Returns minimum difference between any two pair in arr [ 0. . n - 1 ] ; Sort array elements ; Compare differences of adjacent pairs to find the minimum difference . ; Traverse array again and print all pairs with difference as minDiff . ; Driver code | def printMinDiffPairs ( arr , n ) : NEW_LINE INDENT if n <= 1 : return NEW_LINE arr . sort ( ) NEW_LINE minDiff = arr [ 1 ] - arr [ 0 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT minDiff = min ( minDiff , arr [ i ] - arr [ i - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - ar... |
Maximum absolute difference of value and index sums | Brute force Python 3 program to calculate the maximum absolute difference of an array . ; Utility function to calculate the value of absolute difference for the pair ( i , j ) . ; Function to return maximum absolute difference in brute force . ; Variable for storing... | def calculateDiff ( i , j , arr ) : NEW_LINE INDENT return abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) NEW_LINE DEDENT def maxDistance ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( calculateDiff ( i , j , arr ) > result ) :... |
Maximum absolute difference of value and index sums | Function to return maximum absolute difference in linear time . ; max and min variables as described in algorithm . ; Updating max and min variables as described in algorithm . ; Calculating maximum absolute difference . ; Driver program to test above function | def maxDistance ( array ) : NEW_LINE INDENT max1 = - 2147483648 NEW_LINE min1 = + 2147483647 NEW_LINE max2 = - 2147483648 NEW_LINE min2 = + 2147483647 NEW_LINE for i in range ( len ( array ) ) : NEW_LINE INDENT max1 = max ( max1 , array [ i ] + i ) NEW_LINE min1 = min ( min1 , array [ i ] + i ) NEW_LINE max2 = max ( ma... |
Number of local extrema in an array | function to find local extremum ; start loop from position 1 till n - 1 ; check if a [ i ] if greater than both its neighbours , then add 1 to x ; check if a [ i ] if less than both its neighbours , then add 1 to x ; driver program | def extrema ( a , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT count += ( a [ i ] > a [ i - 1 ] and a [ i ] > a [ i + 1 ] ) ; NEW_LINE count += ( a [ i ] < a [ i - 1 ] and a [ i ] < a [ i + 1 ] ) ; NEW_LINE DEDENT return count NEW_LINE DEDENT a = [ 1 , 0 , 2 , 1 ] NEW_LINE n =... |
Find closest number in array | Returns element closest to target in arr [ ] ; Corner cases ; Doing binary search ; If target is less than array element , then search in left ; If target is greater than previous to mid , return closest of two ; Repeat for left half ; If target is greater than mid ; update i ; Only singl... | def findClosest ( arr , n , target ) : NEW_LINE INDENT if ( target <= arr [ 0 ] ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT if ( target >= arr [ n - 1 ] ) : NEW_LINE INDENT return arr [ n - 1 ] NEW_LINE DEDENT i = 0 ; j = n ; mid = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT mid = ( i + j ) // 2 NEW_LINE if (... |
Number of pairs with maximum sum | Python program to count pairs with maximum sum ; traverse through all the pairs ; traverse through all pairs and keep a count of the number of maximum pairs ; driver code | def _sum ( a , n ) : NEW_LINE INDENT maxSum = - 9999999 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT maxSum = max ( maxSum , a [ i ] + a [ j ] ) NEW_LINE DEDENT DEDENT c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if a [ i ... |
Number of pairs with maximum sum | Python 3 program to count pairs with maximum sum . ; Function to find the number of maximum pair sums ; Find maximum and second maximum elements . Also find their counts . ; If maximum element appears more than once . ; If maximum element appears only once . ; Driver Code | import sys NEW_LINE def sum ( a , n ) : NEW_LINE INDENT maxVal = a [ 0 ] ; maxCount = 1 NEW_LINE secondMax = sys . maxsize NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] == maxVal ) : NEW_LINE INDENT maxCount += 1 NEW_LINE DEDENT elif ( a [ i ] > maxVal ) : NEW_LINE INDENT secondMax = maxVal NEW_LINE ... |
Find first k natural numbers missing in given array | Prints first k natural numbers in arr [ 0. . n - 1 ] ; Find first positive number ; Now find missing numbers between array elements ; Find missing numbers after maximum . ; Driver code | def printKMissing ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = 0 NEW_LINE while ( i < n and arr [ i ] <= 0 ) : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT count = 0 NEW_LINE curr = 1 NEW_LINE while ( count < k and i < n ) : NEW_LINE INDENT if ( arr [ i ] != curr ) : NEW_LINE INDENT print ( str ( curr ) +... |
Find first k natural numbers missing in given array | Program to print first k missing number ; creating a hashmap ; Iterate over array ; Iterate to find missing element ; Driver Code | def printmissingk ( arr , n , k ) : NEW_LINE INDENT d = { } NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT d [ arr [ i ] ] = arr [ i ] NEW_LINE DEDENT cnt = 1 NEW_LINE fl = 0 NEW_LINE for i in range ( n + k ) : NEW_LINE INDENT if cnt not in d : NEW_LINE INDENT fl += 1 NEW_LINE print ( cnt , end = " β " ) NEW... |
Noble integers in an array ( count of greater elements is equal to value ) | Returns a Noble integer if present , else returns - 1. ; If count of greater elements is equal to arr [ i ] ; Driver code | def nobleInteger ( arr , size ) : NEW_LINE INDENT for i in range ( 0 , size ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , size ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == arr [ i ] ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT D... |
Noble integers in an array ( count of greater elements is equal to value ) | Python3 code to find Noble elements in an array ; Return a Noble element if present before last ; In case of duplicates we reach last occurrence here ; Driver code | def nobleInteger ( arr ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE n = len ( arr ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i ] == arr [ i + 1 ] : NEW_LINE INDENT continue NEW_LINE DEDENT if arr [ i ] == n - i - 1 : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT if arr [ n - 1 ] == 0 : NEW_... |
Minimum sum of absolute difference of pairs of two arrays | Python3 program to find minimum sum of absolute differences of two arrays . ; Sort both arrays ; Find sum of absolute differences ; Both a [ ] and b [ ] must be of same size . | def findMinSum ( a , b , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + abs ( a [ i ] - b [ i ] ) NEW_LINE DEDENT return sum NEW_LINE DEDENT a = [ 4 , 1 , 8 , 7 ] NEW_LINE b = [ 2 , 3 , 6 , 5 ] NEW_LINE n = len ( a ) NEW_LINE print (... |
Minimum product subset of an array | def to find maximum product of a subset ; Find count of negative numbers , count of zeros , maximum valued negative number , minimum valued positive number and product of non - zero numbers ; If number is 0 , we don 't multiply it with product. ; Count negatives and keep track of m... | def minProductSubset ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT max_neg = float ( ' - inf ' ) NEW_LINE min_pos = float ( ' inf ' ) NEW_LINE count_neg = 0 NEW_LINE count_zero = 0 NEW_LINE prod = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NE... |
Repeatedly search an element by doubling it after every successful search | Python program to repeatedly search an element by doubling it after every successful search ; Sort the given array so that binary search can be applied on it ; Maximum array element ; search for the element b present or not in array ; Driver co... | def binary_search ( a , x , lo = 0 , hi = None ) : NEW_LINE INDENT if hi is None : NEW_LINE INDENT hi = len ( a ) NEW_LINE DEDENT while lo < hi : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE midval = a [ mid ] NEW_LINE if midval < x : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT elif midval > x : NEW_LINE INDENT hi ... |
Maximum sum of pairwise product in an array with negative allowed | Python3 code for above implementation ; Function to find the maximum sum ; Sort the array first ; First multiply negative numbers pairwise and sum up from starting as to get maximum sum . ; Second multiply positive numbers pairwise and summed up from t... | Mod = 1000000007 NEW_LINE def findSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE i = 0 NEW_LINE while i < n and arr [ i ] < 0 : NEW_LINE INDENT if i != n - 1 and arr [ i + 1 ] <= 0 : NEW_LINE INDENT sum = ( sum + ( arr [ i ] * arr [ i + 1 ] ) % Mod ) % Mod NEW_LINE i += 2 NEW_LINE DEDENT els... |
Iteratively Reverse a linked list using only 2 pointers ( An Interesting Method ) | A linked list node ; Function to reverse the linked list using 2 pointers ; Function to push a node ; Function to print linked list ; Start with the empty list | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def reverse ( head_ref ) : NEW_LINE INDENT current = head_ref NEW_LINE next = None NEW_LINE while ( current . next != None ) : NEW_LINE INDENT next = current . next NEW_LINE current . ... |
Delete alternate nodes of a Linked List | deletes alternate nodes of a list starting with head ; Change the next link of head ; Recursively call for the new next of head | def deleteAlt ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT node = head . next NEW_LINE if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT head . next = node . next NEW_LINE deleteAlt ( head . next ) NEW_LINE DEDENT |
Identical Linked Lists | Linked list Node ; head of list ; Returns true if linked lists a and b are identical , otherwise false ; If we reach here , then a and b are not null and their data is same , so move to next nodes in both lists ; If linked lists are identical , then ' a ' and ' b ' must be null at this point . ... | class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def areIdentical ( self , listb ) : NEW_LINE INDENT a = self . head NE... |
Identical Linked Lists | A recursive Python3 function to check if two linked lists are identical or not ; If both lists are empty ; If both lists are not empty , then data of current nodes must match , and same should be recursively true for rest of the nodes . ; If we reach here , then one of the lists is empty and ot... | def areIdentical ( a , b ) : NEW_LINE INDENT if ( a == None and b == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( a != None and b != None ) : NEW_LINE INDENT return ( ( a . data == b . data ) and areIdentical ( a . next , b . next ) ) NEW_LINE DEDENT return False NEW_LINE DEDENT |
Rotate a Linked List | Link list node ; This function rotates a linked list counter - clockwise and updates the head . The function assumes that k is smaller than size of linked list . ; Let us understand the below code for example k = 4 and list = 10.20 . 30.40 .50 . 60. ; Traverse till the end . ; Traverse the linked... | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def rotate ( head_ref , k ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT current = head_ref NEW_LINE while ( current . next != None ) : NEW_LINE INDENT curr... |
Sort a linked list of 0 s , 1 s and 2 s | Python program to sort a linked list of 0 , 1 and 2 ; head of list ; Linked list Node ; initialise count of 0 1 and 2 as 0 ; count total number of '0' , '1' and '2' * count [ 0 ] will store total number of '0' s * count [ 1 ] will store total number of '1' s * count [ 2 ] will ... | class LinkedList ( object ) : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT class Node ( object ) : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def sortList ( self ) : NEW_LINE INDENT count = ... |
Flatten a multilevel linked list | A linked list node has data , next pointer and child pointer | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE self . child = None NEW_LINE DEDENT DEDENT |
Rearrange a linked list such that all even and odd positioned nodes are together | Linked List Node ; A utility function to create a new node ; Rearranges given linked list such that all even positioned nodes are before odd positioned . Returns new head of linked List . ; Corner case ; Initialize first nodes of even an... | class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def newNode ( self , key ) : NEW_LINE INDENT temp = Node ( key ) NEW_L... |
Add 1 to a number represented as linked list | Node class ; Function to create a new node with given data ; Recursively add 1 from end to beginning and returns carry after all nodes are processed . ; If linked list is empty , then return carry ; Add carry returned be next node call ; Update data and return new carry ; ... | 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 newNode ( data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = data NEW_LINE new_node . next = None NEW_LINE return new_node NEW_LINE DEDENT def addW... |
Point arbit pointer to greatest value right side node in a linked list | Node class ; Function to reverse the linked list ; This function populates arbit pointer in every node to the greatest value to its right . ; Reverse given linked list ; Initialize pointer to maximum value node ; Traverse the reversed list ; Conne... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE self . arbit = None NEW_LINE DEDENT DEDENT def reverse ( head ) : NEW_LINE INDENT prev = None NEW_LINE current = head NEW_LINE next = None NEW_LINE while ( current != None ) : NEW_LINE IND... |
Point arbit pointer to greatest value right side node in a linked list | Node class ; This function populates arbit pointer in every node to the greatest value to its right . ; using static maxNode to keep track of maximum orbit node address on right side ; if head is null simply return the list ; if head . next is nul... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE self . arbit = None NEW_LINE DEDENT DEDENT maxNode = newNode ( None ) NEW_LINE def populateArbit ( head ) : NEW_LINE INDENT global maxNode NEW_LINE if ( head == None ) : NEW_LINE INDENT... |
Check if a linked list of strings forms a palindrome | Node class ; ; A utility function to check if str is palindrome or not ; Match characters from beginning and end . ; Returns true if string formed by linked list is palindrome ; Append all nodes to form a string ; Utility function to print the linked LinkedList ; ... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def isPalindromeUtil ( self , string ) : NEW_LINE INDENT return ... |
Delete last occurrence of an item from linked list | A linked list Node ; Function to delete the last occurrence ; If found key , update ; If the last occurrence is the last node ; If it is not the last node ; Utility function to create a new node with given key ; This function prints contents of linked list starting f... | class Node : NEW_LINE INDENT def __init__ ( self , new_data ) : NEW_LINE INDENT self . data = new_data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def deleteLast ( head , x ) : NEW_LINE INDENT temp = head NEW_LINE ptr = None NEW_LINE while ( temp != None ) : NEW_LINE INDENT if ( temp . data == x ) : NEW_LINE IND... |
Flatten a multi | | def flattenList2 ( head ) : NEW_LINE INDENT headcop = head NEW_LINE save = [ ] NEW_LINE save . append ( head ) NEW_LINE prev = None NEW_LINE while ( len ( save ) != 0 ) : NEW_LINE INDENT temp = save [ - 1 ] NEW_LINE save . pop ( ) NEW_LINE if ( temp . next ) : NEW_LINE INDENT save . append ( temp . next ) NEW_LINE DEDE... |
Partitioning a linked list around a given value and keeping the original order | Link list Node ; A utility function to create a new node ; Function to make two separate lists and return head after concatenating ; Let us initialize first and last nodes of three linked lists 1 ) Linked list of values smaller than x . 2 ... | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = data NEW_LINE new_node . next = None NEW_LINE return new_node NEW_LINE DEDENT def partition ( head... |
Check linked list with a loop is palindrome or not | Node class ; Function to find loop starting node . loop_node - . Pointer to one of the loop nodes head - . Pointer to the start node of the linked list ; Count the number of nodes in loop ; Fix one pointer to head ; And the other pointer to k nodes after head ; Move ... | 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 getLoopstart ( loop_node , head ) : NEW_LINE INDENT ptr1 = loop_node NEW_LINE ptr2 = loop_node NEW_LINE k = 1 NEW_LINE i = 0 NEW_LINE while ( ptr1 . next != ptr2 ) : NEW_... |
Length of longest palindrome list in a linked list using O ( 1 ) extra space | Linked List node ; function for counting the common elements ; loop to count coomon in the list starting from node a and b ; increment the count for same values ; Returns length of the longest palindrome sublist in given list ; loop till the... | 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 countCommon ( a , b ) : NEW_LINE INDENT count = 0 NEW_LINE while ( a != None and b != None ) : NEW_LINE INDENT if ( a . data == b . data ) : NEW_LINE INDENT count = count... |
Implementing Iterator pattern of a single Linked List | ; Creating a list ; Elements to be added at the end . in the above created list . ; Elements of list are retrieved through iterator . | if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT list = [ ] NEW_LINE list . append ( 1 ) NEW_LINE list . append ( 2 ) NEW_LINE list . append ( 3 ) NEW_LINE for it in list : NEW_LINE INDENT print ( it , end = ' β ' ) NEW_LINE DEDENT DEDENT |
Move all occurrences of an element to end in a linked list | Linked List node ; A urility function to create a new node . ; Utility function to print the elements in Linked list ; Moves all occurrences of given key to end of linked list . ; Keeps track of locations where key is present . ; Traverse list ; If current po... | 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 newNode ( x ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = x NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def printList ( head ) : NEW_L... |
Move all occurrences of an element to end in a linked list | A Linked list Node ; Function to remove key to end ; Node to keep pointing to tail ; Node to point to last of linked list ; Node prev2 to point to previous when head . data != key ; Loop to perform operations to remove key to end ; Function to display linked ... | 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 newNode ( x ) : NEW_LINE INDENT temp = Node ( x ) NEW_LINE return temp NEW_LINE DEDENT def keyToEnd ( head , key ) : NEW_LINE INDENT tail = head NEW_LINE if ( head == Non... |
Remove every k | Python3 program to delete every k - th Node of a singly linked list . ; Linked list Node ; To remove complete list ( Needed forcase when k is 1 ) ; Deletes every k - th node and returns head of modified list . ; If linked list is empty ; Initialize ptr and prev before starting traversal . ; Traverse li... | 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 freeList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT next = node . next NEW_LINE node = next NEW_LINE DEDENT return node NEW_... |
Check whether the length of given linked list is Even or Odd | Defining structure ; Function to check the length of linklist ; Push function ; Allocating node ; Next of new node to head ; head points to new node ; Driver code ; Adding elements to Linked List ; Checking for length of linklist | class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE self . head = None NEW_LINE DEDENT def LinkedListLength ( self ) : NEW_LINE INDENT while ( self . head != None and self . head . next != None ) : NEW_LINE INDENT self . head = self . head . next... |
Find the sum of last n nodes of the given Linked List | Linked List node ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to point to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; tra... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT head = None NEW_LINE n = 0 NEW_LINE sum = 0 NEW_LINE def push ( head_ref , new_data ) : NEW_LINE INDENT global head NEW_LINE new_node = Node ( 0 ) NEW_LINE new_node . data = ... |
Find the sum of last n nodes of the given Linked List | A Linked list Node ; Function to insert a Node at the beginning of the linked list ; Allocate Node ; Put in the data ; Link the old list to the new Node ; Move the head to poto the new Node ; utility function to find the sum of last ' n ' Nodes ; if n == 0 ; rever... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT head = None NEW_LINE 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 NEW_LIN... |
Find the sum of last n nodes of the given Linked List | A Linked list Node ; Function to insert a Node at the beginning of the linked list ; Allocate Node ; Put in the data ; Link the old list to the new Node ; Move the head to poto the new Node ; Utility function to find the sum of last ' n ' Nodes ; If n == 0 ; Calcu... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT head = None NEW_LINE 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 NEW_LIN... |
In | Structure for a linked list node ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; Allocate node ; Put in the data ; Link the old list off the new node ; Move the head to point to the new node ; Function to merge two sorted linked lists LL1 a... | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_... |
Delete middle of linked list | Link list Node ; Count of nodes ; Deletes middle node and returns head of the modified list ; Base cases ; Find the count of nodes ; Find the middle node ; Delete the middle node ; Delete the middle node ; A utility function to print a given linked list ; Utility function to create a new ... | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def countOfNodes ( head ) : NEW_LINE INDENT count = 0 NEW_LINE while ( head != None ) : NEW_LINE INDENT head = head . next NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DED... |
Merge K sorted linked lists | Set 1 | A Linked List node ; Function to prnodes in a given linked list ; The main function that takes an array of lists arr [ 0. . last ] and generates the sorted output ; Traverse form second list to last ; head of both the lists , 0 and ith list . ; Break if list ended ; Smaller than fi... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def printList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = " β " ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT def mergeKL... |
Merge two sorted lists ( in | Python3 program to merge two sorted linked lists in - place . ; Function to create newNode in a linkedlist ; A utility function to print linked list ; Merges two given lists in - place . This function mainly compares head nodes and calls mergeUtil ( ) ; start with the linked list whose hea... | 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 newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE temp . data = key NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def... |
Merge two sorted lists ( in | Linked List node ; Function to create newNode in a linkedlist ; A utility function to print linked list ; Merges two lists with headers as h1 and h2 . It assumes that h1 ' s β data β is β smaller β than β or β equal β to β h2' s data . ; if only one node in first list simply point its head... | 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 newNode ( key ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = key NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def printList ( node ) : N... |
Recursive selection sort for singly linked list | Swapping node links | Linked List node ; function to swap nodes ' currX ' and ' currY ' in a linked list without swapping data ; make ' currY ' as new head ; adjust links ; Swap next pointers ; function to sort the linked list using recursive selection sort technique ; ... | 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 swapNodes ( head_ref , currX , currY , prevY ) : NEW_LINE INDENT head_ref = currY NEW_LINE prevY . next = currX NEW_LINE temp = currY . next NEW_LINE currY . next = currX... |
Insert a node after the n | Linked List node ; function to get a new node ; allocate memory for the node ; put in the data ; function to insert a node after the nth node from the end ; if list is empty ; get a new node for the value 'x ; find length of the list , i . e , the number of nodes in the list ; traverse up ... | 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 getNode ( data ) : NEW_LINE INDENT newNode = Node ( 0 ) NEW_LINE newNode . data = data NEW_LINE newNode . next = None NEW_LINE return newNode NEW_LINE DEDENT def insertAf... |
Insert a node after the n | Structure of a node ; Function to get a new node ; Allocate memory for the node ; Function to insert a node after the nth node from the end ; If list is empty ; Get a new node for the value 'x ; Initializing the slow and fast pointers ; Move ' fast _ ptr ' to point to the nth node from the... | 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 getNode ( data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE return newNode NEW_LINE DEDENT def insertAfterNthNode ( head , n , x ) : NEW_LINE INDENT if ( head == ... |
Make middle node head in a linked list | Linked List node ; function to get the middle node set it as the beginning of the linked list ; to traverse nodes one by one ; to traverse nodes by skipping one ; to keep track of previous middle ; for previous node of middle node ; move one node each time ; move two nodes each ... | 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 setMiddleHead ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT one_node = head NEW_LINE two_node = head NEW_LINE prev = None N... |
Doubly Linked List | Set 1 ( Introduction and Insertion ) | Given a node as prev_node , insert a new node after the given node ; 1. check if the given prev_node is NULL ; 2. allocate node & 3. put in the data ; 4. Make next of new node as next of prev_node ; 5. Make the next of prev_node as new_node ; 6. Make prev_node... | def insertAfter ( self , prev_node , new_data ) : NEW_LINE INDENT if prev_node is None : NEW_LINE INDENT print ( " This β node β doesn ' t β exist β in β DLL " ) NEW_LINE return NEW_LINE DEDENT new_node = Node ( data = new_data ) NEW_LINE new_node . next = prev_node . next NEW_LINE prev_node . next = new_node NEW_LINE ... |
Sorted merge of two sorted doubly circular linked lists | Python3 implementation for Sorted merge of two sorted doubly circular linked list ; A utility function to insert a new node at the beginning of doubly circular linked list ; allocate space ; put in the data ; if list is empty ; pointer points to last Node ; sett... | 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 self . prev = None NEW_LINE DEDENT DEDENT def insert ( head_ref , data ) : NEW_LINE INDENT new_node = Node ( data ) NEW_LINE new_node . data = data NEW_LINE if ( head_... |
Reverse a Doubly Linked List | Set 4 ( Swapping Data ) | Python3 Program to Reverse a List using Data Swapping ; Insert a new node at the head of the list ; Function to reverse the list ; Traverse the list and set right pointer to end of list ; Swap data of left and right pointer and move them towards each other until ... | 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 newNode ( val ) : NEW_LINE INDENT temp = Node ( val ) NEW_LINE temp . data = val NEW_LINE temp . prev = None NEW_LINE temp . next = None NEW_LINE ret... |
Check if a doubly linked list of characters is palindrome or not | Structure of node ; Given a reference ( pointer to pointer ) to the head of a list and an int , inserts a new node on the front of the list . ; Function to check if list is palindrome or not ; Find rightmost node ; Driver program | class Node : NEW_LINE INDENT def __init__ ( self , data , next , prev ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE self . prev = prev NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data , head_ref , None ) NEW_LINE if head_ref != None : NEW... |
Print nodes between two given level numbers of a binary tree | A binary tree node ; Given a binary tree , print nodes form level number ' low ' to level number 'high ; Marker node to indicate end of level ; Initialize level number ; Enqueue the only first level node and marker node for end of level ; print Q Simple l... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printLevels ( root , low , high ) : NEW_LINE INDENT Q = [ ] NEW_LINE marker = Node ( 11114 ) NEW_LINE level = 1 NEW_LINE Q . append ( root ) NEW... |
Print nodes at k distance from root | A Binary tree node ; Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printKDistant ( root , k ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if k == 0 : NEW_LINE INDENT print root ... |
Print nodes at k distance from root | Iterative | Node of binary tree Function to add a new node ; Function to prnodes of given level ; extra None is appended to keep track of all the nodes to be appended before level is incremented by 1 ; prwhen level is equal to k ; break the loop if level exceeds the given level num... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printKDistant ( root , klevel ) : NEW_LINE INDENT q = [ ] NEW_LINE level = 1 NEW_LINE flag = False NEW_LINE q . append ( root ) NEW_LINE q . append ( No... |
Print all leaf nodes of a Binary Tree from left to right | Binary tree node ; Function to print leaf nodes from left to right ; If node is null , return ; If node is leaf node , print its data ; If left child exists , check for leaf recursively ; If right child exists , check for leaf recursively ; Driver Code ; Let us... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printLeafNodes ( root : Node ) -> None : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( not root . left and no... |
Print all nodes at distance k from a given node | A binary tree node ; Recursive function to print all the nodes at distance k int the tree ( or subtree ) rooted with given root . See ; Base Case ; If we reach a k distant node , print it ; Recur for left and right subtee ; Prints all nodes at distance k from a given ta... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printkDistanceNodeDown ( root , k ) : NEW_LINE INDENT if root is None or k < 0 : NEW_LINE INDENT return NEW_LINE DEDENT if k == 0 : NEW_LINE ... |
Print all nodes that don 't have sibling | A Binary Tree Node ; Function to print all non - root nodes that don 't have a sibling ; Base Case ; If this is an internal node , recur for left and right subtrees ; If left child is NULL , and right is not , print right child and recur for right child ; If right child is NUL... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printSingles ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if root . left is not None and root . right is ... |
Print all nodes that are at distance k from a leaf node | utility that allocates a new Node with the given key ; This function prints all nodes that are distance k from a leaf node path [ ] - . Store ancestors of a node visited [ ] - . Stores true if a node is printed as output . A node may be k distance away from many... | class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def kDistantFromLeafUtil ( node , path , visited , pathLen , k ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT path [ pathLen ... |
Print leftmost and rightmost nodes of a Binary Tree | Python3 program to print corner node at each level of binary tree ; A binary tree node has key , pointer to left child and a pointer to right child ; Function to print corner node at each level ; If the root is null then simply return ; star node is for keeping trac... | from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printCorner ( root : Node ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT q ... |
Print Binary Tree in 2 | Python3 Program to print binary tree in 2D ; Binary Tree Node ; Constructor that allocates a new node with the given data and null left and right pointers . ; Function to print binary tree in 2D It does reverse inorder traversal ; Base case ; Increase distance between levels ; Process right chi... | COUNT = [ 10 ] NEW_LINE class newNode : 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 print2DUtil ( root , space ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT space +=... |
Print Left View of a Binary Tree | A binary tree node ; Recursive function pritn left view of a binary tree ; Base Case ; If this is the first node of its level ; Recur for left and right subtree ; A wrapper over leftViewUtil ( ) ; Driver program to test above function | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def leftViewUtil ( root , level , max_level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if ( max_level [ 0 ] < l... |
Print Left View of a Binary Tree | Utility function to create a new tree node ; function to print left view of binary tree ; number of nodes at current level ; Traverse all nodes of current level ; Print the left most element at the level ; Add left node to queue ; Add right node to queue ; Driver Code ; construct bina... | class newNode : 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 self . hd = 0 NEW_LINE DEDENT DEDENT def printRightView ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q... |
Reduce the given Array of [ 1 , N ] by rotating left or right based on given conditions | Function to find the last element left after performing N - 1 queries of type X ; Stores the next power of 2 ; Iterate until nextPower is at most N ; If X is equal to 1 ; Stores the power of 2 less than or equal to N ; Return the ... | def rotate ( arr , N , X ) : NEW_LINE INDENT nextPower = 1 NEW_LINE while ( nextPower <= N ) : NEW_LINE INDENT nextPower *= 2 NEW_LINE DEDENT if ( X == 1 ) : NEW_LINE INDENT ans = nextPower - N NEW_LINE return ans NEW_LINE DEDENT prevPower = nextPower // 2 NEW_LINE return 2 * ( N - prevPower ) + 1 NEW_LINE DEDENT arr =... |
Maximum number of 0 s placed consecutively at the start and end in any rotation of a Binary String | Function to find the maximum sum of consecutive 0 s present at the start and end of a string present in any of the rotations of the given string ; Check if all the characters in the string are 0 ; Iterate over character... | def findMaximumZeros ( st , n ) : NEW_LINE INDENT c0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == '0' ) : NEW_LINE INDENT c0 += 1 NEW_LINE DEDENT DEDENT if ( c0 == n ) : NEW_LINE INDENT print ( n ) NEW_LINE return NEW_LINE DEDENT s = st + st NEW_LINE mx = 0 NEW_LINE for i in range ( n ) : NEW_LI... |
Maximum number of 0 s placed consecutively at the start and end in any rotation of a Binary String | Function to find the maximum sum of consecutive 0 s present at the start and end of any rotation of the string str ; Stores the count of 0 s ; If the frequency of '1' is 0 ; Print n as the result ; Stores the required s... | def findMaximumZeros ( string , n ) : NEW_LINE INDENT c0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT c0 += 1 NEW_LINE DEDENT DEDENT if ( c0 == n ) : NEW_LINE INDENT print ( n , end = " " ) NEW_LINE return NEW_LINE DEDENT mx = 0 NEW_LINE cnt = 0 NEW_LINE for i in rang... |
Modify a matrix by rotating ith row exactly i times in clockwise direction | Function to rotate every i - th row of the matrix i times ; Traverse the matrix row - wise ; Reverse the current row ; Reverse the first i elements ; Reverse the last ( N - i ) elements ; Increment count ; Print final matrix ; Driver Code | def rotateMatrix ( mat ) : NEW_LINE INDENT i = 0 NEW_LINE mat1 = [ ] NEW_LINE for it in mat : NEW_LINE INDENT it . reverse ( ) NEW_LINE it1 = it [ : i ] NEW_LINE it1 . reverse ( ) NEW_LINE it2 = it [ i : ] NEW_LINE it2 . reverse ( ) NEW_LINE i += 1 NEW_LINE mat1 . append ( it1 + it2 ) NEW_LINE DEDENT for rows in mat1 :... |
Modify given array to a non | Function to check if a non - decreasing array can be obtained by rotating the original array ; Stores copy of original array ; Sort the given vector ; Traverse the array ; Rotate the array by 1 ; If array is sorted ; If it is not possible to sort the array ; Driver Code ; Given array ; Siz... | def rotateArray ( arr , N ) : NEW_LINE INDENT v = arr NEW_LINE v . sort ( reverse = False ) NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT x = arr [ N - 1 ] NEW_LINE i = N - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] NEW_LINE arr [ 0 ] = x NEW_LINE i -= 1 NEW_LINE DEDENT if ( ar... |
Maximum value possible by rotating digits of a given number | Function to find the maximum value possible by rotations of digits of N ; Store the required result ; Store the number of digits ; Iterate over the range [ 1 , len - 1 ] ; Store the unit 's digit ; Store the remaining number ; Find the next rotation ; If the... | def findLargestRotation ( num ) : NEW_LINE INDENT ans = num NEW_LINE length = len ( str ( num ) ) NEW_LINE x = 10 ** ( length - 1 ) NEW_LINE for i in range ( 1 , length ) : NEW_LINE INDENT lastDigit = num % 10 NEW_LINE num = num // 10 NEW_LINE num += ( lastDigit * x ) NEW_LINE if ( num > ans ) : NEW_LINE INDENT ans = n... |
Rotate digits of a given number by K | Function to find the count of digits in N ; Stores count of digits in N ; Calculate the count of digits in N ; Update digit ; Update N ; Function to rotate the digits of N by K ; Stores count of digits in N ; Update K so that only need to handle left rotation ; Stores first K digi... | def numberOfDigit ( N ) : NEW_LINE INDENT digit = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT digit += 1 NEW_LINE N //= 10 NEW_LINE DEDENT return digit NEW_LINE DEDENT def rotateNumberByK ( N , K ) : NEW_LINE INDENT X = numberOfDigit ( N ) NEW_LINE K = ( ( K % X ) + X ) % X NEW_LINE left_no = N // pow ( 10 , X - K ) N... |
Count rotations required to sort given array in non | Function to count minimum anti - clockwise rotations required to sort the array in non - increasing order ; Stores count of arr [ i + 1 ] > arr [ i ] ; Store last index of arr [ i + 1 ] > arr [ i ] ; Traverse the given array ; If the adjacent elements are in increas... | def minMovesToSort ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE index = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE index = i NEW_LINE DEDENT DEDENT if ( count == 0 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT elif ( count == N - ... |
Maximize sum of diagonal of a matrix by rotating all rows or all columns | Python3 program to implement the above approach ; Function to find maximum sum of diagonal elements of matrix by rotating either rows or columns ; Stores maximum diagonal sum of elements of matrix by rotating rows or columns ; Rotate all the col... | import sys NEW_LINE N = 3 NEW_LINE def findMaximumDiagonalSumOMatrixf ( A ) : NEW_LINE INDENT maxDiagonalSum = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT curr += A [ j ] [ ( i + j ) % N ] NEW_LINE DEDENT maxDiagonalSum = max ( maxDiagonal... |
Queries to find maximum sum contiguous subarrays of given length in a rotating array | Function to calculate the maximum sum of length k ; Calculating the max sum for the first k elements ; Find subarray with maximum sum ; Update the sum ; Return maximum sum ; Function to calculate gcd of the two numbers n1 and n2 ; Ba... | def MaxSum ( arr , n , k ) : NEW_LINE INDENT i , max_sum = 0 , 0 NEW_LINE sum = 0 NEW_LINE while i < k : NEW_LINE INDENT sum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT max_sum = sum NEW_LINE while ( i < n ) : NEW_LINE INDENT sum = sum - arr [ i - k ] + arr [ i ] NEW_LINE if ( max_sum < sum ) : NEW_LINE INDENT max_sum... |
Minimize characters to be changed to make the left and right rotation of a string same | Function to find the minimum characters to be removed from the string ; Initialize answer by N ; If length is even ; Frequency array for odd and even indices ; Store the frequency of the characters at even and odd indices ; Stores ... | def getMinimumRemoval ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE ans = n NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT freqEven = { } NEW_LINE freqOdd = { } NEW_LINE for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT freqEven [ chr ( ch ) ] = 0 NEW_LINE freqOdd [ chr ( ch ) ] = 0 NEW_LINE DE... |
Longest subsequence of a number having same left and right rotation | Python3 program to implement the above approach ; Function to find the longest subsequence having equal left and right rotation ; Length of the string ; Iterate for all possible combinations of a two - digit numbers ; Check for alternate occurrence o... | import sys NEW_LINE def findAltSubSeq ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = - sys . maxsize - 1 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT cur , f = 0 , 0 NEW_LINE for k in range ( n ) : NEW_LINE INDENT if ( f == 0 and ord ( s [ k ] ) - ord ( '0' ) == i ) : N... |
Rotate matrix by 45 degrees | Function to rotate matrix by 45 degree ; Counter Variable ; Iterate [ 0 , m ] ; Iterate [ 0 , n ] ; Diagonal Elements Condition ; Appending the Diagonal Elements ; Printing reversed Diagonal Elements ; Dimensions of Matrix ; Given matrix ; Function Call | def matrix ( n , m , li ) : NEW_LINE INDENT ctr = 0 NEW_LINE while ( ctr < 2 * n - 1 ) : NEW_LINE INDENT print ( " β " * abs ( n - ctr - 1 ) , end = " " ) NEW_LINE lst = [ ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if i + j == ctr : NEW_LINE INDENT lst . append ( li [ i ] [... |
Mth element after K Right Rotations of an Array | Function to return Mth element of array after k right rotations ; The array comes to original state after N rotations ; If K is greater or equal to M ; Mth element after k right rotations is ( N - K ) + ( M - 1 ) th element of the array ; Otherwise ; ( M - K - 1 ) th el... | def getFirstElement ( a , N , K , M ) : NEW_LINE INDENT K %= N NEW_LINE if ( K >= M ) : NEW_LINE INDENT index = ( N - K ) + ( M - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT index = ( M - K - 1 ) NEW_LINE DEDENT result = a [ index ] NEW_LINE return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT... |
Find the Mth element of the Array after K left rotations | Function to return Mth element of array after k left rotations ; The array comes to original state after N rotations ; Mth element after k left rotations is ( K + M - 1 ) % N th element of the original array ; Return the result ; Driver Code ; Array initializat... | def getFirstElement ( a , N , K , M ) : NEW_LINE INDENT K %= N NEW_LINE index = ( K + M - 1 ) % N NEW_LINE result = a [ index ] NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 3 , 4 , 5 , 23 ] NEW_LINE N = len ( a ) NEW_LINE K = 2 NEW_LINE M = 1 NEW_LINE print ( getFirstEl... |
Rotate all odd numbers right and all even numbers left in an Array of 1 to N | Function to left rotate ; Function to right rotate ; Function to rotate the array ; Driver code | def left_rotate ( arr ) : NEW_LINE INDENT last = arr [ 1 ] ; NEW_LINE for i in range ( 3 , len ( arr ) , 2 ) : NEW_LINE INDENT arr [ i - 2 ] = arr [ i ] NEW_LINE DEDENT arr [ len ( arr ) - 1 ] = last NEW_LINE DEDENT def right_rotate ( arr ) : NEW_LINE INDENT start = arr [ len ( arr ) - 2 ] NEW_LINE for i in range ( len... |
Maximize count of corresponding same elements in given permutations using cyclic rotations | Python3 program for the above approach ; Function to maximize the matching pairs between two permutation using left and right rotation ; Left array store distance of element from left side and right array store distance of elem... | from collections import defaultdict NEW_LINE def maximumMatchingPairs ( perm1 , perm2 , n ) : NEW_LINE INDENT left = [ 0 ] * n NEW_LINE right = [ 0 ] * n NEW_LINE mp1 = { } NEW_LINE mp2 = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp1 [ perm1 [ i ] ] = i NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT m... |
Count of rotations required to generate a sorted array | Function to return the count of rotations ; Find the smallest element ; Return its index ; If array is not rotated at all ; Driver Code | def countRotation ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 4 , 5 , 1 , 2 , 3 ] NEW_LINE n = len ( arr1 ) NEW_LINE print (... |
Count of rotations required to generate a sorted array | Function to return the count of rotations ; If array is not rotated ; Check if current element is greater than the next element ; The next element is the smallest ; Check if current element is smaller than it 's previous element ; Current element is the smallest... | def countRotation ( arr , low , high ) : NEW_LINE INDENT if ( low > high ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mid = low + ( high - low ) // 2 NEW_LINE if ( mid < high and arr [ mid ] > arr [ mid + 1 ] ) : NEW_LINE INDENT return mid + 1 NEW_LINE DEDENT if ( mid > low and arr [ mid ] < arr [ mid - 1 ] ) : NEW_LIN... |
Range sum queries for anticlockwise rotations of Array by K indices | Function to execute the queries ; Construct a new array of size 2 * N to store prefix sum of every index ; Copy elements to the new array ; Calculate the prefix sum for every index ; Set start pointer as 0 ; Query to perform anticlockwise rotation ; ... | def rotatedSumQuery ( arr , n , query , Q ) : NEW_LINE INDENT prefix = [ 0 ] * ( 2 * n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix [ i ] = arr [ i ] NEW_LINE prefix [ i + n ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , 2 * n ) : NEW_LINE INDENT prefix [ i ] += prefix [ i - 1 ] ; NEW_LINE DEDENT start ... |
Check if a string can be formed from another string by at most X circular clockwise shifts | Function to check that the string s1 can be converted to s2 by clockwise circular shift of all characters of str1 atmost X times ; Check for all characters of the strings whether the difference between their ascii values is les... | def isConversionPossible ( s1 , s2 , x ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE s1 = list ( s1 ) NEW_LINE s2 = list ( s2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT diff = ord ( s2 [ i ] ) - ord ( s1 [ i ] ) NEW_LINE if diff == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if diff < 0 : NEW_LINE INDENT diff = d... |
Count rotations which are divisible by 10 | Function to return the count of all rotations which are divisible by 10. ; Loop to iterate through the number ; If the last digit is 0 , then increment the count ; Driver code | def countRotation ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while n > 0 : NEW_LINE INDENT digit = n % 10 NEW_LINE if ( digit % 2 == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT n = int ( n / 10 ) NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10203 ; N... |
Clockwise rotation of Linked List | Link list node ; A utility function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; A utility function to print linked list ; Function that rotates the given linked list clockwise by k and returns the up... | 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 ) NEW_LINE ( head_re... |
Check if it is possible to make array increasing or decreasing by rotating the array | Python3 implementation of the approach ; Function that returns True if the array can be made increasing or decreasing after rotating it in any direction ; If size of the array is less than 3 ; Check if the array is already decreasing... | import sys NEW_LINE def isPossible ( a , n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT flag = 0 ; NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( not ( a [ i ] > a [ i + 1 ] and a [ i + 1 ] > a [ i + 2 ] ) ) : NEW_LINE INDENT flag = 1 ; NEW_LINE break ; NEW_LINE DEDENT DED... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.