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 means no element is found in a [ i ] so return 0 ; Driver Code | 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 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] [ j ] < prev ) : NEW_LINE INDENT prev = a [ i ] [ j ] ; NEW_LINE sum += prev ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( j == - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT arr = [ [ 1 , 7 , 3 , 4 ] , [ 4 , 2 , 5 , 1 ] , [ 9 , 5 , 1 , 8 ] ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maximumSum ( arr , n ) ) ; NEW_LINE |
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_MIN means no element is found in a [ i ] so return 0 ; Driver Code | 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_LINE INDENT max_smaller = a [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( max_smaller == - 10 ** 9 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT prev = max_smaller NEW_LINE Sum += max_smaller NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ [ 1 , 7 , 3 , 4 ] , [ 4 , 2 , 5 , 1 ] , [ 9 , 5 , 1 , 8 ] ] NEW_LINE n = len ( arr ) NEW_LINE print ( maximumSum ( arr , n ) ) NEW_LINE |
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 , x ) ) == A [ j ] ) : NEW_LINE INDENT ans += 1 NEW_LINE break NEW_LINE DEDENT x += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 3 , 8 , 9 , 12 , 18 , 4 , 24 , 2 , 6 ] NEW_LINE n = len ( A ) NEW_LINE k = 3 NEW_LINE print ( countPairs ( A , n , k ) ) NEW_LINE |
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 < arr [ i ] ) : NEW_LINE INDENT maximum_element = arr [ i ] NEW_LINE min_dis = n NEW_LINE index = i NEW_LINE DEDENT else : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT return min_dis NEW_LINE DEDENT arr = [ 6 , 3 , 1 , 3 , 6 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum β distance β = " , minDistance ( arr , n ) ) NEW_LINE |
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 NEW_LINE DEDENT DEDENT print ( " no β duplicate β found " ) NEW_LINE DEDENT arr = [ 1 , 5 , 5 , 6 , 6 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE dupLastIndex ( arr , n ) NEW_LINE |
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 = [ 25 , 20 , 5 , 10 , 100 ] NEW_LINE n = len ( a ) NEW_LINE print ( findSmallest ( a , n ) ) NEW_LINE |
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 ) : NEW_LINE INDENT if ( a [ i ] % smallest >= 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT return smallest NEW_LINE DEDENT a = [ 25 , 20 , 5 , 10 , 100 ] NEW_LINE n = len ( a ) NEW_LINE print ( findSmallest ( a , n ) ) NEW_LINE |
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 ] ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT return maxIndex NEW_LINE DEDENT arr = [ 3 , 6 , 1 , 0 ] NEW_LINE print ( findIndex ( arr ) ) NEW_LINE |
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 = 0 NEW_LINE DEDENT DEDENT return max ( maximum , count ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE len = len ( arr ) NEW_LINE print ( find_consecutive_steps ( arr , len ) ) NEW_LINE |
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 ( maxi - mini ) ; NEW_LINE DEDENT a = [ 2 , 6 , 4 , 3 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( calculate ( a , n ) ) ; NEW_LINE |
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 ] - arr [ i - 1 ] ) == minDiff : NEW_LINE INDENT print ( " ( " + str ( arr [ i - 1 ] ) + " , β " + str ( arr [ i ] ) + " ) , β " , end = ' ' ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 3 , 2 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE printMinDiffPairs ( arr , n ) NEW_LINE |
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 the maximum absolute distance throughout the traversal of loops . ; Iterate through all pairs . ; If the absolute difference of current pair ( i , j ) is greater than the maximum difference calculated till now , update the value of result . ; Driver program | 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 ) : NEW_LINE INDENT result = calculateDiff ( i , j , arr ) NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT arr = [ - 70 , - 64 , - 6 , - 56 , 64 , 61 , - 57 , 16 , 48 , - 98 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxDistance ( arr , n ) ) NEW_LINE |
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 ( max2 , array [ i ] - i ) NEW_LINE min2 = min ( min2 , array [ i ] - i ) NEW_LINE DEDENT return max ( max1 - min1 , max2 - min2 ) NEW_LINE DEDENT array = [ - 70 , - 64 , - 6 , - 56 , 64 , 61 , - 57 , 16 , 48 , - 98 ] NEW_LINE print ( maxDistance ( array ) ) NEW_LINE |
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 = len ( a ) NEW_LINE print ( extrema ( a , n ) ) NEW_LINE |
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 single element left after search ; Method to compare which one is the more close . We find the closest by taking the difference between the target and both values . It assumes that val2 is greater than val1 and target lies between these two . ; Driver code | 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 ( arr [ mid ] == target ) : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if ( target < arr [ mid ] ) : NEW_LINE INDENT if ( mid > 0 and target > arr [ mid - 1 ] ) : NEW_LINE INDENT return getClosest ( arr [ mid - 1 ] , arr [ mid ] , target ) NEW_LINE DEDENT j = mid NEW_LINE DEDENT else : NEW_LINE INDENT if ( mid < n - 1 and target < arr [ mid + 1 ] ) : NEW_LINE INDENT return getClosest ( arr [ mid ] , arr [ mid + 1 ] , target ) NEW_LINE DEDENT i = mid + 1 NEW_LINE DEDENT DEDENT return arr [ mid ] NEW_LINE DEDENT def getClosest ( val1 , val2 , target ) : NEW_LINE INDENT if ( target - val1 >= val2 - target ) : NEW_LINE INDENT return val2 NEW_LINE DEDENT else : NEW_LINE INDENT return val1 NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 4 , 5 , 6 , 6 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE target = 11 NEW_LINE print ( findClosest ( arr , n , target ) ) NEW_LINE |
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 ] + a [ j ] == maxSum : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT DEDENT return c NEW_LINE DEDENT array = [ 1 , 1 , 1 , 2 , 2 , 2 ] NEW_LINE n = len ( array ) NEW_LINE print ( _sum ( array , n ) ) NEW_LINE |
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 secondMaxCount = maxCount NEW_LINE maxVal = a [ i ] NEW_LINE maxCount = 1 NEW_LINE DEDENT elif ( a [ i ] == secondMax ) : NEW_LINE INDENT secondMax = a [ i ] NEW_LINE secondMaxCount += 1 NEW_LINE DEDENT elif ( a [ i ] > secondMax ) : NEW_LINE INDENT secondMax = a [ i ] NEW_LINE secondMaxCount = 1 NEW_LINE DEDENT DEDENT if ( maxCount > 1 ) : NEW_LINE INDENT return maxCount * ( maxCount - 1 ) / 2 NEW_LINE DEDENT return secondMaxCount NEW_LINE DEDENT array = [ 1 , 1 , 1 , 2 , 2 , 2 , 3 ] NEW_LINE n = len ( array ) NEW_LINE print ( sum ( array , n ) ) 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 ) + " β " , end = ' ' ) NEW_LINE count = count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT curr = curr + 1 NEW_LINE DEDENT while ( count < k ) : NEW_LINE INDENT print ( str ( curr ) + " β " , end = ' ' ) NEW_LINE curr = curr + 1 NEW_LINE count = count + 1 NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE printKMissing ( arr , n , k ) ; NEW_LINE |
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_LINE if fl == k : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT cnt += 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 1 , 4 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE printmissingk ( arr , n , k ) NEW_LINE |
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 DEDENT return - 1 NEW_LINE DEDENT arr = [ 10 , 3 , 20 , 40 , 2 ] NEW_LINE size = len ( arr ) NEW_LINE res = nobleInteger ( arr , size ) NEW_LINE if ( res != - 1 ) : NEW_LINE INDENT print ( " The β noble β integer β is β " , res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β Noble β Integer β Found " ) NEW_LINE DEDENT |
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_LINE INDENT return arr [ n - 1 ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ 10 , 3 , 20 , 40 , 2 ] NEW_LINE res = nobleInteger ( arr ) NEW_LINE if res != - 1 : NEW_LINE INDENT print ( " The β noble β integer β is " , res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β Noble β Integer β Found " ) NEW_LINE DEDENT |
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 ( findMinSum ( a , b , n ) ) NEW_LINE |
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 maximum valued negative . ; Track minimum positive number of array ; If there are all zeros or no negative number present ; If there are all positive ; If there are even number of negative numbers and count_neg not 0 ; Otherwise result is product of all non - zeros divided by maximum valued negative . ; Driver code | 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 ) : NEW_LINE INDENT count_zero = count_zero + 1 NEW_LINE continue NEW_LINE DEDENT if ( a [ i ] < 0 ) : NEW_LINE INDENT count_neg = count_neg + 1 NEW_LINE max_neg = max ( max_neg , a [ i ] ) NEW_LINE DEDENT if ( a [ i ] > 0 ) : NEW_LINE INDENT min_pos = min ( min_pos , a [ i ] ) NEW_LINE DEDENT prod = prod * a [ i ] NEW_LINE DEDENT if ( count_zero == n or ( count_neg == 0 and count_zero > 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( count_neg == 0 ) : NEW_LINE INDENT return min_pos NEW_LINE DEDENT if ( ( count_neg & 1 ) == 0 and count_neg != 0 ) : NEW_LINE INDENT prod = int ( prod / max_neg ) NEW_LINE DEDENT return prod NEW_LINE DEDENT a = [ - 1 , - 1 , - 2 , 4 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( minProductSubset ( a , n ) ) NEW_LINE |
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 code | 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 = mid NEW_LINE DEDENT else : NEW_LINE INDENT return mid NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def findElement ( a , n , b ) : NEW_LINE INDENT a . sort ( ) NEW_LINE mx = a [ n - 1 ] NEW_LINE while ( b < max ) : NEW_LINE INDENT if ( binary_search ( a , b , 0 , n ) != - 1 ) : NEW_LINE INDENT b *= 2 NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT return b NEW_LINE DEDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE b = 1 NEW_LINE print findElement ( a , n , b ) NEW_LINE |
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 the last as to get maximum sum . ; To handle case if positive and negative numbers both are odd in counts . ; If one of them occurs odd times ; Driver code | 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 else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT j = n - 1 NEW_LINE while j >= 0 and arr [ j ] > 0 : NEW_LINE INDENT if j != 0 and arr [ j - 1 ] > 0 : NEW_LINE INDENT sum = ( sum + ( arr [ j ] * arr [ j - 1 ] ) % Mod ) % Mod NEW_LINE j -= 2 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j > i : NEW_LINE INDENT sum = ( sum + ( arr [ i ] * arr [ j ] ) % Mod ) % Mod NEW_LINE DEDENT elif i == j : NEW_LINE INDENT sum = ( sum + arr [ i ] ) % Mod NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ - 1 , 9 , 4 , 5 , - 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSum ( arr , n ) ) NEW_LINE |
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 . next = next . next NEW_LINE next . next = ( head_ref ) NEW_LINE head_ref = next NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT head = None NEW_LINE head = push ( head , 20 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 15 ) NEW_LINE head = push ( head , 85 ) NEW_LINE print ( " Given β linked β list " ) NEW_LINE printList ( head ) NEW_LINE head = reverse ( head ) NEW_LINE print ( " Reversed Linked list " ) NEW_LINE printList ( head ) NEW_LINE |
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 . ; 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 . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; Driver Code ; The constructed linked lists are : llist1 : 3 -> 2 -> 1 llist2 : 3 -> 2 -> 1 | 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 NEW_LINE b = listb . head NEW_LINE while ( a != None and b != None ) : NEW_LINE INDENT if ( a . data != b . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT a = a . next NEW_LINE b = b . next NEW_LINE DEDENT return ( a == None and b == None ) NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT DEDENT llist1 = LinkedList ( ) NEW_LINE llist2 = LinkedList ( ) NEW_LINE llist1 . push ( 1 ) NEW_LINE llist1 . push ( 2 ) NEW_LINE llist1 . push ( 3 ) NEW_LINE llist2 . push ( 1 ) NEW_LINE llist2 . push ( 2 ) NEW_LINE llist2 . push ( 3 ) NEW_LINE if ( llist1 . areIdentical ( llist2 ) == True ) : NEW_LINE INDENT print ( " Identical β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β identical β " ) NEW_LINE DEDENT |
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 other is not | 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 list to k - 1 position which will be last element for rotated array . ; Update the head_ref and last element pointer to None ; 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 ; Function to print linked list ; Driver code ; Start with the empty list ; Create a list 10.20 . 30.40 .50 . 60 | 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 current = current . next NEW_LINE DEDENT current . next = head_ref NEW_LINE current = head_ref NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT head_ref = current . next NEW_LINE current . next = None NEW_LINE return head_ref NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE for i in range ( 60 , 0 , - 10 ) : NEW_LINE INDENT head = push ( head , i ) NEW_LINE DEDENT print ( " Given β linked β list β " ) NEW_LINE printList ( head ) NEW_LINE head = rotate ( head , 4 ) NEW_LINE print ( " Rotated Linked list " ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
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 store total number of '2' s ; Let say count [ 0 ] = n1 , count [ 1 ] = n2 and count [ 2 ] = n3 * now start traversing list from head node , * 1 ) fill the list with 0 , till n1 > 0 * 2 ) fill the list with 1 , till n2 > 0 * 3 ) fill the list with 2 , till n3 > 0 ; Inserts a new Node at front of the list . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; Function to print linked list ; Constructed Linked List is 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 8 -> 9 -> null | 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 = [ 0 , 0 , 0 ] NEW_LINE ptr = self . head NEW_LINE while ptr != None : NEW_LINE INDENT count [ ptr . data ] += 1 NEW_LINE ptr = ptr . next NEW_LINE DEDENT i = 0 NEW_LINE ptr = self . head NEW_LINE while ptr != None : NEW_LINE INDENT if count [ i ] == 0 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ptr . data = i NEW_LINE count [ i ] -= 1 NEW_LINE ptr = ptr . next NEW_LINE DEDENT DEDENT DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = self . Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT def printList ( self ) : NEW_LINE INDENT temp = self . head NEW_LINE while temp != None : NEW_LINE INDENT print str ( temp . data ) , NEW_LINE temp = temp . next NEW_LINE DEDENT print ' ' NEW_LINE DEDENT DEDENT llist = LinkedList ( ) NEW_LINE llist . push ( 0 ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 0 ) NEW_LINE llist . push ( 2 ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 2 ) NEW_LINE llist . push ( 1 ) NEW_LINE llist . push ( 2 ) NEW_LINE print " Linked β List β before β sorting " NEW_LINE llist . printList ( ) NEW_LINE llist . sortList ( ) NEW_LINE print " Linked β List β after β sorting " NEW_LINE llist . printList ( ) NEW_LINE |
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 and odd lists ; Remember the first node of even list so that we can connect the even list at the end of odd list . ; If there are no more nodes , then connect first node of even list to the last node of odd list ; Connecting odd nodes ; If there are NO more even nodes after current odd . ; Connecting even nodes ; A utility function to print a linked list ; Function to insert a new node at the beginning ; Driver code | 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_LINE self . next = None NEW_LINE return temp NEW_LINE DEDENT def rearrangeEvenOdd ( self , head ) : NEW_LINE INDENT if ( self . head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT odd = self . head NEW_LINE even = self . head . next NEW_LINE evenFirst = even NEW_LINE while ( 1 == 1 ) : NEW_LINE INDENT if ( odd == None or even == None or ( even . next ) == None ) : NEW_LINE INDENT odd . next = evenFirst NEW_LINE break NEW_LINE DEDENT odd . next = even . next NEW_LINE odd = even . next NEW_LINE if ( odd . next == None ) : NEW_LINE INDENT even . next = None NEW_LINE odd . next = evenFirst NEW_LINE break NEW_LINE DEDENT even . next = odd . next NEW_LINE even = odd . next NEW_LINE DEDENT return head NEW_LINE DEDENT def printlist ( self , node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = " " ) NEW_LINE print ( " - > " , end = " " ) NEW_LINE node = node . next NEW_LINE DEDENT print ( " NULL " ) NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = self . head NEW_LINE self . head = new_node NEW_LINE DEDENT DEDENT ll = LinkedList ( ) NEW_LINE ll . push ( 5 ) NEW_LINE ll . push ( 4 ) NEW_LINE ll . push ( 3 ) NEW_LINE ll . push ( 2 ) NEW_LINE ll . push ( 1 ) NEW_LINE print ( " Given β Linked β List " ) NEW_LINE ll . printlist ( ll . head ) NEW_LINE start = ll . rearrangeEvenOdd ( ll . head ) NEW_LINE print ( " Modified Linked List " ) NEW_LINE ll . printlist ( start ) NEW_LINE |
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 ; This function mainly uses addWithCarry ( ) . ; Add 1 to linked list from end to beginning ; If there is carry after processing all nodes , then we need to add a new node to linked list ; New node becomes head now ; A utility function to print a linked list ; Driver program to test above function | 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 addWithCarry ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT res = head . data + addWithCarry ( head . next ) NEW_LINE head . data = int ( ( res ) % 10 ) NEW_LINE return int ( ( res ) / 10 ) NEW_LINE DEDENT def addOne ( head ) : NEW_LINE INDENT carry = addWithCarry ( head ) NEW_LINE if ( carry != 0 ) : NEW_LINE INDENT newNode = Node ( 0 ) NEW_LINE newNode . data = carry NEW_LINE newNode . next = head NEW_LINE return newNode NEW_LINE DEDENT return head NEW_LINE 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 print ( " " ) NEW_LINE DEDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 9 ) NEW_LINE head . next . next = newNode ( 9 ) NEW_LINE head . next . next . next = newNode ( 9 ) NEW_LINE print ( " List β is β " ) NEW_LINE printList ( head ) NEW_LINE head = addOne ( head ) NEW_LINE print ( " Resultant list is " ) NEW_LINE printList ( head ) NEW_LINE |
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 ; Connect max through arbit pointer ; Update max if required ; Move ahead in reversed list ; Reverse modified linked list and return head . ; Utility function to print result linked list ; Function to create a new node with given data ; Driver code | 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 INDENT next = current . next NEW_LINE current . next = prev NEW_LINE prev = current NEW_LINE current = next NEW_LINE DEDENT return prev NEW_LINE DEDENT def populateArbit ( head ) : NEW_LINE INDENT head = reverse ( head ) NEW_LINE max = head NEW_LINE temp = head . next NEW_LINE while ( temp != None ) : NEW_LINE INDENT temp . arbit = max NEW_LINE if ( max . data < temp . data ) : NEW_LINE INDENT max = temp NEW_LINE DEDENT temp = temp . next NEW_LINE DEDENT return reverse ( head ) NEW_LINE DEDENT def printNextArbitPointers ( node ) : NEW_LINE INDENT print ( " Node Next Pointer Arbit Pointer " ) NEW_LINE while ( node != None ) : NEW_LINE INDENT print ( node . data , " TABSYMBOL TABSYMBOL " , end = " " ) NEW_LINE if ( node . next != None ) : NEW_LINE INDENT print ( node . next . data , " TABSYMBOL TABSYMBOL " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " None " , " TABSYMBOL TABSYMBOL " , end = " " ) NEW_LINE DEDENT if ( node . arbit != None ) : NEW_LINE INDENT print ( node . arbit . data , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " None " , end = " " ) NEW_LINE DEDENT print ( " " ) NEW_LINE node = node . next 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 head = newNode ( 5 ) NEW_LINE head . next = newNode ( 10 ) NEW_LINE head . next . next = newNode ( 2 ) NEW_LINE head . next . next . next = newNode ( 3 ) NEW_LINE head = populateArbit ( head ) NEW_LINE print ( " Resultant Linked List is : " ) NEW_LINE printNextArbitPointers ( head ) NEW_LINE |
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 null it means we reached at the last node just update the max and maxNode ; Calling the populateArbit to the next node ; updating the arbit node of the current node with the maximum value on the right side ; if current Node value id greater then the previous right node then update it ; Utility function to prresult linked list ; Driver code | 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 return NEW_LINE DEDENT if ( head . next == None ) : NEW_LINE INDENT maxNode = head NEW_LINE return NEW_LINE DEDENT populateArbit ( head . next ) NEW_LINE head . arbit = maxNode NEW_LINE if ( head . data > maxNode . data and maxNode . data != None ) : NEW_LINE INDENT maxNode = head NEW_LINE DEDENT return NEW_LINE DEDENT def printNextArbitPointers ( node ) : NEW_LINE INDENT print ( " Node TABSYMBOL Next β Pointer TABSYMBOL Arbit β Pointer " ) NEW_LINE while ( node != None ) : NEW_LINE INDENT print ( node . data , " TABSYMBOL TABSYMBOL " , end = " " ) NEW_LINE if ( node . next ) : NEW_LINE INDENT print ( node . next . data , " TABSYMBOL TABSYMBOL " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NULL " , " TABSYMBOL TABSYMBOL " , end = " " ) NEW_LINE DEDENT if ( node . arbit ) : NEW_LINE INDENT print ( node . arbit . data , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NULL " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT head = newNode ( 5 ) NEW_LINE head . next = newNode ( 10 ) NEW_LINE head . next . next = newNode ( 2 ) NEW_LINE head . next . next . next = newNode ( 3 ) NEW_LINE populateArbit ( head ) NEW_LINE print ( " Resultant β Linked β List β is : " ) NEW_LINE printNextArbitPointers ( head ) NEW_LINE |
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 ; Driver program to test above function | 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 ( string == string [ : : - 1 ] ) NEW_LINE DEDENT def isPalindrome ( self ) : NEW_LINE INDENT node = self . head NEW_LINE temp = [ ] NEW_LINE while ( node is not None ) : NEW_LINE INDENT temp . append ( node . data ) NEW_LINE node = node . next NEW_LINE DEDENT string = " " . join ( temp ) NEW_LINE return self . isPalindromeUtil ( string ) NEW_LINE DEDENT def printList ( self ) : NEW_LINE INDENT temp = self . head NEW_LINE while ( temp ) : NEW_LINE INDENT print temp . data , NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT DEDENT llist = LinkedList ( ) NEW_LINE llist . head = Node ( ' a ' ) NEW_LINE llist . head . next = Node ( ' bc ' ) NEW_LINE llist . head . next . next = Node ( " d " ) NEW_LINE llist . head . next . next . next = Node ( " dcb " ) NEW_LINE llist . head . next . next . next . next = Node ( " a " ) NEW_LINE print " true " if llist . isPalindrome ( ) else " false " NEW_LINE |
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 from the given Node ; Driver code | 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 INDENT ptr = temp NEW_LINE DEDENT temp = temp . next NEW_LINE DEDENT if ( ptr != None and ptr . next == None ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp . next != ptr ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = None NEW_LINE DEDENT if ( ptr != None and ptr . next != None ) : NEW_LINE INDENT ptr . data = ptr . next . data NEW_LINE temp = ptr . next NEW_LINE ptr . next = ptr . next . next NEW_LINE DEDENT return head NEW_LINE DEDENT def newNode ( x ) : NEW_LINE INDENT node = Node ( 0 ) NEW_LINE node . data = x NEW_LINE node . next = None NEW_LINE return node NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT temp = head NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " None " ) NEW_LINE return NEW_LINE DEDENT while ( temp != None ) : NEW_LINE INDENT print ( temp . data , " β - > β " , end = " " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( " None " ) NEW_LINE DEDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE head . next . next . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next . next . next = newNode ( 4 ) NEW_LINE print ( " Created β Linked β list : β " ) NEW_LINE display ( head ) NEW_LINE head = deleteLast ( head , 4 ) NEW_LINE print ( " List β after β deletion β of β 4 : β " ) NEW_LINE display ( head ) NEW_LINE |
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 DEDENT if ( temp . down ) : NEW_LINE INDENT save . append ( temp . down ) NEW_LINE DEDENT if ( prev != None ) : NEW_LINE INDENT prev . next = temp NEW_LINE DEDENT prev = temp NEW_LINE DEDENT return headcop NEW_LINE DEDENT |
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 ) Linked list of values equal to x . 3 ) Linked list of values greater than x . ; Now iterate original list and connect nodes of appropriate linked lists . ; If current node is equal to x , append it to the list of x values ; If current node is less than X , append it to the list of smaller values ; Append to the list of greater values ; Fix end of greater linked list to None if this list has some nodes ; If smaller list is empty ; If smaller list is not empty and equal list is empty ; If both smaller and equal list are non - empty ; 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 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 , x ) : NEW_LINE INDENT smallerHead = None NEW_LINE smallerLast = None NEW_LINE greaterLast = None NEW_LINE greaterHead = None NEW_LINE equalHead = None NEW_LINE equalLast = None NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( head . data == x ) : NEW_LINE INDENT if ( equalHead == None ) : NEW_LINE INDENT equalHead = equalLast = head NEW_LINE DEDENT else : NEW_LINE INDENT equalLast . next = head NEW_LINE equalLast = equalLast . next NEW_LINE DEDENT DEDENT elif ( head . data < x ) : NEW_LINE INDENT if ( smallerHead == None ) : NEW_LINE INDENT smallerLast = smallerHead = head NEW_LINE DEDENT else : NEW_LINE INDENT smallerLast . next = head NEW_LINE smallerLast = head NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( greaterHead == None ) : NEW_LINE INDENT greaterLast = greaterHead = head NEW_LINE DEDENT else : NEW_LINE INDENT greaterLast . next = head NEW_LINE greaterLast = head NEW_LINE DEDENT DEDENT head = head . next NEW_LINE DEDENT if ( greaterLast != None ) : NEW_LINE INDENT greaterLast . next = None NEW_LINE DEDENT if ( smallerHead == None ) : NEW_LINE INDENT if ( equalHead == None ) : NEW_LINE INDENT return greaterHead NEW_LINE DEDENT equalLast . next = greaterHead NEW_LINE return equalHead NEW_LINE DEDENT if ( equalHead == None ) : NEW_LINE INDENT smallerLast . next = greaterHead NEW_LINE return smallerHead NEW_LINE DEDENT smallerLast . next = equalHead NEW_LINE equalLast . next = greaterHead NEW_LINE return smallerHead NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT head = newNode ( 10 ) NEW_LINE head . next = newNode ( 4 ) NEW_LINE head . next . next = newNode ( 5 ) NEW_LINE head . next . next . next = newNode ( 30 ) NEW_LINE head . next . next . next . next = newNode ( 2 ) NEW_LINE head . next . next . next . next . next = newNode ( 50 ) NEW_LINE x = 3 NEW_LINE head = partition ( head , x ) NEW_LINE printList ( head ) NEW_LINE |
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 both pointers at the same pace , they will meet at loop starting node ; This function detects and find loop starting node in the list ; Start traversing list and detect loop ; If slow_p and fast_p meet then find the loop starting node ; Return starting node of loop ; Utility function to check if a linked list with loop is palindrome with given starting point . ; Traverse linked list until last node is equal to loop_start and store the elements till start in a stack ; Traverse linked list until last node is equal to loop_start second time ; Compare data of node with the top of stack If equal then continue ; Else return False ; Return True if linked list is palindrome ; Function to find if linked list is palindrome or not ; Find the loop starting node ; Check if linked list is palindrome ; Driver code ; Create a loop for testing | 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_LINE INDENT ptr1 = ptr1 . next NEW_LINE k = k + 1 NEW_LINE DEDENT ptr1 = head NEW_LINE ptr2 = head NEW_LINE i = 0 NEW_LINE while ( i < k ) : NEW_LINE INDENT ptr2 = ptr2 . next NEW_LINE i = i + 1 NEW_LINE DEDENT while ( ptr2 != ptr1 ) : NEW_LINE INDENT ptr1 = ptr1 . next NEW_LINE ptr2 = ptr2 . next NEW_LINE DEDENT return ptr1 NEW_LINE DEDENT def detectAndgetLoopstarting ( head ) : NEW_LINE INDENT slow_p = head NEW_LINE fast_p = head NEW_LINE loop_start = None NEW_LINE while ( slow_p != None and fast_p != None and fast_p . next != None ) : NEW_LINE INDENT slow_p = slow_p . next NEW_LINE fast_p = fast_p . next . next NEW_LINE if ( slow_p == fast_p ) : NEW_LINE INDENT loop_start = getLoopstart ( slow_p , head ) NEW_LINE break NEW_LINE DEDENT DEDENT return loop_start NEW_LINE DEDENT def isPalindromeUtil ( head , loop_start ) : NEW_LINE INDENT ptr = head NEW_LINE s = [ ] NEW_LINE count = 0 NEW_LINE while ( ptr != loop_start or count != 1 ) : NEW_LINE INDENT s . append ( ptr . data ) NEW_LINE if ( ptr == loop_start ) : NEW_LINE INDENT count = 1 NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT ptr = head NEW_LINE count = 0 NEW_LINE while ( ptr != loop_start or count != 1 ) : NEW_LINE INDENT if ( ptr . data == s [ - 1 ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT if ( ptr == loop_start ) : NEW_LINE INDENT count = 1 NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT return True NEW_LINE DEDENT def isPalindrome ( head ) : NEW_LINE INDENT loop_start = detectAndgetLoopstarting ( head ) NEW_LINE return isPalindromeUtil ( head , loop_start ) NEW_LINE 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 head = newNode ( 50 ) NEW_LINE head . next = newNode ( 20 ) NEW_LINE head . next . next = newNode ( 15 ) NEW_LINE head . next . next . next = newNode ( 20 ) NEW_LINE head . next . next . next . next = newNode ( 50 ) NEW_LINE head . next . next . next . next . next = head . next . next NEW_LINE if ( isPalindrome ( head ) == True ) : NEW_LINE INDENT print ( " Palindrome " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Palindrome " ) NEW_LINE DEDENT |
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 end of the linked list ; The sublist from head to current reversed . ; check for odd length palindrome by finding longest common list elements beginning from prev and from next ( We exclude curr ) ; check for even length palindrome by finding longest common list elements beginning from curr and from next ; update prev and curr for next iteration ; Utility function to create a new list node ; Let us create a linked lists to test the functions Created list is a : 2 -> 4 -> 3 -> 4 -> 2 -> 15 | 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 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT a = a . next NEW_LINE b = b . next NEW_LINE DEDENT return count NEW_LINE DEDENT def maxPalindrome ( head ) : NEW_LINE INDENT result = 0 NEW_LINE prev = None NEW_LINE curr = head NEW_LINE while ( curr != None ) : NEW_LINE INDENT next = curr . next NEW_LINE curr . next = prev NEW_LINE result = max ( result , 2 * countCommon ( prev , next ) + 1 ) NEW_LINE result = max ( result , 2 * countCommon ( curr , next ) ) NEW_LINE prev = curr NEW_LINE curr = next NEW_LINE DEDENT return result NEW_LINE 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 head = newNode ( 2 ) NEW_LINE head . next = newNode ( 4 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 2 ) NEW_LINE head . next . next . next . next . next = newNode ( 15 ) NEW_LINE print ( maxPalindrome ( head ) ) NEW_LINE |
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 pointer is not same as pointer to a key location , then we must have found a key in linked list . We swap data of pCrawl and pKey and move pKey to next position . ; Find next position where key is present ; Moving to next Node ; Driver code | 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_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def moveToEnd ( head , key ) : NEW_LINE INDENT pKey = head NEW_LINE pCrawl = head NEW_LINE while ( pCrawl != None ) : NEW_LINE INDENT if ( pCrawl != pKey and pCrawl . data != key ) : NEW_LINE INDENT pKey . data = pCrawl . data NEW_LINE pCrawl . data = key NEW_LINE pKey = pKey . next NEW_LINE DEDENT if ( pKey . data != key ) : NEW_LINE INDENT pKey = pKey . next NEW_LINE DEDENT pCrawl = pCrawl . next NEW_LINE DEDENT return head NEW_LINE DEDENT head = newNode ( 10 ) NEW_LINE head . next = newNode ( 20 ) NEW_LINE head . next . next = newNode ( 10 ) NEW_LINE head . next . next . next = newNode ( 30 ) NEW_LINE head . next . next . next . next = newNode ( 40 ) NEW_LINE head . next . next . next . next . next = newNode ( 10 ) NEW_LINE head . next . next . next . next . next . next = newNode ( 60 ) NEW_LINE print ( " Before moveToEnd ( ) , the Linked list is " ) NEW_LINE printList ( head ) NEW_LINE key = 10 NEW_LINE head = moveToEnd ( head , key ) NEW_LINE print ( " After moveToEnd ( ) , the Linked list is " ) NEW_LINE printList ( head ) NEW_LINE |
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 list ; Driver Code | 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 == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( tail . next != None ) : NEW_LINE INDENT tail = tail . next NEW_LINE DEDENT last = tail NEW_LINE current = head NEW_LINE prev = None NEW_LINE prev2 = None NEW_LINE while ( current != tail ) : NEW_LINE INDENT if ( current . data == key and prev2 == None ) : NEW_LINE INDENT prev = current NEW_LINE current = current . next NEW_LINE head = current NEW_LINE last . next = prev NEW_LINE last = last . next NEW_LINE last . next = None NEW_LINE prev = None NEW_LINE DEDENT else : NEW_LINE INDENT if ( current . data == key and prev2 != None ) : NEW_LINE INDENT prev = current NEW_LINE current = current . next NEW_LINE prev2 . next = current NEW_LINE last . next = prev NEW_LINE last = last . next NEW_LINE last . next = None NEW_LINE DEDENT elif ( current != tail ) : NEW_LINE INDENT prev2 = current NEW_LINE current = current . next NEW_LINE DEDENT DEDENT DEDENT return head NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = ' β ' ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 5 ) NEW_LINE root . next = newNode ( 2 ) NEW_LINE root . next . next = newNode ( 2 ) NEW_LINE root . next . next . next = newNode ( 7 ) NEW_LINE root . next . next . next . next = newNode ( 2 ) NEW_LINE root . next . next . next . next . next = newNode ( 2 ) NEW_LINE root . next . next . next . next . next . next = newNode ( 2 ) NEW_LINE key = 2 NEW_LINE print ( " Linked β List β before β operations β : " ) NEW_LINE printList ( root ) NEW_LINE print ( " Linked β List β after β operations β : " ) NEW_LINE root = keyToEnd ( root , key ) NEW_LINE printList ( root ) NEW_LINE DEDENT |
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 list and delete every k - th node ; increment Node count ; check if count is equal to k if yes , then delete current Node ; put the next of current Node in the next of previous Node delete ( prev . next ) ; set count = 0 to reach further k - th Node ; update prev if count is not 0 ; Function to print linked list ; Utility function to create a new node . ; Driver Code ; Start with the empty list | 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_LINE DEDENT def deleteKthNode ( head , k ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT freeList ( head ) NEW_LINE return None NEW_LINE DEDENT ptr = head NEW_LINE prev = None NEW_LINE count = 0 NEW_LINE while ( ptr != None ) : NEW_LINE INDENT count = count + 1 NEW_LINE if ( k == count ) : NEW_LINE INDENT prev . next = ptr . next NEW_LINE count = 0 NEW_LINE DEDENT if ( count != 0 ) : NEW_LINE INDENT prev = ptr NEW_LINE DEDENT ptr = prev . next NEW_LINE DEDENT return head NEW_LINE DEDENT def displayList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = ' β ' ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT def newNode ( x ) : NEW_LINE INDENT temp = Node ( x ) NEW_LINE temp . data = x NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE head . next . next . next . next = newNode ( 5 ) NEW_LINE head . next . next . next . next . next = newNode ( 6 ) NEW_LINE head . next . next . next . next . next . next = newNode ( 7 ) NEW_LINE head . next . next . next . next . next . next . next = newNode ( 8 ) NEW_LINE k = 3 NEW_LINE head = deleteKthNode ( head , k ) NEW_LINE displayList ( head ) NEW_LINE DEDENT |
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 . next NEW_LINE DEDENT if ( self . head == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def push ( self , info ) : NEW_LINE INDENT node = Node ( info ) NEW_LINE node . next = ( self . head ) NEW_LINE ( self . head ) = node NEW_LINE DEDENT DEDENT head = Node ( 0 ) NEW_LINE head . push ( 4 ) NEW_LINE head . push ( 5 ) NEW_LINE head . push ( 7 ) NEW_LINE head . push ( 2 ) NEW_LINE head . push ( 9 ) NEW_LINE head . push ( 6 ) NEW_LINE head . push ( 1 ) NEW_LINE head . push ( 2 ) NEW_LINE head . push ( 0 ) NEW_LINE head . push ( 5 ) NEW_LINE head . push ( 5 ) NEW_LINE check = head . LinkedListLength ( ) NEW_LINE if ( check == 0 ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) NEW_LINE DEDENT |
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 ; traverses the list from left to right ; push the node ' s β data β onto β the β stack β ' st ; move to next node ; pop ' n ' nodes from ' st ' and add them ; required sum ; Driver Code ; create linked list 10.6 .8 .4 .12 | 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 = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE head = head_ref NEW_LINE DEDENT def sumOfLastN_NodesUtil ( head , n ) : NEW_LINE INDENT global sum NEW_LINE if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT st = [ ] NEW_LINE sum = 0 NEW_LINE while ( head != None ) : NEW_LINE INDENT st . append ( head . data ) NEW_LINE head = head . next NEW_LINE DEDENT while ( n ) : NEW_LINE INDENT n -= 1 NEW_LINE sum += st [ 0 ] NEW_LINE st . pop ( 0 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT head = None NEW_LINE push ( head , 12 ) NEW_LINE push ( head , 4 ) NEW_LINE push ( head , 8 ) NEW_LINE push ( head , 6 ) NEW_LINE push ( head , 10 ) NEW_LINE n = 2 NEW_LINE print ( " Sum β of β last " , n , " nodes β = " , sumOfLastN_NodesUtil ( head , n ) ) NEW_LINE |
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 ; reverse the linked list ; traverse the 1 st ' n ' Nodes of the reversed linked list and add them ; accumulate Node ' s β data β to β ' sum ; move to next Node ; reverse back the linked list ; required sum ; Driver code ; create linked list 10.6 .8 .4 .12 | 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_LINE head_ref = new_Node NEW_LINE head = head_ref NEW_LINE return head NEW_LINE DEDENT def reverseList ( ) : NEW_LINE INDENT global head ; NEW_LINE current , prev , next = None , None , None ; NEW_LINE current = head ; NEW_LINE prev = None ; NEW_LINE while ( current != None ) : NEW_LINE INDENT next = current . next ; NEW_LINE current . next = prev ; NEW_LINE prev = current ; NEW_LINE current = next ; NEW_LINE DEDENT head = prev ; NEW_LINE DEDENT def sumOfLastN_NodesUtil ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT reverseList ( ) ; NEW_LINE sum = 0 ; NEW_LINE current = head ; NEW_LINE while ( current != None and n > 0 ) : NEW_LINE INDENT sum += current . data ; NEW_LINE current = current . next ; NEW_LINE n -= 1 ; NEW_LINE DEDENT reverseList ( ) ; NEW_LINE return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = push ( head , 12 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 10 ) NEW_LINE n = 2 ; NEW_LINE print ( " Sum β of β last β " , n , " β Nodes β = β " , sumOfLastN_NodesUtil ( n ) ) ; NEW_LINE DEDENT |
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 ; Calculate the length of the linked list ; Count of first ( len - n ) Nodes ; Just traverse the 1 st ' c ' Nodes ; Move to next Node ; Now traverse the last ' n ' Nodes and add them ; Accumulate Node 's data to sum ; Move to next Node ; Required sum ; Driver code ; Create linked list 10 -> 6 -> 8 -> 4 -> 12 | 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_LINE head_ref = new_Node NEW_LINE head = head_ref NEW_LINE return head NEW_LINE DEDENT def sumOfLastN_NodesUtil ( head , n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = 0 NEW_LINE len = 0 NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT len += 1 NEW_LINE temp = temp . next NEW_LINE DEDENT c = len - n NEW_LINE temp = head NEW_LINE while ( temp != None and c > 0 ) : NEW_LINE INDENT temp = temp . next NEW_LINE c -= 1 NEW_LINE DEDENT while ( temp != None ) : NEW_LINE INDENT sum += temp . data NEW_LINE temp = temp . next NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = push ( head , 12 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 10 ) NEW_LINE n = 2 NEW_LINE print ( " Sum β of β last β " , n , " β Nodes β = β " , sumOfLastN_NodesUtil ( head , n ) ) NEW_LINE DEDENT |
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 and LL2 without using any extra space . ; Run till either one of a or b runs out ; For each element of LL1 , compare it with first element of LL2 . ; Swap the two elements involved if LL1 has a greater element ; To keep LL2 sorted , place first element of LL2 at its correct place ; Find mismatch by traversing the second linked list once ; Correct the pointers ; Move LL1 pointer to next element ; Function to print the linked link ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def mergeLists ( a , b ) : NEW_LINE INDENT while ( a and b ) : NEW_LINE INDENT if ( a . data > b . data ) : NEW_LINE INDENT a . data , b . data = b . data , a . data NEW_LINE temp = b NEW_LINE if ( b . next and b . data > b . next . data ) : NEW_LINE INDENT b = b . next NEW_LINE ptr = b NEW_LINE prev = None NEW_LINE while ( ptr and ptr . data < temp . data ) : NEW_LINE INDENT prev = ptr NEW_LINE ptr = ptr . next NEW_LINE DEDENT prev . next = temp NEW_LINE temp . next = ptr NEW_LINE DEDENT DEDENT a = a . next NEW_LINE DEDENT DEDENT def printList ( head ) : NEW_LINE INDENT while ( head ) : NEW_LINE INDENT print ( head . data , end = ' - > ' ) NEW_LINE head = head . next NEW_LINE DEDENT print ( ' NULL ' ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = None NEW_LINE a = push ( a , 10 ) NEW_LINE a = push ( a , 8 ) NEW_LINE a = push ( a , 7 ) NEW_LINE a = push ( a , 4 ) NEW_LINE a = push ( a , 2 ) NEW_LINE b = None NEW_LINE b = push ( b , 12 ) NEW_LINE b = push ( b , 3 ) NEW_LINE b = push ( b , 1 ) NEW_LINE mergeLists ( a , b ) NEW_LINE print ( " First β List : β " , end = ' ' ) NEW_LINE printList ( a ) NEW_LINE print ( " Second β List : β " , end = ' ' ) NEW_LINE printList ( b ) NEW_LINE DEDENT |
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 node . ; Driver Code ; 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 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 DEDENT def deleteMid ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( head . next == None ) : NEW_LINE INDENT del head NEW_LINE return None NEW_LINE DEDENT copyHead = head NEW_LINE count = countOfNodes ( head ) NEW_LINE mid = count // 2 NEW_LINE while ( mid > 1 ) : NEW_LINE INDENT mid -= 1 NEW_LINE head = head . next NEW_LINE DEDENT head . next = head . next . next NEW_LINE return copyHead NEW_LINE DEDENT def printList ( ptr ) : NEW_LINE INDENT while ( ptr != None ) : NEW_LINE INDENT print ( ptr . data , end = ' - > ' ) NEW_LINE ptr = ptr . next NEW_LINE DEDENT print ( ' NULL ' ) NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . data = data NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 1 ) NEW_LINE head . next = newNode ( 2 ) NEW_LINE head . next . next = newNode ( 3 ) NEW_LINE head . next . next . next = newNode ( 4 ) NEW_LINE print ( " Gven β Linked β List " ) NEW_LINE printList ( head ) NEW_LINE head = deleteMid ( head ) NEW_LINE print ( " Linked β List β after β deletion β of β middle " ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
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 first element ; Traverse the first list ; Smaller than next element ; go to next node ; if last node ; Driver code ; Number of linked lists ; Number of elements in each list ; an array of pointers storing the head nodes of the linked lists ; Merge all lists | 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 mergeKLists ( arr , last ) : NEW_LINE INDENT for i in range ( 1 , last + 1 ) : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT head_0 = arr [ 0 ] NEW_LINE head_i = arr [ i ] NEW_LINE if ( head_i == None ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( head_0 . data >= head_i . data ) : NEW_LINE INDENT arr [ i ] = head_i . next NEW_LINE head_i . next = head_0 NEW_LINE arr [ 0 ] = head_i NEW_LINE DEDENT else : NEW_LINE INDENT while ( head_0 . next != None ) : NEW_LINE INDENT if ( head_0 . next . data >= head_i . data ) : NEW_LINE INDENT arr [ i ] = head_i . next NEW_LINE head_i . next = head_0 . next NEW_LINE head_0 . next = head_i NEW_LINE break NEW_LINE DEDENT head_0 = head_0 . next NEW_LINE if ( head_0 . next == None ) : NEW_LINE INDENT arr [ i ] = head_i . next NEW_LINE head_i . next = None NEW_LINE head_0 . next = head_i NEW_LINE head_0 . next . next = None NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return arr [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 3 NEW_LINE n = 4 NEW_LINE arr = [ None for i in range ( k ) ] NEW_LINE arr [ 0 ] = Node ( 1 ) NEW_LINE arr [ 0 ] . next = Node ( 3 ) NEW_LINE arr [ 0 ] . next . next = Node ( 5 ) NEW_LINE arr [ 0 ] . next . next . next = Node ( 7 ) NEW_LINE arr [ 1 ] = Node ( 2 ) NEW_LINE arr [ 1 ] . next = Node ( 4 ) NEW_LINE arr [ 1 ] . next . next = Node ( 6 ) NEW_LINE arr [ 1 ] . next . next . next = Node ( 8 ) NEW_LINE arr [ 2 ] = Node ( 0 ) NEW_LINE arr [ 2 ] . next = Node ( 9 ) NEW_LINE arr [ 2 ] . next . next = Node ( 10 ) NEW_LINE arr [ 2 ] . next . next . next = Node ( 11 ) NEW_LINE head = mergeKLists ( arr , k - 1 ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
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 head data is the least ; Driver Code ; 1.3 . 5 LinkedList created ; 0.2 . 4 LinkedList created | 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 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 merge ( h1 , h2 ) : NEW_LINE INDENT if ( h1 == None ) : NEW_LINE INDENT return h2 NEW_LINE DEDENT if ( h2 == None ) : NEW_LINE INDENT return h1 NEW_LINE DEDENT if ( h1 . data < h2 . data ) : NEW_LINE INDENT h1 . next = merge ( h1 . next , h2 ) NEW_LINE return h1 NEW_LINE DEDENT else : NEW_LINE INDENT h2 . next = merge ( h1 , h2 . next ) NEW_LINE return h2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = newNode ( 1 ) NEW_LINE head1 . next = newNode ( 3 ) NEW_LINE head1 . next . next = newNode ( 5 ) NEW_LINE head2 = newNode ( 0 ) NEW_LINE head2 . next = newNode ( 2 ) NEW_LINE head2 . next . next = newNode ( 4 ) NEW_LINE mergedhead = merge ( head1 , head2 ) NEW_LINE printList ( mergedhead ) NEW_LINE DEDENT |
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 to second list ; Initialize current and next pointers of both lists ; if curr2 lies in between curr1 and next1 then do curr1 . curr2 . next1 ; now let curr1 and curr2 to point to their immediate next pointers ; if more nodes in first list ; else point the last node of first list to the remaining nodes of second list ; Merges two given lists in - place . This function mainly compares head nodes and calls mergeUtil ( ) ; start with the linked list whose head data is the least ; Driver program ; 1.3 . 5 LinkedList created ; 0.2 . 4 LinkedList created | 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 ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = " β " ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT def mergeUtil ( h1 , h2 ) : NEW_LINE INDENT if ( h1 . next == None ) : NEW_LINE INDENT h1 . next = h2 NEW_LINE return h1 NEW_LINE DEDENT curr1 = h1 NEW_LINE next1 = h1 . next NEW_LINE curr2 = h2 NEW_LINE next2 = h2 . next NEW_LINE while ( next1 != None and curr2 != None ) : NEW_LINE INDENT if ( ( curr2 . data ) >= ( curr1 . data ) and ( curr2 . data ) <= ( next1 . data ) ) : NEW_LINE INDENT next2 = curr2 . next NEW_LINE curr1 . next = curr2 NEW_LINE curr2 . next = next1 NEW_LINE curr1 = curr2 NEW_LINE curr2 = next2 NEW_LINE DEDENT else : NEW_LINE INDENT if ( next1 . next ) : NEW_LINE INDENT next1 = next1 . next NEW_LINE curr1 = curr1 . next NEW_LINE DEDENT else : NEW_LINE INDENT next1 . next = curr2 NEW_LINE return h1 NEW_LINE DEDENT DEDENT DEDENT return h1 NEW_LINE DEDENT def merge ( h1 , h2 ) : NEW_LINE INDENT if ( h1 == None ) : NEW_LINE INDENT return h2 NEW_LINE DEDENT if ( h2 == None ) : NEW_LINE INDENT return h1 NEW_LINE DEDENT if ( h1 . data < h2 . data ) : NEW_LINE INDENT return mergeUtil ( h1 , h2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return mergeUtil ( h2 , h1 ) NEW_LINE DEDENT DEDENT head1 = newNode ( 1 ) NEW_LINE head1 . next = newNode ( 3 ) NEW_LINE head1 . next . next = newNode ( 5 ) NEW_LINE head2 = newNode ( 0 ) NEW_LINE head2 . next = newNode ( 2 ) NEW_LINE head2 . next . next = newNode ( 4 ) NEW_LINE mergedhead = merge ( head1 , head2 ) NEW_LINE printList ( mergedhead ) NEW_LINE |
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 ; if there is only a single node ; ' min ' - pointer to store the node having minimum data value ; ' beforeMin ' - pointer to store node previous to ' min ' node ; traverse the list till the last node ; if true , then update ' min ' and 'beforeMin ; if ' min ' and ' head ' are not same , swap the head node with the ' min ' node ; recursively sort the remaining list ; function to sort the given linked list ; if list is empty ; sort the list using recursive selection sort technique ; 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 ; function to print the linked list ; Driver code ; create linked list 10.12 .8 .4 .6 ; sort the linked list | 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 . next NEW_LINE currX . next = temp NEW_LINE return head_ref NEW_LINE DEDENT def recurSelectionSort ( head ) : NEW_LINE INDENT if ( head . next == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT min = head NEW_LINE beforeMin = None NEW_LINE ptr = head NEW_LINE while ( ptr . next != None ) : NEW_LINE INDENT if ( ptr . next . data < min . data ) : NEW_LINE INDENT min = ptr . next NEW_LINE beforeMin = ptr NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT if ( min != head ) : NEW_LINE INDENT head = swapNodes ( head , head , min , beforeMin ) NEW_LINE DEDENT head . next = recurSelectionSort ( head . next ) NEW_LINE return head NEW_LINE DEDENT def sort ( head_ref ) : NEW_LINE INDENT if ( ( head_ref ) == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT head_ref = recurSelectionSort ( head_ref ) NEW_LINE return head_ref NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " β " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT head = None NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 10 ) NEW_LINE print ( " Linked β list β before β sorting : " ) NEW_LINE printList ( head ) NEW_LINE head = sort ( head ) NEW_LINE print ( " Linked list after sorting : " ) NEW_LINE printList ( head ) NEW_LINE |
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 to the nth node from the end ; insert the ' newNode ' by making the necessary adjustment in the links ; function to print the list ; Creating list 1 -> 3 -> 4 -> 5 | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT 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 insertAfterNthNode ( head , n , x ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT newNode = getNode ( x ) NEW_LINE ptr = head NEW_LINE len = 0 NEW_LINE i = 0 NEW_LINE while ( ptr != None ) : NEW_LINE INDENT len = len + 1 NEW_LINE ptr = ptr . next NEW_LINE DEDENT ptr = head NEW_LINE i = 1 NEW_LINE while ( i <= ( len - n ) ) : NEW_LINE INDENT ptr = ptr . next NEW_LINE i = i + 1 NEW_LINE DEDENT newNode . next = ptr . next NEW_LINE ptr . next = newNode NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " β " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT head = getNode ( 1 ) NEW_LINE head . next = getNode ( 3 ) NEW_LINE head . next . next = getNode ( 4 ) NEW_LINE head . next . next . next = getNode ( 5 ) NEW_LINE n = 4 NEW_LINE x = 2 NEW_LINE print ( " Original β Linked β List : β " ) NEW_LINE printList ( head ) NEW_LINE insertAfterNthNode ( head , n , x ) NEW_LINE print ( ) NEW_LINE print ( " Linked β List β After β Insertion : β " ) NEW_LINE printList ( head ) NEW_LINE |
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 beginning ; Iterate until ' fast _ ptr ' points to the last node ; Move both the pointers to the respective next nodes ; Insert the ' newNode ' by making the necessary adjustment in the links ; Function to print the list ; Driver code ; Creating list 1.3 . 4.5 | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT 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 == None ) : NEW_LINE INDENT return NEW_LINE DEDENT newNode = getNode ( x ) NEW_LINE slow_ptr = head NEW_LINE fast_ptr = head NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT fast_ptr = fast_ptr . next NEW_LINE DEDENT while ( fast_ptr . next != None ) : NEW_LINE INDENT slow_ptr = slow_ptr . next NEW_LINE fast_ptr = fast_ptr . next NEW_LINE DEDENT newNode . next = slow_ptr . next NEW_LINE slow_ptr . next = newNode NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = ' β ' ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = getNode ( 1 ) NEW_LINE head . next = getNode ( 3 ) NEW_LINE head . next . next = getNode ( 4 ) NEW_LINE head . next . next . next = getNode ( 5 ) NEW_LINE n = 4 NEW_LINE x = 2 NEW_LINE print ( " Original β Linked β List : β " , end = ' ' ) NEW_LINE printList ( head ) NEW_LINE insertAfterNthNode ( head , n , x ) NEW_LINE print ( " Linked List After Insertion : " , end = ' ' ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
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 time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate new node ; link the old list to new node ; move the head to point the new node ; A function to print a given linked list ; Create a list of 5 nodes | 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 NEW_LINE while ( two_node != None and two_node . next != None ) : NEW_LINE INDENT prev = one_node NEW_LINE one_node = one_node . next NEW_LINE two_node = two_node . next . next NEW_LINE DEDENT prev . next = prev . next . next NEW_LINE one_node . next = head NEW_LINE head = one_node NEW_LINE return head NEW_LINE DEDENT def push ( head , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head NEW_LINE head = new_node NEW_LINE return head NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( str ( temp . data ) , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT head = None NEW_LINE for i in range ( 5 , 0 , - 1 ) : NEW_LINE INDENT head = push ( head , i ) NEW_LINE DEDENT print ( " β list β before : β " , end = " " ) NEW_LINE printList ( head ) NEW_LINE head = setMiddleHead ( head ) NEW_LINE print ( " β list β After : β " , end = " " ) NEW_LINE printList ( head ) NEW_LINE |
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 as previous of new_node ; 7. Change previous of new_node 's next 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 new_node . prev = prev_node NEW_LINE if new_node . next is not None : NEW_LINE INDENT new_node . next . prev = new_node NEW_LINE DEDENT DEDENT |
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 ; setting up previous and next of new node ; update next and previous pointers of head_ref and last . ; update head_ref pointer ; function for Sorted merge of two sorted doubly linked list ; If first list is empty ; If second list is empty ; Pick the smaller value and adjust the links ; function for Sorted merge of two sorted doubly circular linked list ; if 1 st list is empty ; if 2 nd list is empty ; get pointer to the node which will be the last node of the final list last_node ; store None to the ' next ' link of the last nodes of the two lists ; sorted merge of head1 and head2 ; ' prev ' of 1 st node pointing the last node ' next ' of last node pointing to 1 st node ; function to print the list ; Driver Code ; list 1 : ; list 2 : | 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_ref == None ) : NEW_LINE INDENT new_node . next = new_node NEW_LINE new_node . prev = new_node NEW_LINE DEDENT else : NEW_LINE INDENT last = head_ref . prev NEW_LINE new_node . next = head_ref NEW_LINE new_node . prev = last NEW_LINE last . next = new_node NEW_LINE head_ref . prev = new_node NEW_LINE DEDENT head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def merge ( first , second ) : NEW_LINE INDENT if ( first == None ) : NEW_LINE INDENT return second NEW_LINE DEDENT if ( second == None ) : NEW_LINE INDENT return first NEW_LINE DEDENT if ( first . data < second . data ) : NEW_LINE INDENT first . next = merge ( first . next , second ) NEW_LINE first . next . prev = first NEW_LINE first . prev = None NEW_LINE return first NEW_LINE DEDENT else : NEW_LINE INDENT second . next = merge ( first , second . next ) NEW_LINE second . next . prev = second NEW_LINE second . prev = None NEW_LINE return second NEW_LINE DEDENT DEDENT def mergeUtil ( head1 , head2 ) : NEW_LINE INDENT if ( head1 == None ) : NEW_LINE INDENT return head2 NEW_LINE DEDENT if ( head2 == None ) : NEW_LINE INDENT return head1 NEW_LINE DEDENT if ( head1 . prev . data < head2 . prev . data ) : NEW_LINE INDENT last_node = head2 . prev NEW_LINE DEDENT else : NEW_LINE INDENT last_node = head1 . prev NEW_LINE DEDENT head1 . prev . next = None NEW_LINE head2 . prev . next = None NEW_LINE finalHead = merge ( head1 , head2 ) NEW_LINE finalHead . prev = last_node NEW_LINE last_node . next = finalHead NEW_LINE return finalHead NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp . next != head ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( temp . data , end = " β " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = None NEW_LINE head2 = None NEW_LINE head1 = insert ( head1 , 8 ) NEW_LINE head1 = insert ( head1 , 5 ) NEW_LINE head1 = insert ( head1 , 3 ) NEW_LINE head1 = insert ( head1 , 1 ) NEW_LINE head2 = insert ( head2 , 11 ) NEW_LINE head2 = insert ( head2 , 9 ) NEW_LINE head2 = insert ( head2 , 7 ) NEW_LINE head2 = insert ( head2 , 2 ) NEW_LINE newHead = mergeUtil ( head1 , head2 ) NEW_LINE print ( " Final β Sorted β List : β " , end = " " ) NEW_LINE printList ( newHead ) NEW_LINE DEDENT |
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 they meet or cross each other ; Swap data of left and right pointer ; Advance left pointer ; Advance right pointer ; Driver code | 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 return temp NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head . next != None ) : NEW_LINE INDENT print ( head . data , end = " < - - > " ) NEW_LINE head = head . next NEW_LINE DEDENT print ( head . data ) NEW_LINE DEDENT def insert ( head , val ) : NEW_LINE INDENT temp = newNode ( val ) NEW_LINE temp . next = head NEW_LINE ( head ) . prev = temp NEW_LINE ( head ) = temp NEW_LINE return head NEW_LINE DEDENT def reverseList ( head ) : NEW_LINE INDENT left = head NEW_LINE right = head NEW_LINE while ( right . next != None ) : NEW_LINE INDENT right = right . next NEW_LINE DEDENT while ( left != right and left . prev != right ) : NEW_LINE INDENT t = left . data NEW_LINE left . data = right . data NEW_LINE right . data = t NEW_LINE left = left . next NEW_LINE right = right . prev NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 5 ) NEW_LINE head = insert ( head , 4 ) NEW_LINE head = insert ( head , 3 ) NEW_LINE head = insert ( head , 2 ) NEW_LINE head = insert ( head , 1 ) NEW_LINE printList ( head ) NEW_LINE print ( " List β After β Reversing " ) NEW_LINE head = reverseList ( head ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
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_LINE INDENT head_ref . prev = new_node NEW_LINE head_ref = new_node NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def isPalindrome ( left ) : NEW_LINE INDENT if left == None : NEW_LINE INDENT return True NEW_LINE DEDENT right = left NEW_LINE while right . next != None : NEW_LINE INDENT right = right . next NEW_LINE DEDENT while left != right : NEW_LINE INDENT if left . data != right . data : NEW_LINE INDENT return False NEW_LINE DEDENT left = left . next NEW_LINE right = right . prev NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT head = None NEW_LINE head = push ( head , ' l ' ) NEW_LINE head = push ( head , ' e ' ) NEW_LINE head = push ( head , ' v ' ) NEW_LINE head = push ( head , ' e ' ) NEW_LINE head = push ( head , ' l ' ) NEW_LINE if isPalindrome ( head ) : NEW_LINE INDENT print ( " It β is β Palindrome " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Palindrome " ) NEW_LINE DEDENT DEDENT |
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 level order traversal loop ; Remove the front item from queue ; print Q Check if end of level is reached ; print a new line and increment level number ; Check if marker node was last node in queue or level nubmer is beyond the given upper limit ; Enqueue the marker for end of next level ; If this is marker , then we don 't need print it and enqueue its children ; If level is equal to or greater than given lower level , print it ; Enqueue children of non - marker node ; Driver program to test the above function | 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_LINE Q . append ( marker ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT n = Q [ 0 ] NEW_LINE Q . pop ( 0 ) NEW_LINE if n == marker : NEW_LINE INDENT print NEW_LINE level += 1 NEW_LINE if len ( Q ) == 0 or level > high : NEW_LINE INDENT break NEW_LINE DEDENT Q . append ( marker ) NEW_LINE continue NEW_LINE DEDENT if level >= low : NEW_LINE INDENT print n . key , NEW_LINE DEDENT if n . left is not None : NEW_LINE INDENT Q . append ( n . left ) NEW_LINE Q . append ( n . right ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE print " Level β Order β Traversal β between β given β two β levels β is " , NEW_LINE printLevels ( root , 2 , 3 ) NEW_LINE |
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 . data , NEW_LINE DEDENT else : NEW_LINE INDENT printKDistant ( root . left , k - 1 ) NEW_LINE printKDistant ( root . right , k - 1 ) NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 8 ) NEW_LINE printKDistant ( root , 2 ) NEW_LINE |
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 number ; Driver Code ; create a binary tree | 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 ( None ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE if ( level == klevel and temp != None ) : NEW_LINE INDENT flag = True NEW_LINE print ( temp . data , end = " β " ) NEW_LINE DEDENT q . pop ( 0 ) NEW_LINE if ( temp == None ) : NEW_LINE INDENT if ( len ( q ) ) : NEW_LINE INDENT q . append ( None ) NEW_LINE DEDENT level += 1 NEW_LINE if ( level > klevel ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( temp . left ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT print ( ) NEW_LINE return flag NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 20 ) NEW_LINE root . left = newNode ( 10 ) NEW_LINE root . right = newNode ( 30 ) NEW_LINE root . left . left = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 15 ) NEW_LINE root . left . right . left = newNode ( 12 ) NEW_LINE root . right . left = newNode ( 25 ) NEW_LINE root . right . right = newNode ( 40 ) NEW_LINE print ( " data β at β level β 1 β : β " , end = " " ) NEW_LINE ret = printKDistant ( root , 1 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number β exceeds β total " , " number β of β levels " ) NEW_LINE DEDENT print ( " data β at β level β 2 β : β " , end = " " ) NEW_LINE ret = printKDistant ( root , 2 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number β exceeds β total " , " number β of β levels " ) NEW_LINE DEDENT print ( " data β at β level β 3 β : β " , end = " " ) NEW_LINE ret = printKDistant ( root , 3 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number β exceeds β total " , " number β of β levels " ) NEW_LINE DEDENT print ( " data β at β level β 6 β : β " , end = " " ) NEW_LINE ret = printKDistant ( root , 6 ) NEW_LINE if ( ret == False ) : NEW_LINE INDENT print ( " Number β exceeds β total β number β of β levels " ) NEW_LINE DEDENT DEDENT |
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 create binary tree shown in above diagram ; print leaf nodes of the given tree | 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 not root . right ) : NEW_LINE INDENT print ( root . data , end = " β " ) NEW_LINE return NEW_LINE DEDENT if root . left : NEW_LINE INDENT printLeafNodes ( root . left ) NEW_LINE DEDENT if root . right : NEW_LINE INDENT printLeafNodes ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . right . left = Node ( 5 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . left . left = Node ( 6 ) NEW_LINE root . right . left . right = Node ( 7 ) NEW_LINE root . right . right . left = Node ( 9 ) NEW_LINE root . right . right . right = Node ( 10 ) NEW_LINE printLeafNodes ( root ) NEW_LINE DEDENT |
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 target node The k distant nodes may be upward or downward . This function returns distance of root from target node , it returns - 1 if target node is not present in tree rooted with root ; Base Case 1 : IF tree is empty return - 1 ; If target is same as root . Use the downward function to print all nodes at distance k in subtree rooted with target or root ; Recur for left subtree ; Check if target node was found in left subtree ; If root is at distance k from target , print root Note : dl is distance of root 's left child from target ; Else go to right subtreee and print all k - dl - 2 distant nodes Note : that the right child is 2 edges away from left chlid ; Add 1 to the distance and return value for for parent calls ; MIRROR OF ABOVE CODE FOR RIGHT SUBTREE Note that we reach here only when node was not found in left subtree ; If target was neither present in left nor in right subtree ; Let us construct the tree shown in above diagram | 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 INDENT print root . data NEW_LINE return NEW_LINE DEDENT printkDistanceNodeDown ( root . left , k - 1 ) NEW_LINE printkDistanceNodeDown ( root . right , k - 1 ) NEW_LINE DEDENT def printkDistanceNode ( root , target , k ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if root == target : NEW_LINE INDENT printkDistanceNodeDown ( root , k ) NEW_LINE return 0 NEW_LINE DEDENT dl = printkDistanceNode ( root . left , target , k ) NEW_LINE if dl != - 1 : NEW_LINE INDENT if dl + 1 == k : NEW_LINE INDENT print root . data NEW_LINE DEDENT else : NEW_LINE INDENT printkDistanceNodeDown ( root . right , k - dl - 2 ) NEW_LINE DEDENT return 1 + dl NEW_LINE DEDENT dr = printkDistanceNode ( root . right , target , k ) NEW_LINE if dr != - 1 : NEW_LINE INDENT if ( dr + 1 == k ) : NEW_LINE INDENT print root . data NEW_LINE DEDENT else : NEW_LINE INDENT printkDistanceNodeDown ( root . left , k - dr - 2 ) NEW_LINE DEDENT return 1 + dr NEW_LINE DEDENT return - 1 NEW_LINE DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE target = root . left . right NEW_LINE printkDistanceNode ( root , target , 2 ) 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 NULL and left is not , print left child and recur for left child ; Let us create binary tree given in the above example | 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 not None : NEW_LINE INDENT printSingles ( root . left ) NEW_LINE printSingles ( root . right ) NEW_LINE DEDENT elif root . right is not None : NEW_LINE INDENT print root . right . key , NEW_LINE printSingles ( root . right ) NEW_LINE DEDENT elif root . left is not None : NEW_LINE INDENT print root . left . key , NEW_LINE printSingles ( root . left ) NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . right = Node ( 4 ) NEW_LINE root . right . left = Node ( 5 ) NEW_LINE root . right . left . left = Node ( 6 ) NEW_LINE printSingles ( root ) NEW_LINE |
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 leaves , we want to print it once ; Base case ; append this Node to the path array ; it 's a leaf, so print the ancestor at distance k only if the ancestor is not already printed ; If not leaf node , recur for left and right subtrees ; Given a binary tree and a nuber k , print all nodes that are k distant from a leaf ; Driver Code ; Let us create binary tree given in the above example | 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 ] = node . key NEW_LINE visited [ pathLen ] = False NEW_LINE pathLen += 1 NEW_LINE if ( node . left == None and node . right == None and pathLen - k - 1 >= 0 and visited [ pathLen - k - 1 ] == False ) : NEW_LINE INDENT print ( path [ pathLen - k - 1 ] , end = " β " ) NEW_LINE visited [ pathLen - k - 1 ] = True NEW_LINE return NEW_LINE DEDENT kDistantFromLeafUtil ( node . left , path , visited , pathLen , k ) NEW_LINE kDistantFromLeafUtil ( node . right , path , visited , pathLen , k ) NEW_LINE DEDENT def printKDistantfromLeaf ( node , k ) : NEW_LINE INDENT global MAX_HEIGHT NEW_LINE path = [ None ] * MAX_HEIGHT NEW_LINE visited = [ False ] * MAX_HEIGHT NEW_LINE kDistantFromLeafUtil ( node , path , visited , 0 , k ) NEW_LINE DEDENT MAX_HEIGHT = 10000 NEW_LINE root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . left . right = newNode ( 8 ) NEW_LINE print ( " Nodes β at β distance β 2 β are : " , end = " β " ) NEW_LINE printKDistantfromLeaf ( root , 2 ) NEW_LINE |
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 track of levels ; pushing root node and star node ; Do level order traversal using a single queue ; n denotes the size of the current level in the queue ; If it is leftmost corner value or rightmost corner value then print it ; push the left and right children of the temp node ; Driver Code | 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 = deque ( ) NEW_LINE q . append ( root ) NEW_LINE while q : NEW_LINE INDENT n = len ( q ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . popleft ( ) NEW_LINE if i == 0 or i == n - 1 : NEW_LINE INDENT print ( temp . key , end = " β " ) NEW_LINE DEDENT if temp . left : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 15 ) NEW_LINE root . left = Node ( 10 ) NEW_LINE root . right = Node ( 20 ) NEW_LINE root . left . left = Node ( 8 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . right . left = Node ( 16 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE printCorner ( root ) NEW_LINE DEDENT |
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 child first ; Print current node after space count ; Process left child ; Wrapper over print2DUtil ( ) ; space = [ 0 ] Pass initial space count as 0 ; Driver Code | 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 += COUNT [ 0 ] NEW_LINE print2DUtil ( root . right , space ) NEW_LINE print ( ) NEW_LINE for i in range ( COUNT [ 0 ] , space ) : NEW_LINE INDENT print ( end = " β " ) NEW_LINE DEDENT print ( root . data ) NEW_LINE print2DUtil ( root . left , space ) NEW_LINE DEDENT def print2D ( root ) : NEW_LINE INDENT print2DUtil ( root , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . left . left . left = newNode ( 8 ) NEW_LINE root . left . left . right = newNode ( 9 ) NEW_LINE root . left . right . left = newNode ( 10 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . left . left = newNode ( 12 ) NEW_LINE root . right . left . right = newNode ( 13 ) NEW_LINE root . right . right . left = newNode ( 14 ) NEW_LINE root . right . right . right = newNode ( 15 ) NEW_LINE print2D ( root ) NEW_LINE DEDENT |
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 ] < level ) : NEW_LINE INDENT print " % β d TABSYMBOL " % ( root . data ) , NEW_LINE max_level [ 0 ] = level NEW_LINE DEDENT leftViewUtil ( root . left , level + 1 , max_level ) NEW_LINE leftViewUtil ( root . right , level + 1 , max_level ) NEW_LINE DEDENT def leftView ( root ) : NEW_LINE INDENT max_level = [ 0 ] NEW_LINE leftViewUtil ( root , 1 , max_level ) NEW_LINE DEDENT root = Node ( 12 ) NEW_LINE root . left = Node ( 10 ) NEW_LINE root . right = Node ( 20 ) NEW_LINE root . right . left = Node ( 25 ) NEW_LINE root . right . right = Node ( 40 ) NEW_LINE leftView ( root ) NEW_LINE |
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 binary tree as shown in above diagram | 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 . append ( root ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT n = len ( q ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( i == 1 ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE DEDENT if ( temp . left != None ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 7 ) NEW_LINE root . left . right = newNode ( 8 ) NEW_LINE root . right . right = newNode ( 15 ) NEW_LINE root . right . left = newNode ( 12 ) NEW_LINE root . right . right . left = newNode ( 14 ) NEW_LINE printRightView ( root ) NEW_LINE DEDENT |
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 final value ; Driver Code | 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 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE X = 1 NEW_LINE N = len ( arr ) NEW_LINE print ( rotate ( arr , N , X ) ) NEW_LINE |
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 characters of the string ; If the frequency of '1' is 0 ; Print n as the result ; Concatenate the string with itself ; Stores the required result ; Generate all rotations of the string ; Store the number of consecutive 0 s at the start and end of the string ; Count 0 s present at the start ; Count 0 s present at the end ; Calculate the sum ; Update the overall maximum sum ; Print the result ; Driver Code ; Given string ; Store the size of the string | 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_LINE INDENT cs = 0 NEW_LINE ce = 0 NEW_LINE for j in range ( i , i + n ) : NEW_LINE INDENT if ( s [ j ] == '0' ) : NEW_LINE INDENT cs += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for j in range ( i + n - 1 , i - 1 , - 1 ) : NEW_LINE INDENT if ( s [ j ] == '0' ) : NEW_LINE INDENT ce += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT val = cs + ce NEW_LINE mx = max ( val , mx ) NEW_LINE DEDENT print ( mx ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "1001" NEW_LINE n = len ( s ) NEW_LINE findMaximumZeros ( s , n ) NEW_LINE DEDENT |
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 sum ; Find the maximum consecutive length of 0 s present in the string ; Update the overall maximum sum ; Find the number of 0 s present at the start and end of the string ; Update the count of 0 s at the start ; Update the count of 0 s at the end ; Update the maximum sum ; Print the result ; Driver Code ; Given string ; Store the size of the string | 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 range ( n ) : NEW_LINE INDENT if ( string [ i ] == '0' ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mx = max ( mx , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT mx = max ( mx , cnt ) NEW_LINE start = 0 NEW_LINE end = n - 1 NEW_LINE cnt = 0 NEW_LINE while ( string [ start ] != '1' and start < n ) : NEW_LINE INDENT cnt += 1 NEW_LINE start += 1 NEW_LINE DEDENT while ( string [ end ] != '1' and end >= 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE end -= 1 NEW_LINE DEDENT mx = max ( mx , cnt ) NEW_LINE print ( mx , end = " " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "1001" NEW_LINE n = len ( s ) NEW_LINE findMaximumZeros ( s , n ) NEW_LINE DEDENT |
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 : NEW_LINE INDENT for cols in rows : NEW_LINE INDENT print ( cols , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE rotateMatrix ( mat ) NEW_LINE DEDENT |
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 ; Size of the array ; Function call to check if it is possible to make array non - decreasing by rotating | 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 ( arr == v ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " NO " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 5 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE rotateArray ( arr , N ) NEW_LINE DEDENT |
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 current rotation is greater than the overall answer , then update answer ; Print the result ; Driver Code | 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 = num NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT N = 657 NEW_LINE findLargestRotation ( N ) NEW_LINE |
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 digits of N ; Remove first K digits of N ; Stores count of digits in left_no ; Append left_no to the right of digits of N ; Driver Code ; Function Call | 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 ) NEW_LINE N = N % pow ( 10 , X - K ) NEW_LINE left_digit = numberOfDigit ( left_no ) NEW_LINE N = N * pow ( 10 , left_digit ) + left_no NEW_LINE print ( N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K = 12345 , 7 NEW_LINE rotateNumberByK ( N , K ) NEW_LINE DEDENT |
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 increasing order ; Increment count ; Update index ; Prthe result according to the following conditions ; Otherwise , it is not possible to sort the array ; Given array ; Function Call | 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 - 1 ) : NEW_LINE INDENT print ( N - 1 ) NEW_LINE DEDENT elif ( count == 1 and arr [ 0 ] <= arr [ N - 1 ] ) : NEW_LINE INDENT print ( index + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT arr = [ 2 , 1 , 5 , 4 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minMovesToSort ( arr , N ) NEW_LINE |
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 columns by an integer in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Rotate all the rows by an integer in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Driver code | 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 ( maxDiagonalSum , curr ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT curr = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT curr += A [ ( i + j ) % N ] [ j ] NEW_LINE DEDENT maxDiagonalSum = max ( maxDiagonalSum , curr ) NEW_LINE DEDENT return maxDiagonalSum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 1 , 2 ] , [ 2 , 1 , 2 ] , [ 1 , 2 , 2 ] ] NEW_LINE print ( findMaximumDiagonalSumOMatrixf ( mat ) ) NEW_LINE DEDENT |
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 ; Base Case ; Recursively find the GCD ; Function to rotate the array by Y ; For handling k >= N ; Dividing the array into number of sets ; Rotate the array by Y ; Update arr [ j ] ; Return the rotated array ; Function that performs the queries on the given array ; Traverse each query ; If query of type X = 1 ; Print the array ; If query of type X = 2 ; Driver Code ; Given array arr [ ] ; Given Queries ; Function call | 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 = sum NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return max_sum NEW_LINE DEDENT def gcd ( n1 , n2 ) : NEW_LINE INDENT if ( n2 == 0 ) : NEW_LINE INDENT return n1 NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( n2 , n1 % n2 ) NEW_LINE DEDENT DEDENT def RotateArr ( arr , n , d ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE d = d % n NEW_LINE no_of_sets = gcd ( d , n ) NEW_LINE for i in range ( no_of_sets ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE j = i NEW_LINE while ( True ) : NEW_LINE INDENT k = j + d NEW_LINE if ( k >= n ) : NEW_LINE INDENT k = k - n NEW_LINE DEDENT if ( k == i ) : NEW_LINE INDENT break NEW_LINE DEDENT arr [ j ] = arr [ k ] NEW_LINE j = k NEW_LINE DEDENT arr [ j ] = temp NEW_LINE DEDENT return arr NEW_LINE DEDENT def performQuery ( arr , Q , q ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT arr = RotateArr ( arr , N , Q [ i ] [ 1 ] ) NEW_LINE for t in arr : NEW_LINE INDENT print ( t , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( MaxSum ( arr , N , Q [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE q = 5 NEW_LINE Q = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] , [ 1 , 1 ] , [ 2 , 4 ] ] NEW_LINE performQuery ( arr , Q , q ) NEW_LINE DEDENT |
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 the most occuring frequency for even and odd indices ; Update the answer ; If length is odd ; Stores the frequency of the characters of the string ; Stores the most occuring characterin the string ; Update the answer ; Driver Code | 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 DEDENT for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT if str [ i ] in freqEven : NEW_LINE INDENT freqEven [ str [ i ] ] += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if str [ i ] in freqOdd : NEW_LINE INDENT freqOdd [ str [ i ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT evenMax = 0 NEW_LINE oddMax = 0 NEW_LINE for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT evenMax = max ( evenMax , freqEven [ chr ( ch ) ] ) NEW_LINE oddMax = max ( oddMax , freqOdd [ chr ( ch ) ] ) NEW_LINE DEDENT ans = ans - evenMax - oddMax NEW_LINE DEDENT else : NEW_LINE INDENT freq = { } NEW_LINE for ch in range ( ' a ' , ' z ' ) : NEW_LINE INDENT freq [ chr ( ch ) ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if str [ i ] in freq : NEW_LINE INDENT freq [ str [ i ] ] += 1 NEW_LINE DEDENT DEDENT strMax = 0 NEW_LINE for ch in range ( ' a ' , ' z ' ) : NEW_LINE INDENT strMax = max ( strMax , freq [ chr ( ch ) ] ) NEW_LINE DEDENT ans = ans - strMax NEW_LINE DEDENT return ans NEW_LINE DEDENT str = " geeksgeeks " NEW_LINE print ( getMinimumRemoval ( str ) ) NEW_LINE |
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 of current combination ; Increment the current value ; Increment the current value ; If alternating sequence is obtained of odd length ; Reduce to even length ; Update answer to store the maximum ; Return the answer ; Driver code | 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 ) : NEW_LINE INDENT f = 1 NEW_LINE cur += 1 NEW_LINE DEDENT elif ( f == 1 and ord ( s [ k ] ) - ord ( '0' ) == j ) : NEW_LINE INDENT f = 0 NEW_LINE cur += 1 NEW_LINE DEDENT DEDENT if i != j and cur % 2 == 1 : NEW_LINE INDENT cur -= 1 NEW_LINE DEDENT ans = max ( cur , ans ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT s = "100210601" NEW_LINE print ( findAltSubSeq ( s ) ) NEW_LINE |
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 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT lst . reverse ( ) NEW_LINE print ( * lst ) NEW_LINE ctr += 1 NEW_LINE DEDENT DEDENT n = 8 NEW_LINE m = n NEW_LINE li = [ [ 4 , 5 , 6 , 9 , 8 , 7 , 1 , 4 ] , [ 1 , 5 , 9 , 7 , 5 , 3 , 1 , 6 ] , [ 7 , 5 , 3 , 1 , 5 , 9 , 8 , 0 ] , [ 6 , 5 , 4 , 7 , 8 , 9 , 3 , 7 ] , [ 3 , 5 , 6 , 4 , 8 , 9 , 2 , 1 ] , [ 3 , 1 , 6 , 4 , 7 , 9 , 5 , 0 ] , [ 8 , 0 , 7 , 2 , 3 , 1 , 0 , 8 ] , [ 7 , 5 , 3 , 1 , 5 , 9 , 8 , 5 ] ] NEW_LINE matrix ( n , m , li ) NEW_LINE |
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 element of the array ; Return the result ; Driver Code | 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 a = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( a ) NEW_LINE K , M = 3 , 2 NEW_LINE print ( getFirstElement ( a , N , K , M ) ) NEW_LINE DEDENT |
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 initialization ; Size of the array ; Given K rotation and Mth element to be found after K rotation ; Function call | 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 ( getFirstElement ( a , N , K , M ) ) NEW_LINE DEDENT |
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 ( arr ) - 4 , - 1 , - 2 ) : NEW_LINE INDENT arr [ i + 2 ] = arr [ i ] NEW_LINE DEDENT arr [ 0 ] = start NEW_LINE DEDENT def rotate ( arr ) : NEW_LINE INDENT left_rotate ( arr ) NEW_LINE right_rotate ( arr ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE rotate ( arr ) ; NEW_LINE |
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 element from right side ; Map to store index of elements ; idx1 is index of element in first permutation idx2 is index of element in second permutation ; If element if present on same index on both permutations then distance is zero ; Calculate distance from left and right side ; Calculate distance from left and right side ; Maps to store frequencies of elements present in left and right arrays ; Find maximum frequency ; Return the result ; Driver Code ; Given permutations P1 and P2 ; Function Call | 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 mp2 [ perm2 [ j ] ] = j NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT idx2 = mp2 [ perm1 [ i ] ] NEW_LINE idx1 = i NEW_LINE if ( idx1 == idx2 ) : NEW_LINE INDENT left [ i ] = 0 NEW_LINE right [ i ] = 0 NEW_LINE DEDENT elif ( idx1 < idx2 ) : NEW_LINE INDENT left [ i ] = ( n - ( idx2 - idx1 ) ) NEW_LINE right [ i ] = ( idx2 - idx1 ) NEW_LINE DEDENT else : NEW_LINE INDENT left [ i ] = ( idx1 - idx2 ) NEW_LINE right [ i ] = ( n - ( idx1 - idx2 ) ) NEW_LINE DEDENT DEDENT freq1 = defaultdict ( int ) NEW_LINE freq2 = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq1 [ left [ i ] ] += 1 NEW_LINE freq2 [ right [ i ] ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , max ( freq1 [ left [ i ] ] , freq2 [ right [ i ] ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT P1 = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE P2 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( P1 ) NEW_LINE print ( maximumMatchingPairs ( P1 , P2 , n ) ) NEW_LINE DEDENT |
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 ( countRotation ( arr1 , n ) ) NEW_LINE DEDENT |
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 ; Check if current element is greater than lower bound ; The sequence is increasing so far Search for smallest element on the right subarray ; Smallest element lies on the left subarray ; Search for the smallest element on both subarrays ; Driver code | 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_LINE INDENT return mid NEW_LINE DEDENT if ( arr [ mid ] > arr [ low ] ) : NEW_LINE INDENT return countRotation ( arr , mid + 1 , high ) NEW_LINE DEDENT if ( arr [ mid ] < arr [ high ] ) : NEW_LINE INDENT return countRotation ( arr , low , mid - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT rightIndex = countRotation ( arr , mid + 1 , high ) NEW_LINE leftIndex = countRotation ( arr , low , mid - 1 ) NEW_LINE if ( rightIndex == 0 ) : NEW_LINE INDENT return leftIndex NEW_LINE DEDENT return rightIndex NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 4 , 5 , 1 , 2 , 3 ] NEW_LINE N = len ( arr1 ) NEW_LINE print ( countRotation ( arr1 , 0 , N - 1 ) ) NEW_LINE DEDENT |
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 ; Query to answer range sum ; If pointing to 1 st index ; Display the sum upto start + R ; Subtract sum upto start + L - 1 from sum upto start + R ; Driver code ; Number of query ; Store all the queries | 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 = 0 ; NEW_LINE for q in range ( Q ) : NEW_LINE INDENT if ( query [ q ] [ 0 ] == 1 ) : NEW_LINE INDENT k = query [ q ] [ 1 ] NEW_LINE start = ( start + k ) % n ; NEW_LINE DEDENT elif ( query [ q ] [ 0 ] == 2 ) : NEW_LINE INDENT L = query [ q ] [ 1 ] NEW_LINE R = query [ q ] [ 2 ] NEW_LINE if ( start + L == 0 ) : NEW_LINE INDENT print ( prefix [ start + R ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( prefix [ start + R ] - prefix [ start + L - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; NEW_LINE Q = 5 NEW_LINE query = [ [ 2 , 1 , 3 ] , [ 1 , 3 ] , [ 2 , 0 , 3 ] , [ 1 , 4 ] , [ 2 , 3 , 5 ] ] NEW_LINE n = len ( arr ) ; NEW_LINE rotatedSumQuery ( arr , n , query , Q ) ; NEW_LINE |
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 less than X or not ; If both characters are the same ; Condition to check if the difference less than 0 then find the circular shift by adding 26 to it ; If difference between their ASCII values exceeds X ; Driver Code ; Function Call | 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 = diff + 26 NEW_LINE DEDENT if diff > x : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " you " NEW_LINE s2 = " ara " NEW_LINE x = 6 NEW_LINE result = isConversionPossible ( s1 , s2 , x ) NEW_LINE if result : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
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 ; NEW_LINE print ( countRotation ( n ) ) ; NEW_LINE DEDENT |
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 updated head pointer ; If the linked list is empty ; len is used to store length of the linked list tmp will point to the last node after this loop ; If k is greater than the size of the linked list ; Subtract from length to convert it into left rotation ; If no rotation needed then return the head node ; current will either point to kth or None after this loop ; If current is None then k is equal to the count of nodes in the list Don 't change the list in this case ; current points to the kth node ; Change next of last node to previous head ; Change head to ( k + 1 ) th node ; Change next of kth node to None ; Return the updated head pointer ; Driver code ; The constructed linked list is : 1.2 . 3.4 . 5 ; Rotate the linked list ; Print the rotated linked list | 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_ref ) = new_node NEW_LINE return head_ref NEW_LINE 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 print ( " NULL " ) NEW_LINE DEDENT def rightRotate ( head , k ) : NEW_LINE INDENT if ( not head ) : NEW_LINE INDENT return head NEW_LINE DEDENT tmp = head NEW_LINE len = 1 NEW_LINE while ( tmp . next != None ) : NEW_LINE INDENT tmp = tmp . next NEW_LINE len += 1 NEW_LINE DEDENT if ( k > len ) : NEW_LINE INDENT k = k % len NEW_LINE DEDENT k = len - k NEW_LINE if ( k == 0 or k == len ) : NEW_LINE INDENT return head NEW_LINE DEDENT current = head NEW_LINE cnt = 1 NEW_LINE while ( cnt < k and current != None ) : NEW_LINE INDENT current = current . next NEW_LINE cnt += 1 NEW_LINE DEDENT if ( current == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT kthnode = current NEW_LINE tmp . next = head NEW_LINE head = kthnode . next NEW_LINE kthnode . next = None NEW_LINE return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE k = 2 NEW_LINE updated_head = rightRotate ( head , k ) NEW_LINE printList ( updated_head ) NEW_LINE DEDENT |
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 ; If the array is already decreasing ; Check if the array is already increasing ; If the array is already increasing ; Find the indices of the minimum and the maximum value ; Check if we can make array increasing ; If the array is increasing upto max index and minimum element is right to maximum ; Check if array increasing again or not ; Check if we can make array decreasing ; If the array is decreasing upto min index and minimum element is left to maximum ; Check if array decreasing again or not ; If it is not possible to make the array increasing or decreasing ; Driver code | 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 DEDENT if ( flag == 0 ) : 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 DEDENT if ( flag == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT val1 = sys . maxsize ; mini = - 1 ; NEW_LINE val2 = - sys . maxsize ; maxi = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] < val1 ) : NEW_LINE INDENT mini = i ; NEW_LINE val1 = a [ i ] ; NEW_LINE DEDENT if ( a [ i ] > val2 ) : NEW_LINE INDENT maxi = i ; NEW_LINE val2 = a [ i ] ; NEW_LINE DEDENT DEDENT flag = 1 ; NEW_LINE for i in range ( maxi ) : NEW_LINE INDENT if ( a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 1 and maxi + 1 == mini ) : NEW_LINE INDENT flag = 1 ; NEW_LINE for i in range ( mini , n - 1 ) : NEW_LINE INDENT if ( a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT flag = 1 ; NEW_LINE for i in range ( mini ) : NEW_LINE INDENT if ( a [ i ] < a [ i + 1 ] ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 1 and maxi - 1 == mini ) : NEW_LINE INDENT flag = 1 ; NEW_LINE for i in range ( maxi , n - 1 ) : NEW_LINE INDENT if ( a [ i ] < a [ i + 1 ] ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT a = [ 4 , 5 , 6 , 2 , 3 ] ; NEW_LINE n = len ( a ) ; NEW_LINE if ( isPossible ( a , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Subsets and Splits