text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Count number of rotated strings which have more number of vowels in the first half than second half | Function to return the count of rotated strings which have more number of vowels in the first half than the second half ; Create a new string ; Pre array to store count of all vowels ; Compute the prefix array ; To store the required answer ; Find all rotated strings ; Right and left index of the string ; x1 stores the number of vowels in the rotated string ; Left stores the number of vowels in the first half of rotated string ; Right stores the number of vowels in the second half of rotated string ; If the count of vowels in the first half is greater than the count in the second half ; Return the required answer ; Driver code | def cntRotations ( s , n ) : NEW_LINE INDENT str = s + s ; NEW_LINE pre = [ 0 ] * ( 2 * n ) ; NEW_LINE for i in range ( 2 * n ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT pre [ i ] += pre [ i - 1 ] ; NEW_LINE DEDENT if ( str [ i ] == ' a ' or str [ i ] == ' e ' or str [ i ] == ' i ' or str [ i ] == ' o ' or str [ i ] == ' u ' ) : NEW_LINE INDENT pre [ i ] += 1 ; NEW_LINE DEDENT DEDENT ans = 0 ; NEW_LINE for i in range ( n - 1 , 2 * n - 1 , 1 ) : NEW_LINE INDENT r = i ; l = i - n ; NEW_LINE x1 = pre [ r ] ; NEW_LINE if ( l >= 0 ) : NEW_LINE INDENT x1 -= pre [ l ] ; NEW_LINE DEDENT r = ( int ) ( i - n / 2 ) ; NEW_LINE left = pre [ r ] ; NEW_LINE if ( l >= 0 ) : NEW_LINE INDENT left -= pre [ l ] ; NEW_LINE DEDENT right = x1 - left ; NEW_LINE if ( left > right ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT s = " abecidft " ; NEW_LINE n = len ( s ) ; NEW_LINE print ( cntRotations ( s , n ) ) ; NEW_LINE |
Count number of rotated strings which have more number of vowels in the first half than second half | Function to return the count of rotated strings which have more number of vowels in the first half than the second half ; Compute the number of vowels in first - half ; Compute the number of vowels in second - half ; Check if first - half has more vowels ; Check for all possible rotations ; Return the answer ; Driver code ; Function call | def cntRotations ( s , n ) : NEW_LINE INDENT lh , rh , ans = 0 , 0 , 0 NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) : NEW_LINE INDENT lh += 1 NEW_LINE DEDENT DEDENT for i in range ( n // 2 , n ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) : NEW_LINE INDENT rh += 1 NEW_LINE DEDENT DEDENT if ( lh > rh ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i - 1 ] == ' a ' or s [ i - 1 ] == ' e ' or s [ i - 1 ] == ' i ' or s [ i - 1 ] == ' o ' or s [ i - 1 ] == ' u ' ) : NEW_LINE INDENT rh += 1 NEW_LINE lh -= 1 NEW_LINE DEDENT if ( s [ ( i - 1 + n // 2 ) % n ] == ' a ' or s [ ( i - 1 + n // 2 ) % n ] == ' e ' or s [ ( i - 1 + n // 2 ) % n ] == ' i ' or s [ ( i - 1 + n // 2 ) % n ] == ' o ' or s [ ( i - 1 + n // 2 ) % n ] == ' u ' ) : NEW_LINE INDENT rh -= 1 NEW_LINE lh += 1 NEW_LINE DEDENT if ( lh > rh ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abecidft " NEW_LINE n = len ( s ) NEW_LINE print ( cntRotations ( s , n ) ) NEW_LINE DEDENT |
Queries for rotation and Kth character of the given string in constant time | Python3 implementation of the approach ; Function to perform the required queries on the given string ; Pointer pointing to the current starting character of the string ; For every query ; If the query is to rotate the string ; Update the pointer pointing to the starting character of the string ; Index of the kth character in the current rotation of the string ; Print the kth character ; Driver code | size = 2 NEW_LINE def performQueries ( string , n , queries , q ) : NEW_LINE INDENT ptr = 0 ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT if ( queries [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT ptr = ( ptr + queries [ i ] [ 1 ] ) % n ; NEW_LINE DEDENT else : NEW_LINE INDENT k = queries [ i ] [ 1 ] ; NEW_LINE index = ( ptr + k - 1 ) % n ; NEW_LINE print ( string [ index ] ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcdefgh " ; NEW_LINE n = len ( string ) ; NEW_LINE queries = [ [ 1 , 2 ] , [ 2 , 2 ] , [ 1 , 4 ] , [ 2 , 7 ] ] ; NEW_LINE q = len ( queries ) ; NEW_LINE performQueries ( string , n , queries , q ) ; NEW_LINE DEDENT |
Check if a string can be obtained by rotating another string d places | Function to reverse an array from left index to right index ( both inclusive ) ; Function that returns true if str1 can be made equal to str2 by rotating either d places to the left or to the right ; Left Rotation string will contain the string rotated Anti - Clockwise Right Rotation string will contain the string rotated Clockwise ; Copying the str1 string to left rotation string and right rotation string ; Rotating the string d positions to the left ; Rotating the string d positions to the right ; Compairing the rotated strings ; If cannot be made equal with left rotation ; If cannot be made equal with right rotation ; If both or any one of the rotations of str1 were equal to str2 ; Driver code ; d is the rotating factor ; In case length of str1 < d | def ReverseArray ( arr , left , right ) : NEW_LINE INDENT while ( left < right ) : NEW_LINE INDENT temp = arr [ left ] ; NEW_LINE arr [ left ] = arr [ right ] ; NEW_LINE arr [ right ] = temp ; NEW_LINE left += 1 ; NEW_LINE right -= 1 ; NEW_LINE DEDENT DEDENT def RotateAndCheck ( str1 , str2 , d ) : NEW_LINE INDENT if ( len ( str1 ) != len ( str2 ) ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT left_rot_str1 = [ ] ; right_rot_str1 = [ ] ; NEW_LINE left_flag = True ; right_flag = True ; NEW_LINE str1_size = len ( str1 ) ; NEW_LINE for i in range ( str1_size ) : NEW_LINE INDENT left_rot_str1 . append ( str1 [ i ] ) ; NEW_LINE right_rot_str1 . append ( str1 [ i ] ) ; NEW_LINE DEDENT ReverseArray ( left_rot_str1 , 0 , d - 1 ) ; NEW_LINE ReverseArray ( left_rot_str1 , d , str1_size - 1 ) ; NEW_LINE ReverseArray ( left_rot_str1 , 0 , str1_size - 1 ) ; NEW_LINE ReverseArray ( right_rot_str1 , 0 , str1_size - d - 1 ) ; NEW_LINE ReverseArray ( right_rot_str1 , str1_size - d , str1_size - 1 ) ; NEW_LINE ReverseArray ( right_rot_str1 , 0 , str1_size - 1 ) ; NEW_LINE for i in range ( str1_size ) : NEW_LINE INDENT if ( left_rot_str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT left_flag = False ; NEW_LINE DEDENT if ( right_rot_str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT right_flag = False ; NEW_LINE DEDENT DEDENT if ( left_flag or right_flag ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = list ( " abcdefg " ) ; NEW_LINE str2 = list ( " cdefgab " ) ; NEW_LINE d = 2 ; NEW_LINE d = d % len ( str1 ) ; NEW_LINE if ( RotateAndCheck ( str1 , str2 , d ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Count rotations of N which are Odd and Even | Function to count of all rotations which are odd and even ; Driver code | def countOddRotations ( n ) : NEW_LINE INDENT odd_count = 0 ; even_count = 0 NEW_LINE while n != 0 : NEW_LINE INDENT digit = n % 10 NEW_LINE if digit % 2 == 0 : NEW_LINE INDENT odd_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even_count += 1 NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT print ( " Odd β = " , odd_count ) NEW_LINE print ( " Even β = " , even_count ) NEW_LINE DEDENT n = 1234 NEW_LINE countOddRotations ( n ) NEW_LINE |
Generate all rotations of a number | function to return the count of digit of n ; function to print the left shift numbers ; formula to calculate left shift from previous number ; Update the original number ; Driver code | def numberofDigits ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while n > 0 : NEW_LINE INDENT cnt += 1 NEW_LINE n //= 10 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def cal ( num ) : NEW_LINE INDENT digit = numberofDigits ( num ) NEW_LINE powTen = pow ( 10 , digit - 1 ) NEW_LINE for i in range ( digit - 1 ) : NEW_LINE INDENT firstDigit = num // powTen NEW_LINE left = ( num * 10 + firstDigit - ( firstDigit * powTen * 10 ) ) NEW_LINE print ( left , end = " β " ) NEW_LINE num = left NEW_LINE DEDENT DEDENT num = 1445 NEW_LINE cal ( num ) NEW_LINE |
Generating Lyndon words of length n | Python implementation of the above approach ; To store the indices of the characters ; Loop till w is not empty ; Incrementing the last character ; Repeating w to get a n - length string ; Removing the last character as long it is equal to the largest character in S | n = 2 NEW_LINE S = [ '0' , '1' , '2' ] NEW_LINE k = len ( S ) NEW_LINE S . sort ( ) NEW_LINE w = [ - 1 ] NEW_LINE while w : NEW_LINE INDENT w [ - 1 ] += 1 NEW_LINE m = len ( w ) NEW_LINE if m == n : NEW_LINE INDENT print ( ' ' . join ( S [ i ] for i in w ) ) NEW_LINE DEDENT while len ( w ) < n : NEW_LINE INDENT w . append ( w [ - m ] ) NEW_LINE DEDENT while w and w [ - 1 ] == k - 1 : NEW_LINE INDENT w . pop ( ) NEW_LINE DEDENT DEDENT |
Check whether all the rotations of a given number is greater than or equal to the given number or not | Python3 implementation of the approach ; Splitting the number at index i and adding to the front ; Checking if the value is greater than or equal to the given value ; Driver code | def CheckKCycles ( n , s ) : NEW_LINE INDENT ff = True NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT x = int ( s [ i : ] + s [ 0 : i ] ) NEW_LINE if ( x >= int ( s ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT ff = False NEW_LINE break NEW_LINE DEDENT if ( ff ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT n = 3 NEW_LINE s = "123" NEW_LINE CheckKCycles ( n , s ) NEW_LINE |
Rotate the sub | Python3 implementation of the above approach ; Definition of node of linkedlist ; This function take head pointer of list , start and end points of sublist that is to be rotated and the number k and rotate the sublist to right by k places . ; If k is greater than size of sublist then we will take its modulo with size of sublist ; If k is zero or k is equal to size or k is a multiple of size of sublist then list remains intact ; m - th node ; This loop will traverse all node till end node of sublist . Current traversed node ; Count of traversed nodes ; Previous of m - th node ; We will save ( m - 1 ) th node and later make it point to ( n - k + 1 ) th node ; That is how we bring ( n - k + 1 ) th node to front of sublist . ; This keeps rest part of list intact . ; Function for creating and linking new nodes ; 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 rotateSubList ( A , m , n , k ) : NEW_LINE INDENT size = n - m + 1 NEW_LINE if ( k > size ) : NEW_LINE INDENT k = k % size NEW_LINE DEDENT if ( k == 0 or k == size ) : NEW_LINE INDENT head = A NEW_LINE while ( head != None ) : NEW_LINE INDENT print ( head . data ) NEW_LINE head = head . next NEW_LINE DEDENT return NEW_LINE DEDENT link = None NEW_LINE if ( m == 1 ) : NEW_LINE INDENT link = A NEW_LINE DEDENT c = A NEW_LINE count = 0 NEW_LINE end = None NEW_LINE pre = None NEW_LINE while ( c != None ) : NEW_LINE INDENT count = count + 1 NEW_LINE if ( count == m - 1 ) : NEW_LINE INDENT pre = c NEW_LINE link = c . next NEW_LINE DEDENT if ( count == n - k ) : NEW_LINE INDENT if ( m == 1 ) : NEW_LINE INDENT end = c NEW_LINE A = c . next NEW_LINE DEDENT else : NEW_LINE INDENT end = c NEW_LINE pre . next = c . next NEW_LINE DEDENT DEDENT if ( count == n ) : NEW_LINE INDENT d = c . next NEW_LINE c . next = link NEW_LINE end . next = d NEW_LINE head = A NEW_LINE while ( head != None ) : NEW_LINE INDENT print ( head . data , end = " β " ) NEW_LINE head = head . next NEW_LINE DEDENT return NEW_LINE DEDENT c = c . next NEW_LINE DEDENT DEDENT def push ( head , val ) : NEW_LINE INDENT new_node = Node ( val ) NEW_LINE new_node . data = val NEW_LINE new_node . next = head NEW_LINE head = new_node NEW_LINE return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 70 ) NEW_LINE head = push ( head , 60 ) NEW_LINE head = push ( head , 50 ) NEW_LINE head = push ( head , 40 ) NEW_LINE head = push ( head , 30 ) NEW_LINE head = push ( head , 20 ) NEW_LINE head = push ( head , 10 ) NEW_LINE tmp = head NEW_LINE print ( " Given β List : β " , end = " " ) NEW_LINE while ( tmp != None ) : NEW_LINE INDENT print ( tmp . data , end = " β " ) NEW_LINE tmp = tmp . next NEW_LINE DEDENT print ( ) NEW_LINE m = 3 NEW_LINE n = 6 NEW_LINE k = 2 NEW_LINE print ( " After β rotation β of β sublist : β " , end = " " ) NEW_LINE rotateSubList ( head , m , n , k ) NEW_LINE DEDENT |
Generating numbers that are divisor of their right | Python program to Generating numbers that are divisor of their right - rotations ; Function to check if N is a divisor of its right - rotation ; Function to generate m - digit numbers which are divisor of their right - rotation ; Driver code | from math import log10 NEW_LINE def rightRotationDivisor ( N ) : NEW_LINE INDENT lastDigit = N % 10 NEW_LINE rightRotation = ( lastDigit * 10 ** int ( log10 ( N ) ) + N // 10 ) NEW_LINE return rightRotation % N == 0 NEW_LINE DEDENT def generateNumbers ( m ) : NEW_LINE INDENT for i in range ( 10 ** ( m - 1 ) , 10 ** m ) : NEW_LINE INDENT if rightRotationDivisor ( i ) : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT DEDENT m = 3 NEW_LINE generateNumbers ( m ) NEW_LINE |
Generating numbers that are divisor of their right | Python program to Generating numbers that are divisor of their right - rotations ; Function to generate m - digit numbers which are divisor of their right - rotation ; Driver code | from math import log10 NEW_LINE def generateNumbers ( m ) : NEW_LINE INDENT numbers = [ ] NEW_LINE for y in range ( 1 , 10 ) : NEW_LINE INDENT k_max = ( ( 10 ** ( m - 2 ) * ( 10 * y + 1 ) ) // ( 10 ** ( m - 1 ) + y ) ) NEW_LINE for k in range ( 1 , k_max + 1 ) : NEW_LINE INDENT x = ( ( y * ( 10 ** ( m - 1 ) - k ) ) // ( 10 * k - 1 ) ) NEW_LINE if ( ( y * ( 10 ** ( m - 1 ) - k ) ) % ( 10 * k - 1 ) == 0 ) : NEW_LINE INDENT numbers . append ( 10 * x + y ) NEW_LINE DEDENT DEDENT DEDENT for n in sorted ( numbers ) : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT m = 3 NEW_LINE generateNumbers ( m ) NEW_LINE |
Check if an array is sorted and rotated | Python3 program to check if an array is sorted and rotated clockwise ; Function to check if an array is sorted and rotated clockwise ; Find the minimum element and it 's index ; Check if all elements before minIndex are in increasing order ; Check if all elements after minIndex are in increasing order ; Check if last element of the array is smaller than the element just before the element at minIndex starting element of the array for arrays like [ 3 , 4 , 6 , 1 , 2 , 5 ] - not sorted circular array ; Driver code ; Function Call | import sys NEW_LINE def checkIfSortRotated ( arr , n ) : NEW_LINE INDENT minEle = sys . maxsize NEW_LINE maxEle = - sys . maxsize - 1 NEW_LINE minIndex = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] < minEle : NEW_LINE INDENT minEle = arr [ i ] NEW_LINE minIndex = i NEW_LINE DEDENT DEDENT flag1 = 1 NEW_LINE for i in range ( 1 , minIndex ) : NEW_LINE INDENT if arr [ i ] < arr [ i - 1 ] : NEW_LINE INDENT flag1 = 0 NEW_LINE break NEW_LINE DEDENT DEDENT flag2 = 2 NEW_LINE for i in range ( minIndex + 1 , n ) : NEW_LINE INDENT if arr [ i ] < arr [ i - 1 ] : NEW_LINE INDENT flag2 = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag1 and flag2 and arr [ n - 1 ] < arr [ 0 ] ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT arr = [ 3 , 4 , 5 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE checkIfSortRotated ( arr , n ) NEW_LINE |
Rotate a matrix by 90 degree in clockwise direction without using any extra space | Python3 implementation of above approach ; Function to rotate the matrix 90 degree clockwise ; printing the matrix on the basis of observations made on indices . ; Driver code | N = 4 NEW_LINE def rotate90Clockwise ( arr ) : NEW_LINE INDENT global N NEW_LINE for j in range ( N ) : NEW_LINE INDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT arr = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE rotate90Clockwise ( arr ) ; NEW_LINE |
Elements that occurred only once in the array | Function to find the elements that appeared only once in the array ; Sort the array ; Check for first element ; Check for all the elements if it is different its adjacent elements ; Check for the last element ; Driver code | def occurredOnce ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE if arr [ 0 ] != arr [ 1 ] : NEW_LINE INDENT print ( arr [ 0 ] , end = " β " ) NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] and arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if arr [ n - 2 ] != arr [ n - 1 ] : NEW_LINE INDENT print ( arr [ n - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE occurredOnce ( arr , n ) NEW_LINE DEDENT |
Elements that occurred only once in the array | Python3 implementation to find elements that appeared only once ; Function to find the elements that appeared only once in the array ; Store all the elements in the map with their occurrence ; Traverse the map and print all the elements with occurrence 1 ; Driver code | import math as mt NEW_LINE def occurredOnce ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT for it in mp : NEW_LINE INDENT if mp [ it ] == 1 : NEW_LINE INDENT print ( it , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE occurredOnce ( arr , n ) NEW_LINE |
Elements that occurred only once in the array | Function to find the elements that appeared only once in the array ; Check if the first and last element is equal If yes , remove those elements ; Start traversing the remaining elements ; Check if current element is equal to the element at immediate previous index If yes , check the same for next element ; Else print the current element ; Check for the last element ; Driver code | def occurredOnce ( arr , n ) : NEW_LINE INDENT i = 1 NEW_LINE len = n NEW_LINE if arr [ 0 ] == arr [ len - 1 ] : NEW_LINE INDENT i = 2 NEW_LINE len -= 1 NEW_LINE DEDENT while i < n : NEW_LINE INDENT if arr [ i ] == arr [ i - 1 ] : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i - 1 ] , end = " β " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( arr [ n - 1 ] != arr [ 0 ] and arr [ n - 1 ] != arr [ n - 2 ] ) : NEW_LINE INDENT print ( arr [ n - 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE occurredOnce ( arr , n ) NEW_LINE DEDENT |
Split the array and add the first part to the end | Set 2 | Function to reverse arr [ ] from index start to end ; Function to print an array ; Function to left rotate arr [ ] of size n by k ; Driver Code ; Function calling | def rvereseArray ( arr , start , end ) : NEW_LINE INDENT while start < end : NEW_LINE INDENT temp = arr [ start ] NEW_LINE arr [ start ] = arr [ end ] NEW_LINE arr [ end ] = temp NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def splitArr ( arr , k , n ) : NEW_LINE INDENT rvereseArray ( arr , 0 , n - 1 ) NEW_LINE rvereseArray ( arr , 0 , n - k - 1 ) NEW_LINE rvereseArray ( arr , n - k , n - 1 ) NEW_LINE DEDENT arr = [ 12 , 10 , 5 , 6 , 52 , 36 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE splitArr ( arr , k , n ) NEW_LINE printArray ( arr , n ) NEW_LINE |
Check if strings are rotations of each other or not | Set 2 | Python program to check if two strings are rotations of each other ; create lps [ ] that will hold the longest prefix suffix values for pattern ; length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; the loop calculates lps [ i ] for i = 1 to n - 1 ; Match from that rotating point ; Driver code | def isRotation ( a : str , b : str ) -> bool : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if ( n != m ) : NEW_LINE INDENT return False NEW_LINE DEDENT lps = [ 0 for _ in range ( n ) ] NEW_LINE length = 0 NEW_LINE i = 1 NEW_LINE lps [ 0 ] = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] == b [ length ] ) : NEW_LINE INDENT length += 1 NEW_LINE lps [ i ] = length NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( length == 0 ) : NEW_LINE INDENT lps [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT length = lps [ length - 1 ] NEW_LINE DEDENT DEDENT DEDENT i = 0 NEW_LINE for k in range ( lps [ n - 1 ] , m ) : NEW_LINE INDENT if ( b [ k ] != a [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " ABACD " NEW_LINE s2 = " CDABA " NEW_LINE print ( "1" if isRotation ( s1 , s2 ) else "0" ) NEW_LINE DEDENT |
Count rotations divisible by 8 | function to count of all rotations divisible by 8 ; For single digit number ; For two - digit numbers ( considering all pairs ) ; first pair ; second pair ; considering all three - digit sequences ; Considering the number formed by the last digit and the first two digits ; Considering the number formed by the last two digits and the first digit ; required count of rotations ; Driver Code | def countRotationsDivBy8 ( n ) : NEW_LINE INDENT l = len ( n ) NEW_LINE count = 0 NEW_LINE if ( l == 1 ) : NEW_LINE INDENT oneDigit = int ( n [ 0 ] ) NEW_LINE if ( oneDigit % 8 == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( l == 2 ) : NEW_LINE INDENT first = int ( n [ 0 ] ) * 10 + int ( n [ 1 ] ) NEW_LINE second = int ( n [ 1 ] ) * 10 + int ( n [ 0 ] ) NEW_LINE if ( first % 8 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( second % 8 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT threeDigit = 0 NEW_LINE for i in range ( 0 , ( l - 2 ) ) : NEW_LINE INDENT threeDigit = ( int ( n [ i ] ) * 100 + int ( n [ i + 1 ] ) * 10 + int ( n [ i + 2 ] ) ) NEW_LINE if ( threeDigit % 8 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT threeDigit = ( int ( n [ l - 1 ] ) * 100 + int ( n [ 0 ] ) * 10 + int ( n [ 1 ] ) ) NEW_LINE if ( threeDigit % 8 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT threeDigit = ( int ( n [ l - 2 ] ) * 100 + int ( n [ l - 1 ] ) * 10 + int ( n [ 0 ] ) ) NEW_LINE if ( threeDigit % 8 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = "43262488612" NEW_LINE print ( " Rotations : " , countRotationsDivBy8 ( n ) ) NEW_LINE DEDENT |
Minimum move to end operations to make all strings equal | Python 3 program to make all strings same using move to end operations . ; Returns minimum number of moves to end operations to make all strings same . ; Consider s [ i ] as target string and count rotations required to make all other strings same as str [ i ] . ; find function returns the index where we found arr [ i ] which is actually count of move - to - front operations . ; If any two strings are not rotations of each other , we can 't make them same. ; Driver Code | import sys NEW_LINE def minimunMoves ( arr , n ) : NEW_LINE INDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT tmp = arr [ j ] + arr [ j ] NEW_LINE index = tmp . find ( arr [ i ] ) NEW_LINE if ( index == len ( arr [ i ] ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT curr_count += index NEW_LINE DEDENT ans = min ( curr_count , ans ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " xzzwo " , " zwoxz " , " zzwox " , " xzzwo " ] NEW_LINE n = len ( arr ) NEW_LINE print ( minimunMoves ( arr , n ) ) NEW_LINE DEDENT |
Count rotations in sorted and rotated linked list | Linked list node ; Function that count number of rotation in singly linked list . ; Declare count variable and assign it 1. ; Declare a min variable and assign to data of head node . ; Check that while head not equal to None . ; If min value is greater then head -> data then it breaks the while loop and return the value of count . ; head assign the next value of head . ; Function to push element in linked list . ; Allocate dynamic memory for newNode . ; Assign the data into newNode . ; newNode -> next assign the address of head node . ; newNode become the headNode . ; Display linked list . ; Driver code ; Create a node and initialize with None ; push ( ) insert node in linked list . 15 -> 18 -> 5 -> 8 -> 11 -> 12 ; Function call countRotation ( ) | 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 countRotation ( head ) : NEW_LINE INDENT count = 0 NEW_LINE min = head . data NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( min > head . data ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE head = head . next NEW_LINE DEDENT return count NEW_LINE DEDENT def push ( head , data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE newNode . data = data NEW_LINE newNode . next = ( head ) NEW_LINE ( head ) = newNode NEW_LINE 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 DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 11 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 18 ) NEW_LINE head = push ( head , 15 ) NEW_LINE printList ( head ) ; NEW_LINE print ( ) NEW_LINE print ( " Linked β list β rotated β elements : β " , end = ' ' ) NEW_LINE print ( countRotation ( head ) ) NEW_LINE DEDENT |
Rotate Linked List block wise | Link list node ; Recursive function to rotate one block ; Rotate Clockwise ; Rotate anti - Clockwise ; Function to rotate the linked list block wise ; If length is 0 or 1 return head ; If degree of rotation is 0 , return head ; Traverse upto last element of this block ; Storing the first node of next block ; If nodes of this block are less than k . Rotate this block also ; Append the new head of next block to the tail of this block ; Return head of updated Linked List ; Function to push a node ; Function to print linked list ; Driver code ; Start with the empty list ; Create a list 1.2 . 3.4 .5 . 6.7 . 8.9 . None ; k is block size and d is number of rotations in every block . | 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 rotateHelper ( blockHead , blockTail , d , tail , k ) : NEW_LINE INDENT if ( d == 0 ) : NEW_LINE INDENT return blockHead , tail NEW_LINE DEDENT if ( d > 0 ) : NEW_LINE INDENT temp = blockHead NEW_LINE i = 1 NEW_LINE while temp . next . next != None and i < k - 1 : NEW_LINE INDENT temp = temp . next NEW_LINE i += 1 NEW_LINE DEDENT blockTail . next = blockHead NEW_LINE tail = temp NEW_LINE return rotateHelper ( blockTail , temp , d - 1 , tail , k ) NEW_LINE DEDENT if ( d < 0 ) : NEW_LINE INDENT blockTail . next = blockHead NEW_LINE tail = blockHead NEW_LINE return rotateHelper ( blockHead . next , blockHead , d + 1 , tail , k ) NEW_LINE DEDENT DEDENT def rotateByBlocks ( head , k , d ) : NEW_LINE INDENT if ( head == None or head . next == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT if ( d == 0 ) : NEW_LINE INDENT return head NEW_LINE DEDENT temp = head NEW_LINE tail = None NEW_LINE i = 1 NEW_LINE while temp . next != None and i < k : NEW_LINE INDENT temp = temp . next NEW_LINE i += 1 NEW_LINE DEDENT nextBlock = temp . next NEW_LINE if ( i < k ) : NEW_LINE INDENT head , tail = rotateHelper ( head , temp , d % k , tail , i ) NEW_LINE DEDENT else : NEW_LINE INDENT head , tail = rotateHelper ( head , temp , d % k , tail , k ) NEW_LINE DEDENT tail . next = rotateByBlocks ( nextBlock , k , d % k ) ; NEW_LINE return head ; NEW_LINE 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 DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE for i in range ( 9 , 0 , - 1 ) : NEW_LINE INDENT head = push ( head , i ) NEW_LINE DEDENT print ( " Given β linked β list β " ) NEW_LINE printList ( head ) NEW_LINE k = 3 NEW_LINE d = 2 NEW_LINE head = rotateByBlocks ( head , k , d ) NEW_LINE print ( " Rotated by blocks Linked list " ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
Check if two numbers are bit rotations of each other or not | function to check if two numbers are equal after bit rotation ; x64 has concatenation of x with itself . ; comapring only last 32 bits ; right shift by 1 unit ; Driver Code | def isRotation ( x , y ) : NEW_LINE INDENT x64 = x | ( x << 32 ) NEW_LINE while ( x64 >= y ) : NEW_LINE INDENT if ( ( x64 ) == y ) : NEW_LINE INDENT return True NEW_LINE DEDENT x64 >>= 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 122 NEW_LINE y = 2147483678 NEW_LINE if ( isRotation ( x , y ) == False ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) NEW_LINE DEDENT DEDENT |
Count rotations divisible by 4 | Returns count of all rotations divisible by 4 ; For single digit number ; At - least 2 digit number ( considering all pairs ) ; Considering the number formed by the pair of last digit and 1 st digit ; Driver program | def countRotations ( n ) : NEW_LINE INDENT l = len ( n ) NEW_LINE if ( l == 1 ) : NEW_LINE INDENT oneDigit = ( int ) ( n [ 0 ] ) NEW_LINE if ( oneDigit % 4 == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 0 , l - 1 ) : NEW_LINE INDENT twoDigit = ( int ) ( n [ i ] ) * 10 + ( int ) ( n [ i + 1 ] ) NEW_LINE if ( twoDigit % 4 == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT twoDigit = ( int ) ( n [ l - 1 ] ) * 10 + ( int ) ( n [ 0 ] ) NEW_LINE if ( twoDigit % 4 == 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT n = "4834" NEW_LINE print ( " Rotations : β " , countRotations ( n ) ) NEW_LINE |
Check if a string can be obtained by rotating another string 2 places | Function to check if string2 is obtained by string 1 ; Initialize string as anti - clockwise rotation ; Initialize string as clock wise rotation ; check if any of them is equal to string1 ; Driver code | def isRotated ( str1 , str2 ) : NEW_LINE INDENT if ( len ( str1 ) != len ( str2 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( len ( str1 ) < 2 ) : NEW_LINE INDENT return str1 == str2 NEW_LINE DEDENT clock_rot = " " NEW_LINE anticlock_rot = " " NEW_LINE l = len ( str2 ) NEW_LINE anticlock_rot = ( anticlock_rot + str2 [ l - 2 : ] + str2 [ 0 : l - 2 ] ) NEW_LINE clock_rot = clock_rot + str2 [ 2 : ] + str2 [ 0 : 2 ] NEW_LINE return ( str1 == clock_rot or str1 == anticlock_rot ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " geeks " NEW_LINE str2 = " eksge " NEW_LINE DEDENT if isRotated ( str1 , str2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Lexicographically minimum string rotation | Set 1 | This function return lexicographically minimum rotation of str ; Find length of given string ; Create an array of strings to store all rotations ; Create a concatenation of string with itself ; One by one store all rotations of str in array . A rotation is obtained by getting a substring of concat ; Sort all rotations ; Return the first rotation from the sorted array ; Driver Code | def minLexRotation ( str_ ) : NEW_LINE INDENT n = len ( str_ ) NEW_LINE arr = [ 0 ] * n NEW_LINE concat = str_ + str_ NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = concat [ i : n + i ] NEW_LINE DEDENT arr . sort ( ) NEW_LINE return arr [ 0 ] NEW_LINE DEDENT print ( minLexRotation ( " GEEKSFORGEEKS " ) ) NEW_LINE print ( minLexRotation ( " GEEKSQUIZ " ) ) NEW_LINE print ( minLexRotation ( " BCABDADAB " ) ) NEW_LINE |
Types of Linked List | structure of Node | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT |
Types of Linked List | structure of Node | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . previous = None NEW_LINE self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT |
Types of Linked List | structure of Node | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT |
Types of Linked List | structure of Node | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . previous = None NEW_LINE self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT |
Types of Linked List | structure of Node | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT |
Remove all even parity nodes from a Doubly and Circular Singly Linked List | Node of the doubly linked list ; Function to insert a node at the beginning of the Doubly Linked List ; Allocate the node ; Insert the data ; Since we are adding at the beginning , prev is always None ; Link the old list off the new node ; Change the prev of head node to new node ; Move the head to point to the new node ; Function that returns true if count of set bits in x is even ; parity will store the count of set bits ; Function to delete a node in a Doubly Linked List . head_ref - . pointer to head node pointer . delt - . pointer to node to be deleted ; Base case ; If the node to be deleted is head node ; Change next only if node to be deleted is not the last node ; Change prev only if node to be deleted is not the first node ; Finally , free the memory occupied by delt ; Function to to remove all the Even Parity Nodes from a doubly linked list ; Iterating through the linked list ; If node ' s β data ' s parity is even ; Function to print nodes in a given doubly linked list ; Driver Code ; Create the doubly linked list 18 < . 15 < . 8 < . 9 < . 14 ; Uncomment to view the list cout << " Original β List : β " ; printList ( head ) ; ; Modified List | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . prev = None 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 . prev = None NEW_LINE new_node . next = ( head_ref ) NEW_LINE if ( ( head_ref ) != None ) : NEW_LINE INDENT ( head_ref ) . prev = new_node NEW_LINE DEDENT ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def isEvenParity ( x ) : NEW_LINE INDENT parity = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT parity += 1 NEW_LINE DEDENT x = x >> 1 NEW_LINE DEDENT if ( parity % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def deleteNode ( head_ref , delt ) : NEW_LINE INDENT if ( head_ref == None or delt == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( head_ref == delt ) : NEW_LINE INDENT head_ref = delt . next NEW_LINE DEDENT if ( delt . next != None ) : NEW_LINE INDENT delt . next . prev = delt . prev NEW_LINE DEDENT if ( delt . prev != None ) : NEW_LINE INDENT delt . prev . next = delt . next NEW_LINE DEDENT del ( delt ) NEW_LINE return head_ref NEW_LINE DEDENT def deleteEvenParityNodes ( head_ref ) : NEW_LINE INDENT ptr = head_ref NEW_LINE next = None NEW_LINE while ( ptr != None ) : NEW_LINE INDENT next = ptr . next NEW_LINE if ( isEvenParity ( ptr . data ) ) : NEW_LINE INDENT head_ref = deleteNode ( head_ref , ptr ) NEW_LINE DEDENT ptr = next NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT print ( " Empty list " ) NEW_LINE return NEW_LINE DEDENT 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 = None NEW_LINE head = push ( head , 14 ) NEW_LINE head = push ( head , 9 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 15 ) NEW_LINE head = push ( head , 18 ) NEW_LINE head = deleteEvenParityNodes ( head ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
Remove all even parity nodes from a Doubly and Circular Singly Linked List | Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; Create a new node and make head as next of it . ; If linked list is not None then set the next of last node ; Find the node before head and update next of it . ; Pofor the first node ; Function to deltete the node from a Circular Linked list ; If node to be delteted is head node ; Traverse list till not found deltete node ; Copy the address of the node ; Finally , free the memory occupied by delt ; Function that returns true if count of set bits in x is even ; parity will store the count of set bits ; Function to deltete all the Even Parity Nodes from the singly circular linked list ; Traverse the list till the end ; If the node ' s β data β has β even β parity , β β deltete β node β ' ptr ; Poto the next node ; Function to prnodes in a given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 11.9 .34 .6 .13 .21 | 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 , data ) : NEW_LINE INDENT ptr1 = Node ( ) NEW_LINE temp = head_ref ; NEW_LINE ptr1 . data = data ; NEW_LINE ptr1 . next = head_ref ; NEW_LINE if ( head_ref != None ) : NEW_LINE INDENT while ( temp . next != head_ref ) : NEW_LINE INDENT temp = temp . next ; NEW_LINE DEDENT temp . next = ptr1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 . next = ptr1 ; NEW_LINE DEDENT head_ref = ptr1 ; NEW_LINE return head_ref NEW_LINE DEDENT def delteteNode ( head_ref , delt ) : NEW_LINE INDENT if ( head_ref == delt ) : NEW_LINE INDENT head_ref = delt . next ; NEW_LINE DEDENT temp = head_ref ; NEW_LINE while ( temp . next != delt ) : NEW_LINE INDENT temp = temp . next ; NEW_LINE DEDENT temp . next = delt . next ; NEW_LINE del ( delt ) ; NEW_LINE return head_ref ; NEW_LINE DEDENT def isEvenParity ( x ) : NEW_LINE INDENT parity = 0 ; NEW_LINE while ( x != 0 ) : NEW_LINE INDENT if ( x & 1 ) != 0 : NEW_LINE INDENT parity += 1 NEW_LINE DEDENT x = x >> 1 ; NEW_LINE DEDENT if ( parity % 2 == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def delteteEvenParityNodes ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return head ; NEW_LINE DEDENT if ( head == head . next ) : NEW_LINE INDENT if ( isEvenParity ( head . data ) ) : NEW_LINE INDENT head = None ; NEW_LINE DEDENT return head ; NEW_LINE DEDENT ptr = head ; NEW_LINE next = None NEW_LINE while True : NEW_LINE INDENT next = ptr . next ; NEW_LINE if ( isEvenParity ( ptr . data ) ) : NEW_LINE INDENT head = delteteNode ( head , ptr ) ; NEW_LINE DEDENT ptr = next ; NEW_LINE if ( ptr == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( head == head . next ) : NEW_LINE INDENT if ( isEvenParity ( head . data ) ) : NEW_LINE INDENT head = None ; NEW_LINE DEDENT return head ; NEW_LINE DEDENT return head ; NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT print ( " Empty β List " ) NEW_LINE return ; NEW_LINE DEDENT temp = head ; NEW_LINE if ( head != None ) : NEW_LINE INDENT while True : NEW_LINE INDENT print ( temp . data , end = ' β ' ) NEW_LINE temp = temp . next NEW_LINE if temp == head : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 21 ) ; NEW_LINE head = push ( head , 13 ) ; NEW_LINE head = push ( head , 6 ) ; NEW_LINE head = push ( head , 34 ) ; NEW_LINE head = push ( head , 9 ) ; NEW_LINE head = push ( head , 11 ) ; NEW_LINE head = delteteEvenParityNodes ( head ) ; NEW_LINE printList ( head ) ; NEW_LINE DEDENT |
Remove all the Even Digit Sum Nodes from a Circular Singly Linked List | Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; Create a new node and make head as next of it . ; If linked list is not None then set the next of last node ; Find the node before head and update next of it . ; Point for the first node ; Function to deltete the node from a Circular Linked list ; If node to be delteted is head node ; Traverse list till not found deltete node ; Copy the address of the node ; Finally , free the memory occupied by delt ; Function to find the digit sum for a number ; Function to deltete all the Even Digit Sum Nodes from the singly circular linked list ; Traverse the list till the end ; If the node ' s β data β is β Fibonacci , β β deltete β node β ' ptr ; Point to the next node ; Function to print nodes in a given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 9.11 .34 .6 .13 .21 | 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 , data ) : NEW_LINE INDENT ptr1 = Node ( data ) NEW_LINE temp = head_ref NEW_LINE ptr1 . data = data NEW_LINE ptr1 . next = head_ref NEW_LINE if ( head_ref != None ) : NEW_LINE INDENT while ( temp . next != head_ref ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = ptr1 NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 . next = ptr1 NEW_LINE DEDENT head_ref = ptr1 NEW_LINE return head_ref NEW_LINE DEDENT def delteteNode ( head_ref , delt ) : NEW_LINE INDENT temp = head_ref NEW_LINE if ( head_ref == delt ) : NEW_LINE INDENT head_ref = delt . next NEW_LINE DEDENT while ( temp . next != delt ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = delt . next NEW_LINE del ( delt ) NEW_LINE return NEW_LINE DEDENT def digitSum ( num ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( num != 0 ) : NEW_LINE INDENT sum += ( num % 10 ) NEW_LINE num //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def delteteEvenDigitSumNodes ( head ) : NEW_LINE INDENT ptr = head NEW_LINE next = None NEW_LINE while True : NEW_LINE INDENT if ( not ( digitSum ( ptr . data ) & 1 ) ) : NEW_LINE INDENT delteteNode ( head , ptr ) NEW_LINE DEDENT next = ptr . next NEW_LINE ptr = next NEW_LINE if ( ptr == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE if ( head != None ) : NEW_LINE INDENT while True : NEW_LINE INDENT print ( temp . data , end = ' β ' ) NEW_LINE temp = temp . next NEW_LINE if ( temp == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 21 ) NEW_LINE head = push ( head , 13 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 34 ) NEW_LINE head = push ( head , 11 ) NEW_LINE head = push ( head , 9 ) NEW_LINE delteteEvenDigitSumNodes ( head ) NEW_LINE printList ( head ) NEW_LINE DEDENT |
Remove all Fibonacci Nodes from a Circular Singly Linked List | Structure for a node ; Function to add a node at the beginning of a Circular linked list ; Create a new node and make head as next of it . ; If linked list is not None then set the next of last node ; Find the node before head and update next of it . ; Point for the first node ; Delete the node from a Circular Linked list ; If node to be deleted is head node ; Traverse list till not found delete node ; Copy the address of the node ; Finally , free the memory occupied by delt ; Function to find the maximum node of the circular linked list ; Pointer for traversing ; Initialize head to the current pointer ; Initialize min value to max ; While the last node is not reached ; If current node data is greater for max then replace it ; Function to create hashmap table to check Fibonacci numbers ; Adding the first two elements to the hashmap ; Inserting the Fibonacci numbers into the hashmap ; Function to delete all the Fibonacci nodes from the singly circular linked list ; Find the largest node value in Circular Linked List ; Creating a hashmap containing all the Fibonacci numbers upto the maximum data value in the circular linked list ; Traverse the list till the end ; If the node ' s β data β is β Fibonacci , β β delete β node β ' ptr ; Point to the next node ; Function to print nodes in a given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 9.11 .34 .6 .13 .20 | 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 , data ) : NEW_LINE INDENT ptr1 = Node ( ) NEW_LINE temp = head_ref ; NEW_LINE ptr1 . data = data ; NEW_LINE ptr1 . next = head_ref ; NEW_LINE if ( head_ref != None ) : NEW_LINE INDENT while ( temp . next != head_ref ) : NEW_LINE INDENT temp = temp . next ; NEW_LINE DEDENT temp . next = ptr1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 . next = ptr1 ; NEW_LINE DEDENT head_ref = ptr1 ; NEW_LINE return head_ref NEW_LINE DEDENT def deleteNode ( head_ref , delt ) : NEW_LINE INDENT temp = head_ref ; NEW_LINE if ( head_ref == delt ) : NEW_LINE INDENT head_ref = delt . next ; NEW_LINE DEDENT while ( temp . next != delt ) : NEW_LINE INDENT temp = temp . next ; NEW_LINE DEDENT temp . next = delt . next ; NEW_LINE del ( delt ) ; NEW_LINE return ; NEW_LINE DEDENT def largestElement ( head_ref ) : NEW_LINE INDENT current = None NEW_LINE current = head_ref ; NEW_LINE maxEle = - 10000000 NEW_LINE while ( True ) : NEW_LINE INDENT if ( current . data > maxEle ) : NEW_LINE INDENT maxEle = current . data ; NEW_LINE DEDENT current = current . next ; NEW_LINE if ( current == head_ref ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return maxEle ; NEW_LINE DEDENT def createHash ( hashmap , maxElement ) : NEW_LINE INDENT prev = 0 NEW_LINE curr = 1 ; NEW_LINE hashmap . add ( prev ) ; NEW_LINE hashmap . add ( curr ) ; NEW_LINE while ( curr <= maxElement ) : NEW_LINE INDENT temp = curr + prev ; NEW_LINE hashmap . add ( temp ) ; NEW_LINE prev = curr ; NEW_LINE curr = temp ; NEW_LINE DEDENT DEDENT def deleteFibonacciNodes ( head ) : NEW_LINE INDENT maxEle = largestElement ( head ) ; NEW_LINE hashmap = set ( ) NEW_LINE createHash ( hashmap , maxEle ) ; NEW_LINE ptr = head ; NEW_LINE next = None NEW_LINE while ( True ) : NEW_LINE INDENT if ( ptr . data in hashmap ) : NEW_LINE INDENT deleteNode ( head , ptr ) ; NEW_LINE DEDENT next = ptr . next ; NEW_LINE ptr = next ; NEW_LINE if ( ptr == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT def printList ( head ) : NEW_LINE INDENT temp = head ; NEW_LINE if ( head != None ) : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT print ( temp . data , end = ' β ' ) NEW_LINE temp = temp . next NEW_LINE if ( temp == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 20 ) ; NEW_LINE head = push ( head , 13 ) ; NEW_LINE head = push ( head , 6 ) ; NEW_LINE head = push ( head , 34 ) ; NEW_LINE head = push ( head , 11 ) ; NEW_LINE head = push ( head , 9 ) ; NEW_LINE deleteFibonacciNodes ( head ) ; NEW_LINE printList ( head ) ; NEW_LINE DEDENT |
Delete all odd nodes of a Circular Linked List | Python3 program to delete all odd node from a Circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not None then set the next of last node ; For the first node ; Delete the node if it is odd ; If node to be deleted is head node ; Traverse list till not found delete node ; Copy address of node ; Function to delete all odd nodes from the singly circular linked list ; if node is odd ; po to next node ; Function to pr nodes ; Driver code ; Initialize lists as empty ; Created linked list will be 56 -> 61 -> 57 -> 11 -> 12 -> 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 DEDENT DEDENT def push ( head_ref , data ) : NEW_LINE INDENT ptr1 = Node ( data ) NEW_LINE temp = head_ref NEW_LINE ptr1 . data = data NEW_LINE ptr1 . next = head_ref NEW_LINE if ( head_ref != None ) : NEW_LINE INDENT while ( temp . next != head_ref ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = ptr1 NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 . next = ptr1 NEW_LINE DEDENT head_ref = ptr1 NEW_LINE return head_ref NEW_LINE DEDENT def deleteNode ( head_ref , delete ) : NEW_LINE INDENT temp = head_ref NEW_LINE if ( head_ref == delete ) : NEW_LINE INDENT head_ref = delete . next NEW_LINE DEDENT while ( temp . next != delete ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = delete . next NEW_LINE DEDENT def deleteoddNodes ( head ) : NEW_LINE INDENT ptr = head NEW_LINE next = None NEW_LINE next = ptr . next NEW_LINE ptr = next NEW_LINE while ( ptr != head ) : NEW_LINE INDENT if ( ptr . data % 2 == 1 ) : NEW_LINE INDENT deleteNode ( head , ptr ) NEW_LINE DEDENT next = ptr . next NEW_LINE ptr = next NEW_LINE DEDENT return head NEW_LINE DEDENT def prList ( head ) : NEW_LINE INDENT temp = head NEW_LINE if ( head != None ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE while ( temp != head ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 11 ) NEW_LINE head = push ( head , 57 ) NEW_LINE head = push ( head , 61 ) NEW_LINE head = push ( head , 56 ) NEW_LINE print ( " List β after β deletion β : β " , end = " " ) NEW_LINE head = deleteoddNodes ( head ) NEW_LINE prList ( head ) NEW_LINE DEDENT |
Insertion in a sorted circular linked list when a random pointer is given | Python3 implementation of the approach ; Node structure ; Function to create a node ; Function to find and return the head ; If the list is empty ; Finding the last node of the linked list the last node must have the highest value if no such element is present then all the nodes of the linked list must be same ; Return the head ; Function to insert a new_node in the list in sorted fashion . Note that this function expects a pointer to head node as this can modify the head of the input linked list ; If the list is empty ; If the node to be inserted is the smallest then it has to be the new head ; Find the last node of the list as it will be pointing to the head ; Locate the node before the point of insertion ; Return the new head ; Function to print the nodes of the linked list ; Driver code ; Start with an empty linked list ; Create linked list from the given array ; Move to a random node if it exists ; Print the contents of the created list | from random import randint NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . next = None NEW_LINE self . data = 0 NEW_LINE DEDENT DEDENT def create ( ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . next = None NEW_LINE return new_node NEW_LINE DEDENT def find_head ( random ) : NEW_LINE INDENT if ( random == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT head = None NEW_LINE var = random NEW_LINE while ( not ( var . data > var . next . data or var . next == random ) ) : NEW_LINE INDENT var = var . next NEW_LINE DEDENT return var . next NEW_LINE DEDENT def sortedInsert ( head_ref , new_node ) : NEW_LINE INDENT current = head_ref NEW_LINE if ( current == None ) : NEW_LINE INDENT new_node . next = new_node NEW_LINE head_ref = new_node NEW_LINE DEDENT elif ( current . data >= new_node . data ) : NEW_LINE INDENT while ( current . next != head_ref ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT current . next = new_node NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE DEDENT else : NEW_LINE INDENT while ( current . next != head_ref and current . next . data < new_node . data ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT new_node . next = current . next NEW_LINE current . next = new_node NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def printList ( start ) : NEW_LINE INDENT temp = 0 NEW_LINE if ( start != None ) : NEW_LINE INDENT temp = start NEW_LINE while True : NEW_LINE INDENT print ( temp . data , end = ' β ' ) NEW_LINE temp = temp . next NEW_LINE if ( temp == start ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 56 , 2 , 11 , 1 , 90 ] NEW_LINE start = None ; NEW_LINE temp = 0 NEW_LINE for i in range ( 6 ) : NEW_LINE INDENT if ( start != None ) : NEW_LINE INDENT for j in range ( randint ( 0 , 10 ) ) : NEW_LINE INDENT start = start . next NEW_LINE DEDENT DEDENT temp = create ( ) NEW_LINE temp . data = arr [ i ] NEW_LINE start = sortedInsert ( find_head ( start ) , temp ) NEW_LINE DEDENT printList ( find_head ( start ) ) NEW_LINE DEDENT |
Splitting starting N nodes into new Circular Linked List while preserving the old nodes | Python3 implementation of the approach ; Function to add a node to the empty list ; If not empty ; Assigning the data ; Creating the link ; Function to add a node to the beginning of the list ; If list is empty ; Assign data ; Function to traverse and prthe list ; If list is empty ; Pointing to the first Node of the list ; Traversing the list ; Function to find the length of the CircularLinkedList ; Stores the length ; List is empty ; Iterator Node to traverse the List ; Return the length of the list ; Function to split the first k nodes into a new CircularLinkedList and the remaining nodes stay in the original CircularLinkedList ; Empty Node for reference ; Check if the list is empty If yes , then return NULL ; NewLast will contain the last node of the new split list itr to iterate the node till the required node ; Update NewLast to the required node and link the last to the start of rest of the list ; Return the last node of the required list ; Driver code ; Append the new last node into the new list ; Print the new 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 addToEmpty ( last , data ) : NEW_LINE INDENT if ( last != None ) : NEW_LINE INDENT return last NEW_LINE DEDENT temp = Node ( data ) NEW_LINE last = temp NEW_LINE last . next = last NEW_LINE return last NEW_LINE DEDENT def addBegin ( last , data ) : NEW_LINE INDENT if ( last == None ) : NEW_LINE INDENT return addToEmpty ( data ) NEW_LINE DEDENT temp = Node ( data ) NEW_LINE temp . next = last . next NEW_LINE last . next = temp NEW_LINE return last NEW_LINE DEDENT def traverse ( last ) : NEW_LINE INDENT if ( last == None ) : NEW_LINE INDENT print ( " List β is β empty . " ) NEW_LINE return NEW_LINE DEDENT p = last . next NEW_LINE while True : NEW_LINE INDENT print ( p . data , end = " β " ) NEW_LINE p = p . next NEW_LINE if p == last . next : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT def length ( last ) : NEW_LINE INDENT x = 0 NEW_LINE if ( last == None ) : NEW_LINE INDENT return x NEW_LINE DEDENT itr = last . next NEW_LINE while ( itr . next != last . next ) : NEW_LINE INDENT x += 1 NEW_LINE itr = itr . next NEW_LINE DEDENT return ( x + 1 ) NEW_LINE DEDENT def split ( last , k ) : NEW_LINE INDENT passs = Node ( - 1 ) NEW_LINE if ( last == None ) : NEW_LINE INDENT return last NEW_LINE DEDENT itr = last NEW_LINE for i in range ( k ) : NEW_LINE INDENT itr = itr . next NEW_LINE DEDENT newLast = itr NEW_LINE passs . next = itr . next NEW_LINE newLast . next = last . next NEW_LINE last . next = passs . next NEW_LINE return newLast NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT clist = None NEW_LINE clist = addToEmpty ( clist , 12 ) NEW_LINE clist = addBegin ( clist , 10 ) NEW_LINE clist = addBegin ( clist , 8 ) NEW_LINE clist = addBegin ( clist , 6 ) NEW_LINE clist = addBegin ( clist , 4 ) NEW_LINE clist = addBegin ( clist , 2 ) NEW_LINE print ( " Original β list : " , end = " " ) NEW_LINE traverse ( clist ) NEW_LINE k = 4 NEW_LINE clist2 = split ( clist , k ) NEW_LINE print ( " The β new β lists β are : " , end = " " ) NEW_LINE traverse ( clist2 ) NEW_LINE traverse ( clist ) NEW_LINE DEDENT |
Convert a given Binary Tree to Circular Doubly Linked List | Set 2 | A binary tree node has data , and left and right pointers ; Function to perform In - Order traversal of the tree and store the nodes in a vector ; first recur on left child ; append the data of node in vector ; now recur on right child ; Function to convert Binary Tree to Circular Doubly Linked list using the vector which stores In - Order traversal of the Binary Tree ; Base cases ; Vector to be used for storing the nodes of tree in In - order form ; Calling the In - Order traversal function ; Create the head of the linked list pointing to the root of the tree ; Create a current pointer to be used in traversal ; Traversing the nodes of the tree starting from the second elements ; Create a temporary pointer pointing to current ; Current 's right points to the current node in traversal ; Current points to its right ; Current 's left points to temp ; Current 's right points to head of the list ; Head 's left points to current ; Return head of the list ; Display Circular Link List ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT v = [ ] NEW_LINE def inorder ( root ) : NEW_LINE INDENT global v NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE v . append ( root . data ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT def bTreeToCList ( root ) : NEW_LINE INDENT global v NEW_LINE if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT v = [ ] NEW_LINE inorder ( root ) NEW_LINE head_ref = Node ( v [ 0 ] ) NEW_LINE curr = head_ref NEW_LINE i = 1 NEW_LINE while ( i < len ( v ) ) : NEW_LINE INDENT temp = curr NEW_LINE curr . right = Node ( v [ i ] ) NEW_LINE curr = curr . right NEW_LINE curr . left = temp NEW_LINE i = i + 1 NEW_LINE DEDENT curr . right = head_ref NEW_LINE head_ref . left = curr NEW_LINE return head_ref NEW_LINE DEDENT def displayCList ( head ) : NEW_LINE INDENT print ( " Circular β Doubly β Linked β List β is β : " , end = " " ) NEW_LINE itr = head NEW_LINE while ( True ) : NEW_LINE INDENT print ( itr . data , end = " β " ) NEW_LINE itr = itr . right NEW_LINE if ( head == itr ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 12 ) NEW_LINE root . right = Node ( 15 ) NEW_LINE root . left . left = Node ( 25 ) NEW_LINE root . left . right = Node ( 30 ) NEW_LINE root . right . left = Node ( 36 ) NEW_LINE head = bTreeToCList ( root ) NEW_LINE displayCList ( head ) NEW_LINE |
Deletion at different positions in a Circular Linked List | Function to delete last node of Circular Linked List ; check if list doesn 't have any node if not then return ; check if list have single node if yes then delete it and return ; move first node to last previous | def DeleteLast ( head ) : NEW_LINE INDENT current = head NEW_LINE temp = head NEW_LINE previous = None NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " List is empty " ) NEW_LINE return None NEW_LINE DEDENT if ( current . next == current ) : NEW_LINE INDENT head = None NEW_LINE return None NEW_LINE DEDENT while ( current . next != head ) : NEW_LINE INDENT previous = current NEW_LINE current = current . next NEW_LINE DEDENT previous . next = current . next NEW_LINE head = previous . next NEW_LINE return head NEW_LINE DEDENT |
Deletion at different positions in a Circular Linked List | A linked list node ; Function to insert a node at the end of a Circular linked list ; Create a new node ; check node is created or not ; insert data into newly created node ; check list is empty if not have any node then make first node it ; if list have already some node ; move first node to last node ; put first or head node address in new node link ; put new node address into last node link ( next ) ; Function print data of list ; if list is empty , simply show message ; traverse first to last node ; Function return number of nodes present in list ; if list is empty simply return length zero ; traverse forst to last node ; Function delete First node of Circular Linked List ; check list have any node if not then return ; check list have single node if yes then delete it and return ; traverse second to first ; now previous is last node and next is first node of list first node ( next ) link address put in last node ( previous ) link ; make second node as head node ; Function to delete last node of Circular Linked List ; check if list doesn 't have any node if not then return ; check if list have single node if yes then delete it and return ; move first node to last previous ; Function delete node at a given poisition of Circular Linked List ; Find length of list ; check list have any node if not then return ; given index is in list or not ; delete first node ; traverse first to last node ; if index found delete that node ; Driver Code ; Deleting Node at position ; Deleting first Node ; Deleting last Node | class Node : NEW_LINE INDENT def __init__ ( self , new_data ) : NEW_LINE INDENT self . data = new_data NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT def Insert ( head , data ) : NEW_LINE INDENT current = head NEW_LINE newNode = Node ( 0 ) NEW_LINE if ( newNode == None ) : NEW_LINE INDENT print ( " Memory Error " ) NEW_LINE return None NEW_LINE DEDENT newNode . data = data NEW_LINE if ( head == None ) : NEW_LINE INDENT newNode . next = newNode NEW_LINE head = newNode NEW_LINE return head NEW_LINE DEDENT else : NEW_LINE INDENT while ( current . next != head ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT newNode . next = head NEW_LINE current . next = newNode NEW_LINE DEDENT return head NEW_LINE DEDENT def Display ( head ) : NEW_LINE INDENT current = head NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " Display List is empty " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT print ( current . data , end = " β " ) NEW_LINE current = current . next NEW_LINE if ( current == head ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def Length ( head ) : NEW_LINE INDENT current = head NEW_LINE count = 0 NEW_LINE if ( head == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT current = current . next NEW_LINE count = count + 1 NEW_LINE if ( current == head ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def DeleteFirst ( head ) : NEW_LINE INDENT previous = head NEW_LINE next = head NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " List is empty " ) NEW_LINE return None NEW_LINE DEDENT if ( previous . next == previous ) : NEW_LINE INDENT head = None NEW_LINE return None NEW_LINE DEDENT while ( previous . next != head ) : NEW_LINE INDENT previous = previous . next NEW_LINE next = previous . next NEW_LINE DEDENT previous . next = next . next NEW_LINE head = previous . next NEW_LINE return head NEW_LINE DEDENT def DeleteLast ( head ) : NEW_LINE INDENT current = head NEW_LINE temp = head NEW_LINE previous = None NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " List is empty " ) NEW_LINE return None NEW_LINE DEDENT if ( current . next == current ) : NEW_LINE INDENT head = None NEW_LINE return None NEW_LINE DEDENT while ( current . next != head ) : NEW_LINE INDENT previous = current NEW_LINE current = current . next NEW_LINE DEDENT previous . next = current . next NEW_LINE head = previous . next NEW_LINE return head NEW_LINE DEDENT def DeleteAtPosition ( head , index ) : NEW_LINE INDENT len = Length ( head ) NEW_LINE count = 1 NEW_LINE previous = head NEW_LINE next = head NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " Delete Last List is empty " ) NEW_LINE return None NEW_LINE DEDENT if ( index >= len or index < 0 ) : NEW_LINE INDENT print ( " Index is not Found " ) NEW_LINE return None NEW_LINE DEDENT if ( index == 0 ) : NEW_LINE INDENT head = DeleteFirst ( head ) NEW_LINE return head NEW_LINE DEDENT while ( len > 0 ) : NEW_LINE INDENT if ( index == count ) : NEW_LINE INDENT previous . next = next . next NEW_LINE return head NEW_LINE DEDENT previous = previous . next NEW_LINE next = previous . next NEW_LINE len = len - 1 NEW_LINE count = count + 1 NEW_LINE DEDENT return head NEW_LINE DEDENT head = None NEW_LINE head = Insert ( head , 99 ) NEW_LINE head = Insert ( head , 11 ) NEW_LINE head = Insert ( head , 22 ) NEW_LINE head = Insert ( head , 33 ) NEW_LINE head = Insert ( head , 44 ) NEW_LINE head = Insert ( head , 55 ) NEW_LINE head = Insert ( head , 66 ) NEW_LINE print ( " Initial β List : β " ) NEW_LINE Display ( head ) NEW_LINE print ( " After Deleting node at index 4 : " ) NEW_LINE head = DeleteAtPosition ( head , 4 ) NEW_LINE Display ( head ) NEW_LINE print ( " Initial List : " ) NEW_LINE Display ( head ) NEW_LINE print ( " After Deleting first node : " ) NEW_LINE head = DeleteFirst ( head ) NEW_LINE Display ( head ) NEW_LINE print ( " Initial List : " ) NEW_LINE Display ( head ) NEW_LINE print ( " After Deleting last node : " ) NEW_LINE head = DeleteLast ( head ) NEW_LINE Display ( head ) NEW_LINE |
Find minimum and maximum elements in singly Circular Linked List | structure for a node ; Function to print minimum and maximum nodes of the circular linked list ; check list is empty ; initialize head to current pointer ; initialize max int value to min initialize min int value to max ; While last node is not reached ; If current node data is lesser for min then replace it ; If current node data is greater for max then replace it ; Function to insert a node at the end of a Circular linked list ; Create a new node ; check node is created or not ; insert data into newly created node ; check list is empty if not have any node then make first node it ; if list have already some node ; move firt node to last node ; put first or head node address in new node link ; put new node address into last node link ( next ) ; Function to print the Circular linked list ; if list is empty simply show message ; traverse first to last node ; 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 printMinMax ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT current = head ; NEW_LINE min = 1000000000 NEW_LINE max = - 1000000000 ; NEW_LINE while True : NEW_LINE INDENT if ( current . data < min ) : NEW_LINE INDENT min = current . data ; NEW_LINE DEDENT if ( current . data > max ) : NEW_LINE INDENT max = current . data ; NEW_LINE DEDENT current = current . next ; NEW_LINE if ( current == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ' Minimum β = β { } , β Maximum β = β { } ' . format ( min , max ) ) NEW_LINE DEDENT def insertNode ( head , data ) : NEW_LINE INDENT current = head ; NEW_LINE newNode = Node ( ) NEW_LINE if not newNode : NEW_LINE INDENT print ( " Memory Error " ) ; NEW_LINE return head NEW_LINE DEDENT newNode . data = data ; NEW_LINE if ( head == None ) : NEW_LINE INDENT newNode . next = newNode ; NEW_LINE head = newNode ; NEW_LINE return head NEW_LINE DEDENT else : NEW_LINE INDENT while ( current . next != head ) : NEW_LINE INDENT current = current . next ; NEW_LINE DEDENT newNode . next = head ; NEW_LINE current . next = newNode ; NEW_LINE DEDENT return head NEW_LINE DEDENT def displayList ( head ) : NEW_LINE INDENT current = head ; NEW_LINE if ( head == None ) : NEW_LINE INDENT print ( " Display List is empty " ) ; NEW_LINE return ; NEW_LINE DEDENT else : NEW_LINE INDENT while True : NEW_LINE INDENT print ( current . data , end = ' β ' ) ; NEW_LINE current = current . next ; NEW_LINE if ( current == head ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Head = None ; NEW_LINE Head = insertNode ( Head , 99 ) ; NEW_LINE Head = insertNode ( Head , 11 ) ; NEW_LINE Head = insertNode ( Head , 22 ) ; NEW_LINE Head = insertNode ( Head , 33 ) ; NEW_LINE Head = insertNode ( Head , 44 ) ; NEW_LINE Head = insertNode ( Head , 55 ) ; NEW_LINE Head = insertNode ( Head , 66 ) ; NEW_LINE print ( " Initial β List : β " , end = ' ' ) NEW_LINE displayList ( Head ) ; NEW_LINE printMinMax ( Head ) ; NEW_LINE DEDENT |
Delete all the even nodes of a Circular Linked List | Python3 program to delete all even node from a Circular singly linked list ; Structure for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not None then set the next of last node ; For the first node ; Delete the node if it is even ; If node to be deleted is head node ; traverse list till not found delete node ; copy address of node ; Function to delete all even nodes from the singly circular linked list ; if node is even ; po to next node ; Function to pr nodes ; Driver code ; Initialize lists as empty ; Created linked list will be 57.11 .2 .56 .12 .61 | import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , data ) : NEW_LINE INDENT ptr1 = Node ( data ) NEW_LINE temp = head_ref NEW_LINE ptr1 . data = data NEW_LINE ptr1 . next = head_ref NEW_LINE if ( head_ref != None ) : NEW_LINE INDENT while ( temp . next != head_ref ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = ptr1 NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 . next = ptr1 NEW_LINE DEDENT head_ref = ptr1 NEW_LINE return head_ref NEW_LINE DEDENT def deleteNode ( head_ref , delete ) : NEW_LINE INDENT temp = head_ref NEW_LINE if ( head_ref == delete ) : NEW_LINE INDENT head_ref = delete . next NEW_LINE DEDENT while ( temp . next != delete ) : NEW_LINE INDENT temp = temp . next NEW_LINE DEDENT temp . next = delete . next NEW_LINE DEDENT def deleteEvenNodes ( head ) : NEW_LINE INDENT ptr = head NEW_LINE next = None NEW_LINE next = ptr . next NEW_LINE ptr = next NEW_LINE while ( ptr != head ) : NEW_LINE INDENT if ( ptr . data % 2 == 0 ) : NEW_LINE INDENT deleteNode ( head , ptr ) NEW_LINE DEDENT next = ptr . next NEW_LINE ptr = next NEW_LINE DEDENT return head NEW_LINE DEDENT def prList ( head ) : NEW_LINE INDENT temp = head NEW_LINE if ( head != None ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE while ( temp != head ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 61 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 56 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 11 ) NEW_LINE head = push ( head , 57 ) NEW_LINE print ( " List β after β deletion β : β " , end = " " ) NEW_LINE head = deleteEvenNodes ( head ) NEW_LINE prList ( head ) NEW_LINE DEDENT |
Sum of the nodes of a Circular Linked List | Python3 program to find the sum of all nodes of a Circular linked list ; class for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not NULL then set the next of last node ; For the first node ; Function to find sum of the given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 11 -> 2 -> 56 -> 12 | import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head , data ) : NEW_LINE INDENT if not head : NEW_LINE INDENT head = Node ( data ) NEW_LINE head . next = head NEW_LINE return head NEW_LINE DEDENT lnode = head NEW_LINE while ( lnode and lnode . next is not head ) : NEW_LINE INDENT lnode = lnode . next NEW_LINE DEDENT ptr1 = Node ( data ) NEW_LINE ptr1 . next = head NEW_LINE lnode . next = ptr1 NEW_LINE head = ptr1 NEW_LINE return head NEW_LINE DEDENT def sumOfList ( head ) : NEW_LINE INDENT temp = head NEW_LINE tsum = temp . data NEW_LINE temp = temp . next NEW_LINE while ( temp is not head ) : NEW_LINE INDENT tsum += temp . data NEW_LINE temp = temp . next NEW_LINE DEDENT return tsum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 56 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 11 ) NEW_LINE print ( " Sum β of β circular β list β is β = β { } " . format ( sumOfList ( head ) ) ) NEW_LINE DEDENT |
Delete every Kth node from circular linked list | Python3 program to delete every kth Node from circular linked list . ; structure for a Node ; Utility function to print the circular linked list ; Function to delete every kth Node ; If list is empty , simply return . ; take two poers - current and previous ; Check if Node is the only Node \ If yes , we reached the goal , therefore return . ; Pr intermediate list . ; If more than one Node present in the list , Make previous pointer po to current Iterate current pointer k times , i . e . current Node is to be deleted . ; If Node to be deleted is head ; If Node to be deleted is last Node . ; Function to insert a Node at the end of a Circular linked list ; Create a new Node ; if the list is empty , make the new Node head Also , it will po to itself . ; traverse the list to reach the last Node and insert the Node ; Driver Code ; insert Nodes in the circular linked list ; Delete every kth Node from the circular linked 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 prList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT temp = head NEW_LINE print ( temp . data , end = " - > " ) NEW_LINE temp = temp . next NEW_LINE while ( temp != head ) : NEW_LINE INDENT print ( temp . data , end = " - > " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( head . data ) NEW_LINE DEDENT def deleteK ( head_ref , k ) : NEW_LINE INDENT head = head_ref NEW_LINE if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT curr = head NEW_LINE prev = None NEW_LINE while True : NEW_LINE INDENT if ( curr . next == head and curr == head ) : NEW_LINE INDENT break NEW_LINE DEDENT prList ( head ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT prev = curr NEW_LINE curr = curr . next NEW_LINE DEDENT if ( curr == head ) : NEW_LINE INDENT prev = head NEW_LINE while ( prev . next != head ) : NEW_LINE INDENT prev = prev . next NEW_LINE DEDENT head = curr . next NEW_LINE prev . next = head NEW_LINE head_ref = head NEW_LINE DEDENT elif ( curr . next == head ) : NEW_LINE INDENT prev . next = head NEW_LINE DEDENT else : NEW_LINE INDENT prev . next = curr . next NEW_LINE DEDENT DEDENT DEDENT def insertNode ( head_ref , x ) : NEW_LINE INDENT head = head_ref NEW_LINE temp = Node ( x ) NEW_LINE if ( head == None ) : NEW_LINE INDENT temp . next = temp NEW_LINE head_ref = temp NEW_LINE return head_ref NEW_LINE DEDENT else : NEW_LINE INDENT temp1 = head NEW_LINE while ( temp1 . next != head ) : NEW_LINE INDENT temp1 = temp1 . next NEW_LINE DEDENT temp1 . next = temp NEW_LINE temp . next = head NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = insertNode ( head , 1 ) NEW_LINE head = insertNode ( head , 2 ) NEW_LINE head = insertNode ( head , 3 ) NEW_LINE head = insertNode ( head , 4 ) NEW_LINE head = insertNode ( head , 5 ) NEW_LINE head = insertNode ( head , 6 ) NEW_LINE head = insertNode ( head , 7 ) NEW_LINE head = insertNode ( head , 8 ) NEW_LINE head = insertNode ( head , 9 ) NEW_LINE k = 4 NEW_LINE deleteK ( head , k ) NEW_LINE DEDENT |
Insertion at Specific Position in a Circular Doubly Linked List | Node of the doubly linked list ; Utility function to create a node in memory ; Function to display the list ; Function to count nunmber of elements in the list ; Declare temp pointer to traverse the list ; Variable to store the count ; Iterate the list and increment the count ; As the list is circular , increment the counter at last ; Function to insert a node at a given position in the circular doubly linked list ; Declare two pointers ; Create a new node in memory ; Point temp to start ; count of total elements in the list ; If list is empty or the position is not valid , return False ; Assign the data ; Iterate till the loc ; See in Image , circle 1 ; See in Image , Circle 2 ; See in Image , Circle 3 ; See in Image , Circle 4 ; Function to create circular doubly linked list from array elements ; Declare newNode and temporary pointer ; Iterate the loop until array length ; Create new node ; Assign the array data ; If it is first element Put that node prev and next as start as it is circular ; Find the last node ; Add the last node to make them in circular fashion ; Driver Code ; Array elements to create circular doubly linked list ; Start Pointer ; Create the List ; Display the list before insertion ; Inserting 8 at 3 rd position ; Display the list after insertion | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def getNode ( ) : NEW_LINE INDENT return ( Node ( 0 ) ) NEW_LINE DEDENT def displayList ( temp ) : NEW_LINE INDENT t = temp NEW_LINE if ( temp == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The β list β is : β " , end = " β " ) NEW_LINE while ( temp . next != t ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( temp . data ) NEW_LINE return 1 NEW_LINE DEDENT DEDENT def countList ( start ) : NEW_LINE INDENT temp = start NEW_LINE count = 0 NEW_LINE while ( temp . next != start ) : NEW_LINE INDENT temp = temp . next NEW_LINE count = count + 1 NEW_LINE DEDENT count = count + 1 NEW_LINE return count NEW_LINE DEDENT def insertAtLocation ( start , data , loc ) : NEW_LINE INDENT temp = None NEW_LINE newNode = None NEW_LINE i = 0 NEW_LINE count = 0 NEW_LINE newNode = getNode ( ) NEW_LINE temp = start NEW_LINE count = countList ( start ) NEW_LINE if ( temp == None or count < loc ) : NEW_LINE INDENT return start NEW_LINE DEDENT else : NEW_LINE INDENT newNode . data = data NEW_LINE i = 1 ; NEW_LINE while ( i < loc - 1 ) : NEW_LINE INDENT temp = temp . next NEW_LINE i = i + 1 NEW_LINE DEDENT newNode . next = temp . next NEW_LINE ( temp . next ) . prev = newNode NEW_LINE temp . next = newNode NEW_LINE newNode . prev = temp NEW_LINE return start NEW_LINE DEDENT return start NEW_LINE DEDENT def createList ( arr , n , start ) : NEW_LINE INDENT newNode = None NEW_LINE temp = None NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT newNode = getNode ( ) NEW_LINE newNode . data = arr [ i ] NEW_LINE if ( i == 0 ) : NEW_LINE INDENT start = newNode NEW_LINE newNode . prev = start NEW_LINE newNode . next = start NEW_LINE DEDENT else : NEW_LINE INDENT temp = ( start ) . prev NEW_LINE temp . next = newNode NEW_LINE newNode . next = start NEW_LINE newNode . prev = temp NEW_LINE temp = start NEW_LINE temp . prev = newNode NEW_LINE DEDENT i = i + 1 ; NEW_LINE DEDENT return start NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE start = None NEW_LINE start = createList ( arr , n , start ) NEW_LINE displayList ( start ) NEW_LINE start = insertAtLocation ( start , 8 , 3 ) NEW_LINE displayList ( start ) NEW_LINE DEDENT |
Convert an Array to a Circular Doubly Linked List | Node of the doubly linked list ; Utility function to create a node in memory ; Function to display the list ; Function to convert array into list ; Declare newNode and temporary pointer ; Iterate the loop until array length ; Create new node ; Assign the array data ; If it is first element Put that node prev and next as start as it is circular ; Find the last node ; Add the last node to make them in circular fashion ; Driver Code ; Array to be converted ; Start Pointer ; Create the List ; Display the list | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def getNode ( ) : NEW_LINE INDENT return ( Node ( 0 ) ) NEW_LINE DEDENT def displayList ( temp ) : NEW_LINE INDENT t = temp NEW_LINE if ( temp == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The β list β is : β " , end = " β " ) NEW_LINE while ( temp . next != t ) : NEW_LINE INDENT print ( temp . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( temp . data ) NEW_LINE return 1 NEW_LINE DEDENT DEDENT def createList ( arr , n , start ) : NEW_LINE INDENT newNode = None NEW_LINE temp = None NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT newNode = getNode ( ) NEW_LINE newNode . data = arr [ i ] NEW_LINE if ( i == 0 ) : NEW_LINE INDENT start = newNode NEW_LINE newNode . prev = start NEW_LINE newNode . next = start NEW_LINE DEDENT else : NEW_LINE INDENT temp = ( start ) . prev NEW_LINE temp . next = newNode NEW_LINE newNode . next = start NEW_LINE newNode . prev = temp NEW_LINE temp = start NEW_LINE temp . prev = newNode NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return start NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE start = None NEW_LINE start = createList ( arr , n , start ) NEW_LINE displayList ( start ) NEW_LINE DEDENT |
Lucky alive person in a circle | Code Solution to sword puzzle | Node structure ; Function to find the luckiest person ; Create a single node circular linked list . ; Starting from first soldier . ; condition for evaluating the existence of single soldier who is not killed . ; deleting soldier from the circular list who is killed in the fight . ; Returning the Luckiest soldier who remains alive . ; 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 ( data ) : NEW_LINE INDENT node = Node ( data ) NEW_LINE return node NEW_LINE DEDENT def alivesol ( Num ) : NEW_LINE INDENT if ( Num == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT last = newNode ( 1 ) ; NEW_LINE last . next = last ; NEW_LINE for i in range ( 2 , Num + 1 ) : NEW_LINE INDENT temp = newNode ( i ) ; NEW_LINE temp . next = last . next ; NEW_LINE last . next = temp ; NEW_LINE last = temp ; NEW_LINE DEDENT curr = last . next ; NEW_LINE temp = None NEW_LINE while ( curr . next != curr ) : NEW_LINE INDENT temp = curr ; NEW_LINE curr = curr . next ; NEW_LINE temp . next = curr . next ; NEW_LINE del curr ; NEW_LINE temp = temp . next ; NEW_LINE curr = temp ; NEW_LINE DEDENT res = temp . data ; NEW_LINE del temp ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 ; NEW_LINE print ( alivesol ( N ) ) NEW_LINE DEDENT |
Lowest Common Ancestor of the deepest leaves of a Binary Tree | Node of a Binary Tree ; Function to find the depth of the Binary Tree ; If root is not null ; Left recursive subtree ; Right recursive subtree ; Returns the maximum depth ; Function to perform the depth first search on the binary tree ; If root is null ; If curr is equal to depth ; Left recursive subtree ; Right recursive subtree ; If left and right are not null ; Return left , if left is not null Otherwise return right ; Function to find the LCA of the deepest nodes of the binary tree ; If root is null ; Stores the deepest depth of the binary tree ; Return the LCA of the nodes at level depth ; Driver Code ; Given Binary Tree | class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def finddepth ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = finddepth ( root . left ) NEW_LINE right = finddepth ( root . right ) NEW_LINE return 1 + max ( left , right ) NEW_LINE DEDENT def dfs ( root , curr , depth ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( curr == depth ) : NEW_LINE INDENT return root NEW_LINE DEDENT left = dfs ( root . left , curr + 1 , depth ) NEW_LINE right = dfs ( root . right , curr + 1 , depth ) NEW_LINE if ( left != None and right != None ) : NEW_LINE INDENT return root NEW_LINE DEDENT return left if left else right NEW_LINE DEDENT def lcaOfDeepestLeaves ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return None NEW_LINE DEDENT depth = finddepth ( root ) - 1 NEW_LINE return dfs ( root , 0 , depth ) NEW_LINE 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 . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . left . left = Node ( 8 ) NEW_LINE root . right . left . right = Node ( 9 ) NEW_LINE print ( lcaOfDeepestLeaves ( root ) . data ) NEW_LINE DEDENT |
Check if two nodes are on same path in a tree | Set 2 | Function to filter the return Values ; Utility function to check if nodes are on same path or not ; Condition to check if any vertex is equal to given two vertex or not ; Check if the current position has 1 ; Recursive call ; Return LCA ; Function to check if nodes lies on same path or not ; Driver code | def filter ( x , y , z ) : NEW_LINE INDENT if ( x != - 1 and y != - 1 ) : NEW_LINE INDENT return z NEW_LINE DEDENT return y if x == - 1 else x NEW_LINE DEDENT def samePathUtil ( mtrx , vrtx , v1 , v2 , i ) : NEW_LINE INDENT ans = - 1 NEW_LINE if ( i == v1 or i == v2 ) : NEW_LINE INDENT return i NEW_LINE DEDENT for j in range ( 0 , vrtx ) : NEW_LINE INDENT if ( mtrx [ i ] [ j ] == 1 ) : NEW_LINE INDENT ans = filter ( ans , samePathUtil ( mtrx , vrtx , v1 , v2 , j ) , i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , i ) : NEW_LINE INDENT lca = samePathUtil ( mtrx , vrtx , v1 - 1 , v2 - 1 , i ) NEW_LINE if ( lca == v1 - 1 or lca == v2 - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT vrtx = 7 NEW_LINE edge = 6 NEW_LINE mtrx = [ [ 0 , 1 , 1 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] ] NEW_LINE v1 = 1 NEW_LINE v2 = 5 NEW_LINE if ( isVertexAtSamePath ( mtrx , vrtx , v1 , v2 , 0 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find distance between two nodes in the given Binary tree for Q queries | Python3 Program to find distance between two nodes using LCA ; lg2 ( MAX ) ; Array to store the level of each node ; Vector to store tree ; Pre - Processing to calculate values of lca [ ] [ ] , dist [ ] [ ] ; Using recursion formula to calculate the values of lca [ ] [ ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ ] [ ] and dist [ ] [ ] ; Function to find the distance between given nodes u and v ; The node which is present farthest from the root node is taken as v . If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Adding distance of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x ] [ 0 ] is ; Adding the distance of v and u to its 2 ^ i - th ancestor ; Adding the distance of u and v to its first ancestor ; Driver Code ; Number of nodes ; Add edges with their cost ; Initialising lca and dist values with - 1 and 0 respectively ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 3 } ; Query 3 : { 3 , 5 } | MAX = 1000 NEW_LINE lg = 10 NEW_LINE level = [ 0 for i in range ( MAX ) ] NEW_LINE lca = [ [ 0 for i in range ( lg ) ] for j in range ( MAX ) ] NEW_LINE dist = [ [ 0 for i in range ( lg ) ] for j in range ( MAX ) ] NEW_LINE graph = [ [ ] for i in range ( MAX ) ] NEW_LINE def addEdge ( u , v , cost ) : NEW_LINE INDENT global graph NEW_LINE graph [ u ] . append ( [ v , cost ] ) NEW_LINE graph [ v ] . append ( [ u , cost ] ) NEW_LINE DEDENT def dfs ( node , parent , h , cost ) : NEW_LINE INDENT lca [ node ] [ 0 ] = parent NEW_LINE level [ node ] = h NEW_LINE if ( parent != - 1 ) : NEW_LINE INDENT dist [ node ] [ 0 ] = cost NEW_LINE DEDENT for i in range ( 1 , lg ) : NEW_LINE INDENT if ( lca [ node ] [ i - 1 ] != - 1 ) : NEW_LINE INDENT lca [ node ] [ i ] = lca [ lca [ node ] [ i - 1 ] ] [ i - 1 ] NEW_LINE dist [ node ] [ i ] = ( dist [ node ] [ i - 1 ] + dist [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) NEW_LINE DEDENT DEDENT for i in graph [ node ] : NEW_LINE INDENT if ( i [ 0 ] == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( i [ 0 ] , node , h + 1 , i [ 1 ] ) NEW_LINE DEDENT DEDENT def findDistance ( u , v ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( level [ u ] > level [ v ] ) : NEW_LINE INDENT temp = u NEW_LINE u = v NEW_LINE v = temp NEW_LINE DEDENT i = lg - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( lca [ v ] [ i ] != - 1 and level [ lca [ v ] [ i ] ] >= level [ u ] ) : NEW_LINE INDENT ans += dist [ v ] [ i ] NEW_LINE v = lca [ v ] [ i ] NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( v == u ) : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT i = lg - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( lca [ v ] [ i ] != lca [ u ] [ i ] ) : NEW_LINE INDENT ans += dist [ u ] [ i ] + dist [ v ] [ i ] NEW_LINE v = lca [ v ] [ i ] NEW_LINE u = lca [ u ] [ i ] NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT ans += ( dist [ u ] [ 0 ] + dist [ v ] [ 0 ] ) NEW_LINE print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE addEdge ( 1 , 2 , 2 ) NEW_LINE addEdge ( 1 , 3 , 3 ) NEW_LINE addEdge ( 2 , 4 , 5 ) NEW_LINE addEdge ( 2 , 5 , 7 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( lg ) : NEW_LINE INDENT lca [ i ] [ j ] = - 1 NEW_LINE dist [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT dfs ( 1 , - 1 , 0 , 0 ) NEW_LINE findDistance ( 1 , 3 ) NEW_LINE findDistance ( 2 , 3 ) NEW_LINE findDistance ( 3 , 5 ) NEW_LINE DEDENT |
Count of all prime weight nodes between given nodes in the given Tree | Python3 program count prime weight nodes between two nodes in the given tree ; Function to perform Sieve Of Eratosthenes for prime number ; Initialize all entries of prime it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . memset ( prime , true , sizeof ( prime ) ) ; Check if prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to perform dfs ; Stores parent of each node ; Stores level of each node from root ; Function to perform prime number between the path ; The node which is present farthest from the root node is taken as v If u is farther from root node then swap the two ; Find the ancestor of v which is at same level as u ; If Weight is prime increment count ; If u is the ancestor of v then u is the LCA of u and v Now check if weigh [ v ] is prime or not ; When v and u are on the same level but are in different subtree . Now move both u and v up by 1 till they are not same ; If weight of first ancestor is prime ; Driver code ; Precompute all the prime numbers till MAX ; Weights of the node ; Edges of the tree | MAX = 1000 NEW_LINE weight = [ 0 for i in range ( MAX ) ] NEW_LINE level = [ 0 for i in range ( MAX ) ] NEW_LINE par = [ 0 for i in range ( MAX ) ] NEW_LINE prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE graph = [ [ ] for i in range ( MAX ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if p * p > MAX + 1 : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def dfs ( node , parent , h ) : NEW_LINE INDENT par [ node ] = parent NEW_LINE level [ node ] = h NEW_LINE for child in graph [ node ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( child , node , h + 1 ) NEW_LINE DEDENT DEDENT def findPrimeOnPath ( u , v ) : NEW_LINE INDENT count = 0 NEW_LINE if ( level [ u ] > level [ v ] ) : NEW_LINE INDENT u , v = v , u NEW_LINE DEDENT d = level [ v ] - level [ u ] NEW_LINE while ( d ) : NEW_LINE INDENT if ( prime [ weight [ v ] ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT v = par [ v ] NEW_LINE d -= 1 NEW_LINE DEDENT if ( v == u ) : NEW_LINE INDENT if ( prime [ weight [ v ] ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT while ( v != u ) : NEW_LINE INDENT if ( prime [ weight [ v ] ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( prime [ weight [ u ] ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT u = par [ u ] NEW_LINE v = par [ v ] NEW_LINE DEDENT if ( prime [ weight [ v ] ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE weight [ 1 ] = 5 NEW_LINE weight [ 2 ] = 10 NEW_LINE weight [ 3 ] = 11 NEW_LINE weight [ 4 ] = 8 NEW_LINE weight [ 5 ] = 6 NEW_LINE graph [ 1 ] . append ( 2 ) NEW_LINE graph [ 2 ] . append ( 3 ) NEW_LINE graph [ 2 ] . append ( 4 ) NEW_LINE graph [ 1 ] . append ( 5 ) NEW_LINE dfs ( 1 , - 1 , 0 ) NEW_LINE u = 3 NEW_LINE v = 5 NEW_LINE print ( findPrimeOnPath ( u , v ) ) NEW_LINE DEDENT |
Query to find the maximum and minimum weight between two nodes in the given tree using LCA . | Python3 Program to find the maximum and minimum weight between two nodes in the given tree using LCA ; log2 ( MAX ) ; Array to store the level of each node ; Vector to store tree ; Array to store weight of nodes ; Pre - Processing to calculate values of lca [ ] [ ] , MinWeight [ ] [ ] and MaxWeight [ ] [ ] ; Using recursion formula to calculate the values of lca [ ] [ ] ; Storing the level of each node ; Using recursion formula to calculate the values of lca [ ] [ ] , MinWeight [ ] [ ] and MaxWeight [ ] [ ] ; Function to find the minimum and maximum weights in the given range ; The node which is present farthest from the root node is taken as v If u is farther from root node then swap the two ; Finding the ancestor of v which is at same level as u ; Calculating Minimum and Maximum Weight of node v till its 2 ^ i - th ancestor ; If u is the ancestor of v then u is the LCA of u and v ; Finding the node closest to the root which is not the common ancestor of u and v i . e . a node x such that x is not the common ancestor of u and v but lca [ x ] [ 0 ] is ; Calculating the minimum of MinWeight of v to its 2 ^ i - th ancestor and MinWeight of u to its 2 ^ i - th ancestor ; Calculating the maximum of MaxWeight of v to its 2 ^ i - th ancestor and MaxWeight of u to its 2 ^ i - th ancestor ; Calculating the Minimum of first ancestor of u and v ; Calculating the maximum of first ancestor of u and v ; Driver code ; Number of nodes ; Add edges ; Perform DFS ; Query 1 : { 1 , 3 } ; Query 2 : { 2 , 4 } ; Query 3 : { 3 , 5 } | import sys NEW_LINE MAX = 1000 NEW_LINE log = 10 NEW_LINE level = [ 0 for i in range ( MAX ) ] ; NEW_LINE lca = [ [ - 1 for j in range ( log ) ] for i in range ( MAX ) ] NEW_LINE minWeight = [ [ sys . maxsize for j in range ( log ) ] for i in range ( MAX ) ] NEW_LINE maxWeight = [ [ - sys . maxsize for j in range ( log ) ] for i in range ( MAX ) ] NEW_LINE graph = [ [ ] for i in range ( MAX ) ] NEW_LINE weight = [ 0 for i in range ( MAX ) ] NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT graph [ u ] . append ( v ) ; NEW_LINE graph [ v ] . append ( u ) ; NEW_LINE DEDENT def dfs ( node , parent , h ) : NEW_LINE INDENT lca [ node ] [ 0 ] = parent ; NEW_LINE level [ node ] = h ; NEW_LINE if ( parent != - 1 ) : NEW_LINE INDENT minWeight [ node ] [ 0 ] = ( min ( weight [ node ] , weight [ parent ] ) ) ; NEW_LINE maxWeight [ node ] [ 0 ] = ( max ( weight [ node ] , weight [ parent ] ) ) ; NEW_LINE DEDENT for i in range ( 1 , log ) : NEW_LINE INDENT if ( lca [ node ] [ i - 1 ] != - 1 ) : NEW_LINE INDENT lca [ node ] [ i ] = lca [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ; NEW_LINE minWeight [ node ] [ i ] = min ( minWeight [ node ] [ i - 1 ] , minWeight [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) ; NEW_LINE maxWeight [ node ] [ i ] = max ( maxWeight [ node ] [ i - 1 ] , maxWeight [ lca [ node ] [ i - 1 ] ] [ i - 1 ] ) ; NEW_LINE DEDENT DEDENT for i in graph [ node ] : NEW_LINE INDENT if ( i == parent ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dfs ( i , node , h + 1 ) ; NEW_LINE DEDENT DEDENT def findMinMaxWeight ( u , v ) : NEW_LINE INDENT minWei = sys . maxsize NEW_LINE maxWei = - sys . maxsize NEW_LINE if ( level [ u ] > level [ v ] ) : NEW_LINE INDENT u , v = v , u NEW_LINE DEDENT for i in range ( log - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( lca [ v ] [ i ] != - 1 and level [ lca [ v ] [ i ] ] >= level [ u ] ) : NEW_LINE INDENT minWei = min ( minWei , minWeight [ v ] [ i ] ) ; NEW_LINE maxWei = max ( maxWei , maxWeight [ v ] [ i ] ) ; NEW_LINE v = lca [ v ] [ i ] ; NEW_LINE DEDENT DEDENT if ( v == u ) : NEW_LINE INDENT print ( str ( minWei ) + ' β ' + str ( maxWei ) ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( log - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( lca [ v ] [ i ] != lca [ u ] [ i ] ) : NEW_LINE INDENT minWei = ( min ( minWei , min ( minWeight [ v ] [ i ] , minWeight [ u ] [ i ] ) ) ) ; NEW_LINE maxWei = max ( maxWei , max ( maxWeight [ v ] [ i ] , maxWeight [ u ] [ i ] ) ) ; NEW_LINE v = lca [ v ] [ i ] ; NEW_LINE u = lca [ u ] [ i ] ; NEW_LINE DEDENT DEDENT minWei = min ( minWei , min ( minWeight [ v ] [ 0 ] , minWeight [ u ] [ 0 ] ) ) ; NEW_LINE maxWei = max ( maxWei , max ( maxWeight [ v ] [ 0 ] , maxWeight [ u ] [ 0 ] ) ) ; NEW_LINE print ( str ( minWei ) + ' β ' + str ( maxWei ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE addEdge ( 1 , 2 ) ; NEW_LINE addEdge ( 1 , 5 ) ; NEW_LINE addEdge ( 2 , 4 ) ; NEW_LINE addEdge ( 2 , 3 ) ; NEW_LINE weight [ 1 ] = - 1 ; NEW_LINE weight [ 2 ] = 5 ; NEW_LINE weight [ 3 ] = - 1 ; NEW_LINE weight [ 4 ] = 3 ; NEW_LINE weight [ 5 ] = - 2 ; NEW_LINE dfs ( 1 , - 1 , 0 ) ; NEW_LINE findMinMaxWeight ( 1 , 3 ) ; NEW_LINE findMinMaxWeight ( 2 , 4 ) ; NEW_LINE findMinMaxWeight ( 3 , 5 ) ; NEW_LINE DEDENT |
Lowest Common Ancestor for a Set of Nodes in a Rooted Tree | Python Program to find the LCA in a rooted tree for a given set of nodes ; Set time 1 initially ; Case for root node ; In - time for node ; Out - time for the node ; level [ i ] -- > Level of node i ; t_in [ i ] -- > In - time of node i ; t_out [ i ] -- > Out - time of node i ; Fill the level , in - time and out - time of all nodes ; To find minimum in - time among all nodes in LCA set ; To find maximum in - time among all nodes in LCA set ; Node with same minimum and maximum out time is LCA for the set ; Take the minimum level as level of LCA ; If i - th node is at a higher level than that of the minimum among the nodes of the given set ; Compare in - time , out - time and level of i - th node to the respective extremes among all nodes of the given set ; Driver code | from typing import List NEW_LINE from sys import maxsize NEW_LINE INT_MAX = maxsize NEW_LINE INT_MIN = - maxsize NEW_LINE T = 1 NEW_LINE def dfs ( node : int , parent : int , g : List [ List [ int ] ] , level : List [ int ] , t_in : List [ int ] , t_out : List [ int ] ) -> None : NEW_LINE INDENT global T NEW_LINE if ( parent == - 1 ) : NEW_LINE INDENT level [ node ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT level [ node ] = level [ parent ] + 1 NEW_LINE DEDENT t_in [ node ] = T NEW_LINE for i in g [ node ] : NEW_LINE INDENT if ( i != parent ) : NEW_LINE INDENT T += 1 NEW_LINE dfs ( i , node , g , level , t_in , t_out ) NEW_LINE DEDENT DEDENT T += 1 NEW_LINE t_out [ node ] = T NEW_LINE DEDENT def findLCA ( n : int , g : List [ List [ int ] ] , v : List [ int ] ) -> int : NEW_LINE INDENT level = [ 0 for _ in range ( n + 1 ) ] NEW_LINE t_in = [ 0 for _ in range ( n + 1 ) ] NEW_LINE t_out = [ 0 for _ in range ( n + 1 ) ] NEW_LINE dfs ( 1 , - 1 , g , level , t_in , t_out ) NEW_LINE mint = INT_MAX NEW_LINE maxt = INT_MIN NEW_LINE minv = - 1 NEW_LINE maxv = - 1 NEW_LINE for i in v : NEW_LINE INDENT if ( t_in [ i ] < mint ) : NEW_LINE INDENT mint = t_in [ i ] NEW_LINE minv = i NEW_LINE DEDENT if ( t_out [ i ] > maxt ) : NEW_LINE INDENT maxt = t_out [ i ] NEW_LINE maxv = i NEW_LINE DEDENT DEDENT if ( minv == maxv ) : NEW_LINE INDENT return minv NEW_LINE DEDENT lev = min ( level [ minv ] , level [ maxv ] ) NEW_LINE node = 0 NEW_LINE l = INT_MIN NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( level [ i ] > lev ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( t_in [ i ] <= mint and t_out [ i ] >= maxt and level [ i ] > l ) : NEW_LINE INDENT node = i NEW_LINE l = level [ i ] NEW_LINE DEDENT DEDENT return node NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 NEW_LINE g = [ [ ] for _ in range ( n + 1 ) ] NEW_LINE g [ 1 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 1 ) NEW_LINE g [ 1 ] . append ( 3 ) NEW_LINE g [ 3 ] . append ( 1 ) NEW_LINE g [ 1 ] . append ( 4 ) NEW_LINE g [ 4 ] . append ( 1 ) NEW_LINE g [ 2 ] . append ( 5 ) NEW_LINE g [ 5 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 6 ) NEW_LINE g [ 6 ] . append ( 2 ) NEW_LINE g [ 3 ] . append ( 7 ) NEW_LINE g [ 7 ] . append ( 3 ) NEW_LINE g [ 4 ] . append ( 10 ) NEW_LINE g [ 10 ] . append ( 4 ) NEW_LINE g [ 8 ] . append ( 7 ) NEW_LINE g [ 7 ] . append ( 8 ) NEW_LINE g [ 9 ] . append ( 7 ) NEW_LINE g [ 7 ] . append ( 9 ) NEW_LINE v = [ 7 , 3 , 8 ] NEW_LINE print ( findLCA ( n , g , v ) ) NEW_LINE DEDENT |
Minimum and maximum node that lies in the path connecting two nodes in a Binary Tree | Python3 implementation of the approach ; Function to store the path from root node to given node of the tree in path vector and then returns true if the path exists otherwise false ; Function to print the minimum and the maximum value present in the path connecting the given two nodes of the given binary tree ; To store the path from the root node to a ; To store the path from the root node to b ; To store the minimum and the maximum value in the path from LCA to a ; To store the minimum and the maximum value in the path from LCA to b ; If both a and b are present in the tree ; Compare the paths to get the first different value ; Find minimum and maximum value in the path from LCA to a ; Find minimum and maximum value in the path from LCA to b ; Minimum of min values in first path and second path ; Maximum of max values in first path and second path ; If no path exists ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def FindPath ( root , path , key ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return False NEW_LINE DEDENT path . append ( root . data ) NEW_LINE if root . data == key : NEW_LINE INDENT return True NEW_LINE DEDENT if ( FindPath ( root . left , path , key ) or FindPath ( root . right , path , key ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT path . pop ( ) NEW_LINE return False NEW_LINE DEDENT def minMaxNodeInPath ( root , a , b ) : NEW_LINE INDENT Path1 = [ ] NEW_LINE Path2 = [ ] NEW_LINE min1 , max1 = float ( ' inf ' ) , float ( ' - inf ' ) NEW_LINE min2 , max2 = float ( ' inf ' ) , float ( ' - inf ' ) NEW_LINE i , j = 0 , 0 NEW_LINE if ( FindPath ( root , Path1 , a ) and FindPath ( root , Path2 , b ) ) : NEW_LINE INDENT while i < len ( Path1 ) and i < len ( Path2 ) : NEW_LINE INDENT if Path1 [ i ] != Path2 [ i ] : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE j = i NEW_LINE while i < len ( Path1 ) : NEW_LINE INDENT if min1 > Path1 [ i ] : NEW_LINE INDENT min1 = Path1 [ i ] NEW_LINE DEDENT if max1 < Path1 [ i ] : NEW_LINE INDENT max1 = Path1 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while j < len ( Path2 ) : NEW_LINE INDENT if min2 > Path2 [ j ] : NEW_LINE INDENT min2 = Path2 [ j ] NEW_LINE DEDENT if max2 < Path2 [ j ] : NEW_LINE INDENT max2 = Path2 [ j ] NEW_LINE DEDENT j += 1 NEW_LINE DEDENT print ( " Min β = " , min ( min1 , min2 ) ) NEW_LINE print ( " Max β = " , max ( max1 , max2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Min = - 1 Max = - 1 " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE a , b = 5 , 14 NEW_LINE minMaxNodeInPath ( root , a , b ) NEW_LINE DEDENT |
Sum of all odd nodes in the path connecting two given nodes | Binary Tree node ; Utitlity function to create a Binary Tree node ; Function to check if there is a path from root to the given node . It also populates arr ' with the given path ; if root is None there is no path ; push the node ' s β value β in β ' arr ; if it is the required node return True ; else check whether the required node lies in the left subtree or right subtree of the current node ; required node does not lie either in the left or right subtree of the current node Thus , remove current node ' s β value β from β β ' arr 'and then return False ; Function to get the sum of odd nodes in the path between any two nodes in a binary tree ; vector to store the path of first node n1 from root ; vector to store the path of second node n2 from root ; Get intersection point ; Keep moving forward until no intersection is found ; calculate sum of ODD nodes from the path ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT node = Node ( ) NEW_LINE node . data = data NEW_LINE node . left = None NEW_LINE node . right = None NEW_LINE return node NEW_LINE DEDENT def getPath ( root , arr , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT arr . append ( root . data ) NEW_LINE if ( root . data == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( getPath ( root . left , arr , x ) or getPath ( root . right , arr , x ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT arr . pop ( ) NEW_LINE return False NEW_LINE DEDENT def sumOddNodes ( root , n1 , n2 ) : NEW_LINE INDENT path1 = [ ] NEW_LINE path2 = [ ] NEW_LINE getPath ( root , path1 , n1 ) NEW_LINE getPath ( root , path2 , n2 ) NEW_LINE intersection = - 1 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i != len ( path1 ) or j != len ( path2 ) ) : NEW_LINE INDENT if ( i == j and path1 [ i ] == path2 [ j ] ) : NEW_LINE INDENT i = i + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT else : NEW_LINE INDENT intersection = j - 1 NEW_LINE break NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE i = len ( path1 ) - 1 NEW_LINE while ( i > intersection ) : NEW_LINE INDENT if ( path1 [ i ] % 2 != 0 ) : NEW_LINE INDENT sum += path1 [ i ] NEW_LINE DEDENT i = i - 1 NEW_LINE DEDENT i = intersection NEW_LINE while ( i < len ( path2 ) ) : NEW_LINE INDENT if ( path2 [ i ] % 2 != 0 ) : NEW_LINE INDENT sum += path2 [ i ] NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT 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 . right = newNode ( 6 ) NEW_LINE node1 = 5 NEW_LINE node2 = 6 NEW_LINE print ( sumOddNodes ( root , node1 , node2 ) ) NEW_LINE |
Lowest Common Ancestor in Parent Array Representation | Maximum value in a node ; Function to find the Lowest common ancestor ; Create a visited vector and mark all nodes as not visited . ; Moving from n1 node till root and mark every accessed node as visited ; Move to the parent of node n1 ; For second node finding the first node common ; Insert function for Binary tree ; Driver Code ; Maximum capacity of binary tree ; Root marked | MAX = 1000 NEW_LINE def findLCA ( n1 , n2 , parent ) : NEW_LINE INDENT visited = [ False for i in range ( MAX ) ] NEW_LINE visited [ n1 ] = True NEW_LINE while ( parent [ n1 ] != - 1 ) : NEW_LINE INDENT visited [ n1 ] = True NEW_LINE n1 = parent [ n1 ] NEW_LINE DEDENT visited [ n1 ] = True NEW_LINE while ( visited [ n2 ] == False ) : NEW_LINE INDENT n2 = parent [ n2 ] NEW_LINE DEDENT return n2 NEW_LINE DEDENT def insertAdj ( parent , i , j ) : NEW_LINE INDENT parent [ i ] = j NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT parent = [ 0 for i in range ( MAX ) ] NEW_LINE parent [ 20 ] = - 1 NEW_LINE insertAdj ( parent , 8 , 20 ) NEW_LINE insertAdj ( parent , 22 , 20 ) NEW_LINE insertAdj ( parent , 4 , 8 ) NEW_LINE insertAdj ( parent , 12 , 8 ) NEW_LINE insertAdj ( parent , 10 , 12 ) NEW_LINE insertAdj ( parent , 14 , 12 ) NEW_LINE print ( findLCA ( 10 , 14 , parent ) ) NEW_LINE DEDENT |
Queries to find distance between two nodes of a Binary tree | Python3 program to find distance between two nodes for multiple queries ; A tree node structure ; Array to store level of each node ; Utility Function to store level of all nodes ; queue to hold tree node with level ; let root node be at level 0 ; Do level Order Traversal of tree ; Node p . first is on level p . second ; If left child exits , put it in queue with current_level + 1 ; If right child exists , put it in queue with current_level + 1 ; Stores Euler Tour ; index in Euler array ; Find Euler Tour ; store current node 's data ; If left node exists ; traverse left subtree ; store parent node 's data ; If right node exists ; traverse right subtree ; store parent node 's data ; checks for visited nodes ; Stores level of Euler Tour ; Stores indices of the first occurrence of nodes in Euler tour ; Preprocessing Euler Tour for finding LCA ; If node is not visited before ; Add to first occurrence ; Mark it visited ; Stores values and positions ; Utility function to find minimum of pair type values ; Utility function to build segment tree ; Utility function to find LCA ; Function to return distance between two nodes n1 and n2 ; Maintain original Values ; Get First Occurrence of n1 ; Get First Occurrence of n2 ; Swap if low > high ; Get position of minimum value ; Extract value out of Euler tour ; return calculated distance ; Build Tree ; Store Levels ; Find L and H array ; Build sparse table ; Driver Code ; Number of nodes ; Constructing tree given in the above figure ; Function to do all preprocessing | from collections import deque NEW_LINE from sys import maxsize as INT_MAX NEW_LINE MAX = 100001 NEW_LINE 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 level = [ 0 ] * MAX NEW_LINE def findLevels ( root : Node ) : NEW_LINE INDENT global level NEW_LINE if root is None : NEW_LINE INDENT return NEW_LINE DEDENT q = deque ( ) NEW_LINE q . append ( ( root , 0 ) ) NEW_LINE while q : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . popleft ( ) NEW_LINE level [ p [ 0 ] . data ] = p [ 1 ] NEW_LINE if p [ 0 ] . left : NEW_LINE INDENT q . append ( ( p [ 0 ] . left , p [ 1 ] + 1 ) ) NEW_LINE DEDENT if p [ 0 ] . right : NEW_LINE INDENT q . append ( ( p [ 0 ] . right , p [ 1 ] + 1 ) ) NEW_LINE DEDENT DEDENT DEDENT Euler = [ 0 ] * MAX NEW_LINE idx = 0 NEW_LINE def eulerTree ( root : Node ) : NEW_LINE INDENT global Euler , idx NEW_LINE idx += 1 NEW_LINE Euler [ idx ] = root . data NEW_LINE if root . left : NEW_LINE INDENT eulerTree ( root . left ) NEW_LINE idx += 1 NEW_LINE Euler [ idx ] = root . data NEW_LINE DEDENT if root . right : NEW_LINE INDENT eulerTree ( root . right ) NEW_LINE idx += 1 NEW_LINE Euler [ idx ] = root . data NEW_LINE DEDENT DEDENT vis = [ 0 ] * MAX NEW_LINE L = [ 0 ] * MAX NEW_LINE H = [ 0 ] * MAX NEW_LINE def preprocessEuler ( size : int ) : NEW_LINE INDENT global L , H , vis NEW_LINE for i in range ( 1 , size + 1 ) : NEW_LINE INDENT L [ i ] = level [ Euler [ i ] ] NEW_LINE if vis [ Euler [ i ] ] == 0 : NEW_LINE INDENT H [ Euler [ i ] ] = i NEW_LINE vis [ Euler [ i ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT seg = [ 0 ] * ( 4 * MAX ) NEW_LINE for i in range ( 4 * MAX ) : NEW_LINE INDENT seg [ i ] = [ 0 , 0 ] NEW_LINE DEDENT def minPair ( a : list , b : list ) -> list : NEW_LINE INDENT if a [ 0 ] <= b [ 0 ] : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT def buildSegTree ( low : int , high : int , pos : int ) -> list : NEW_LINE INDENT if low == high : NEW_LINE INDENT seg [ pos ] [ 0 ] = L [ low ] NEW_LINE seg [ pos ] [ 1 ] = low NEW_LINE return seg [ pos ] NEW_LINE DEDENT mid = low + ( high - low ) // 2 NEW_LINE buildSegTree ( low , mid , 2 * pos ) NEW_LINE buildSegTree ( mid + 1 , high , 2 * pos + 1 ) NEW_LINE seg [ pos ] = min ( seg [ 2 * pos ] , seg [ 2 * pos + 1 ] ) NEW_LINE DEDENT def LCA ( qlow : int , qhigh : int , low : int , high : int , pos : int ) -> list : NEW_LINE INDENT if qlow <= low and qhigh >= high : NEW_LINE INDENT return seg [ pos ] NEW_LINE DEDENT if qlow > high or qhigh < low : NEW_LINE INDENT return [ INT_MAX , 0 ] NEW_LINE DEDENT mid = low + ( high - low ) // 2 NEW_LINE return minPair ( LCA ( qlow , qhigh , low , mid , 2 * pos ) , LCA ( qlow , qhigh , mid + 1 , high , 2 * pos + 1 ) ) NEW_LINE DEDENT def findDistance ( n1 : int , n2 : int , size : int ) -> int : NEW_LINE INDENT prevn1 = n1 NEW_LINE prevn2 = n2 NEW_LINE n1 = H [ n1 ] NEW_LINE n2 = H [ n2 ] NEW_LINE if n2 < n1 : NEW_LINE INDENT n1 , n2 = n2 , n1 NEW_LINE DEDENT lca = LCA ( n1 , n2 , 1 , size , 1 ) [ 1 ] NEW_LINE lca = Euler [ lca ] NEW_LINE return level [ prevn1 ] + level [ prevn2 ] - 2 * level [ lca ] NEW_LINE DEDENT def preProcessing ( root : Node , N : int ) : NEW_LINE INDENT eulerTree ( root ) NEW_LINE findLevels ( root ) NEW_LINE preprocessEuler ( 2 * N - 1 ) NEW_LINE buildSegTree ( 1 , 2 * N - 1 , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 8 NEW_LINE 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 ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . left . right = Node ( 8 ) NEW_LINE preProcessing ( root , N ) NEW_LINE print ( " Dist ( 4 , β 5 ) β = " , findDistance ( 4 , 5 , 2 * N - 1 ) ) NEW_LINE print ( " Dist ( 4 , β 6 ) β = " , findDistance ( 4 , 6 , 2 * N - 1 ) ) NEW_LINE print ( " Dist ( 3 , β 4 ) β = " , findDistance ( 3 , 4 , 2 * N - 1 ) ) NEW_LINE print ( " Dist ( 2 , β 4 ) β = " , findDistance ( 2 , 4 , 2 * N - 1 ) ) NEW_LINE print ( " Dist ( 8 , β 5 ) β = " , findDistance ( 8 , 5 , 2 * N - 1 ) ) NEW_LINE DEDENT |
LCA for general or n | Maximum number of nodes is 100000 and nodes are numbered from 1 to 100000 ; Storing root to node path ; Storing the path from root to node ; Pushing current node into the path ; Node found ; Terminating the path ; This Function compares the path from root to ' a ' & root to ' b ' and returns LCA of a and b . Time Complexity : O ( n ) ; Trivial case ; Setting root to be first element in path ; Calculating path from root to a ; Calculating path from root to b ; Runs till path 1 & path 2 mathches ; Returns the last matching node in the paths ; Driver code ; Number of nodes | MAXN = 100001 NEW_LINE tree = [ 0 ] * MAXN NEW_LINE for i in range ( MAXN ) : NEW_LINE INDENT tree [ i ] = [ ] NEW_LINE DEDENT path = [ 0 ] * 3 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT path [ i ] = [ 0 ] * MAXN NEW_LINE DEDENT flag = False NEW_LINE def dfs ( cur : int , prev : int , pathNumber : int , ptr : int , node : int ) -> None : NEW_LINE INDENT global tree , path , flag NEW_LINE for i in range ( len ( tree [ cur ] ) ) : NEW_LINE INDENT if ( tree [ cur ] [ i ] != prev and not flag ) : NEW_LINE INDENT path [ pathNumber ] [ ptr ] = tree [ cur ] [ i ] NEW_LINE if ( tree [ cur ] [ i ] == node ) : NEW_LINE INDENT flag = True NEW_LINE path [ pathNumber ] [ ptr + 1 ] = - 1 NEW_LINE return NEW_LINE DEDENT dfs ( tree [ cur ] [ i ] , cur , pathNumber , ptr + 1 , node ) NEW_LINE DEDENT DEDENT DEDENT def LCA ( a : int , b : int ) -> int : NEW_LINE INDENT global flag NEW_LINE if ( a == b ) : NEW_LINE INDENT return a NEW_LINE DEDENT path [ 1 ] [ 0 ] = path [ 2 ] [ 0 ] = 1 NEW_LINE flag = False NEW_LINE dfs ( 1 , 0 , 1 , 1 , a ) NEW_LINE flag = False NEW_LINE dfs ( 1 , 0 , 2 , 1 , b ) NEW_LINE i = 0 NEW_LINE while ( path [ 1 ] [ i ] == path [ 2 ] [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT return path [ 1 ] [ i - 1 ] NEW_LINE DEDENT def addEdge ( a : int , b : int ) -> None : NEW_LINE INDENT tree [ a ] . append ( b ) NEW_LINE tree [ b ] . append ( a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 NEW_LINE addEdge ( 1 , 2 ) NEW_LINE addEdge ( 1 , 3 ) NEW_LINE addEdge ( 2 , 4 ) NEW_LINE addEdge ( 2 , 5 ) NEW_LINE addEdge ( 2 , 6 ) NEW_LINE addEdge ( 3 , 7 ) NEW_LINE addEdge ( 3 , 8 ) NEW_LINE print ( " LCA ( 4 , β 7 ) β = β { } " . format ( LCA ( 4 , 7 ) ) ) NEW_LINE print ( " LCA ( 4 , β 6 ) β = β { } " . format ( LCA ( 4 , 6 ) ) ) NEW_LINE DEDENT |
Tarjan 's off | Number of nodes in input tree ; COLOUR ' WHITE ' is assigned value 1 ; COLOUR ' BLACK ' is assigned value 2 ; A binary tree node has data , pointer to left child and a pointer to right child ; subset [ i ] . parent - . Holds the parent of node - ' i ' subset [ i ] . rank - . Holds the rank of node - ' i ' subset [ i ] . ancestor - . Holds the LCA queries answers subset [ i ] . child - . Holds one of the child of node - ' i ' if present , else - '0' subset [ i ] . sibling - . Holds the right - sibling of node - ' i ' if present , else - '0' subset [ i ] . color - . Holds the colour of node - ' i ' ; Structure to represent a query A query consists of ( L , R ) and we will process the queries offline a / c to Tarjan 's oflline LCA algorithm ; Helper function that allocates a new node with the given data and None left and right pointers . ; A utility function to make set ; A utility function to find set of an element i ( uses path compression technique ) ; Find root and make root as parent of i ( path compression ) ; A function that does union of two sets of x and y ( uses union by rank ) ; Attach smaller rank tree under root of high rank tree ( Union by Rank ) ; If ranks are same , then make one as root and increment its rank by one ; The main function that prints LCAs . u is root 's data. m is size of q[] ; Make Sets ; Initially , each node 's ancestor is the node itself. ; This while loop doesn 't run for more than 2 times as there can be at max. two children of a node ; This is basically an inorder traversal and we preprocess the arrays . child [ ] and sibling [ ] in " struct β subset " with the tree structure using this function . ; Recur on left child ; Note that the below two lines can also be this - subsets [ node . data ] . child = node . right . data ; subsets [ node . right . data ] . sibling = node . left . data ; This is because if both left and right children of node - ' i ' are present then we can store any of them in subsets [ i ] . child and correspondingly its sibling ; Recur on right child ; A function to initialise prior to pre - processing and LCA walk ; Initialising the structure with 0 's memset(subsets, 0, (V+1) * sizeof(struct subset)); ; Prints LCAs for given queries q [ 0. . m - 1 ] in a tree with given root ; Allocate memory for V subsets and nodes ; Creates subsets and colors them WHITE ; Preprocess the tree ; Perform a tree walk to process the LCA queries offline ; Driver code ; We construct a binary tree : - 1 / \ 2 3 / \ 4 5 ; LCA Queries to answer | V = 5 NEW_LINE WHITE = 1 NEW_LINE BLACK = 2 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT class subset : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . parent = 0 NEW_LINE self . rank = 0 NEW_LINE self . ancestor = 0 NEW_LINE self . child = 0 NEW_LINE self . sibling = 0 NEW_LINE self . color = 0 NEW_LINE DEDENT DEDENT class Query : NEW_LINE INDENT def __init__ ( self , L , R ) : NEW_LINE INDENT self . L = L NEW_LINE self . R = R NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT node = Node ( ) NEW_LINE node . data = data NEW_LINE node . left = node . right = None NEW_LINE return ( node ) NEW_LINE DEDENT def makeSet ( subsets , i ) : NEW_LINE INDENT if ( i < 1 or i > V ) : NEW_LINE INDENT return NEW_LINE DEDENT subsets [ i ] . color = WHITE NEW_LINE subsets [ i ] . parent = i NEW_LINE subsets [ i ] . rank = 0 NEW_LINE return NEW_LINE DEDENT def findSet ( subsets , i ) : NEW_LINE INDENT if ( subsets [ i ] . parent != i ) : NEW_LINE INDENT subsets [ i ] . parent = findSet ( subsets , subsets [ i ] . parent ) NEW_LINE DEDENT return subsets [ i ] . parent NEW_LINE DEDENT def unionSet ( subsets , x , y ) : NEW_LINE INDENT xroot = findSet ( subsets , x ) NEW_LINE yroot = findSet ( subsets , y ) NEW_LINE if ( subsets [ xroot ] . rank < subsets [ yroot ] . rank ) : NEW_LINE INDENT subsets [ xroot ] . parent = yroot NEW_LINE DEDENT elif ( subsets [ xroot ] . rank > subsets [ yroot ] . rank ) : NEW_LINE INDENT subsets [ yroot ] . parent = xroot NEW_LINE DEDENT else : NEW_LINE INDENT subsets [ yroot ] . parent = xroot NEW_LINE ( subsets [ xroot ] . rank ) += 1 NEW_LINE DEDENT DEDENT def lcaWalk ( u , q , m , subsets ) : NEW_LINE INDENT makeSet ( subsets , u ) NEW_LINE subsets [ findSet ( subsets , u ) ] . ancestor = u NEW_LINE child = subsets [ u ] . child NEW_LINE while ( child != 0 ) : NEW_LINE INDENT lcaWalk ( child , q , m , subsets ) NEW_LINE unionSet ( subsets , u , child ) NEW_LINE subsets [ findSet ( subsets , u ) ] . ancestor = u NEW_LINE child = subsets [ child ] . sibling NEW_LINE DEDENT subsets [ u ] . color = BLACK NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( q [ i ] . L == u ) : NEW_LINE INDENT if ( subsets [ q [ i ] . R ] . color == BLACK ) : NEW_LINE INDENT print ( " LCA ( % d β % d ) β - > β % d " % ( q [ i ] . L , q [ i ] . R , subsets [ findSet ( subsets , q [ i ] . R ) ] . ancestor ) ) NEW_LINE DEDENT DEDENT elif ( q [ i ] . R == u ) : NEW_LINE INDENT if ( subsets [ q [ i ] . L ] . color == BLACK ) : NEW_LINE INDENT print ( " LCA ( % d β % d ) β - > β % d " % ( q [ i ] . L , q [ i ] . R , subsets [ findSet ( subsets , q [ i ] . L ) ] . ancestor ) ) NEW_LINE DEDENT DEDENT DEDENT return NEW_LINE DEDENT def preprocess ( node , subsets ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT preprocess ( node . left , subsets ) NEW_LINE if ( node . left != None and node . right != None ) : NEW_LINE INDENT subsets [ node . data ] . child = node . left . data NEW_LINE subsets [ node . left . data ] . sibling = node . right . data NEW_LINE DEDENT elif ( ( node . left != None and node . right == None ) or ( node . left == None and node . right != None ) ) : NEW_LINE INDENT if ( node . left != None and node . right == None ) : NEW_LINE INDENT subsets [ node . data ] . child = node . left . data NEW_LINE DEDENT else : NEW_LINE INDENT subsets [ node . data ] . child = node . right . data NEW_LINE DEDENT DEDENT preprocess ( node . right , subsets ) NEW_LINE DEDENT def initialise ( subsets ) : NEW_LINE INDENT for i in range ( 1 , V + 1 ) : NEW_LINE INDENT subsets [ i ] . color = WHITE NEW_LINE DEDENT return NEW_LINE DEDENT def printLCAs ( root , q , m ) : NEW_LINE INDENT subsets = [ subset ( ) for _ in range ( V + 1 ) ] NEW_LINE initialise ( subsets ) NEW_LINE preprocess ( root , subsets ) NEW_LINE lcaWalk ( root . data , q , m , subsets ) 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 q = [ Query ( 5 , 4 ) , Query ( 1 , 3 ) , Query ( 2 , 3 ) ] NEW_LINE m = len ( q ) NEW_LINE printLCAs ( root , q , m ) NEW_LINE DEDENT |
Time Complexity and Space Complexity | Function to find a pair in the given array whose sum is equal to z ; Iterate through all the pairs ; Check if the sum of the pair ( a [ i ] , a [ j ] ) is equal to z ; Given Input ; Function Call | def findPair ( a , n , z ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i != j and a [ i ] + a [ j ] == z ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT a = [ 1 , - 2 , 1 , 0 , 5 ] NEW_LINE z = 0 NEW_LINE n = len ( a ) NEW_LINE if ( findPair ( a , n , z ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT |
Analysis of Algorithms | Big | Function to print all possible pairs ; Given array ; Store the size of the array ; Function Call | def printt ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT print ( a [ i ] , " " , a [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE printt ( a , n ) NEW_LINE |
Maximum sum obtained by dividing Array into several subarrays as per given conditions | Function to find the required answer ; Stores maximum sum ; Adding the difference of elements at ends of increasing subarray to the answer ; Input ; Functio calling | def maximumSum ( arr , N ) : NEW_LINE INDENT Sum = 0 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT Sum += ( arr [ i ] - arr [ i - 1 ] ) NEW_LINE DEDENT DEDENT return Sum ; NEW_LINE DEDENT arr = [ 1 , 5 , 3 ] ; NEW_LINE N = len ( arr ) NEW_LINE print ( maximumSum ( arr , N ) ) ; NEW_LINE |
The Slowest Sorting Algorithms | Function to implement stooge sort ; Base Case ; If first element is smaller than last element , swap them ; If there are more than 2 elements in the array ; Recursively sort the first 2 / 3 elements ; Recursively sort the last 2 / 3 elements ; Recursively sort the first 2 / 3 elements again ; Driver Code ; Function Call ; Display the sorted array | def stoogesort ( arr , l , h ) : NEW_LINE INDENT if ( l >= h ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( arr [ l ] > arr [ h ] ) : NEW_LINE INDENT temp = arr [ l ] NEW_LINE arr [ l ] = arr [ h ] NEW_LINE arr [ h ] = temp NEW_LINE DEDENT if ( h - l + 1 > 2 ) : NEW_LINE INDENT t = ( h - l + 1 ) // 3 NEW_LINE stoogesort ( arr , l , h - t ) NEW_LINE stoogesort ( arr , l + t , h ) NEW_LINE stoogesort ( arr , l , h - t ) NEW_LINE DEDENT DEDENT arr = [ 2 , 4 , 5 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE stoogesort ( arr , 0 , N - 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Determine winner of the Game by arranging balls in a row | Function to find the winner of the Game by arranging the balls in a row ; Check if small balls are greater or equal to the large ones ; X can place balls therefore scores n - 1 ; Condition if large balls are greater than small ; X can have m - 1 as a score since greater number of balls can only be adjacent ; Compare the score ; Driver Code ; Given number of small balls ( N ) and number of large balls ( M ) ; Function call | def findWinner ( n , m ) : NEW_LINE INDENT X = 0 ; NEW_LINE Y = 0 ; NEW_LINE if ( n >= m ) : NEW_LINE INDENT X = n - 1 ; NEW_LINE Y = m ; NEW_LINE DEDENT else : NEW_LINE INDENT X = m - 1 ; NEW_LINE Y = n ; NEW_LINE DEDENT if ( X > Y ) : NEW_LINE INDENT print ( " X " ) ; NEW_LINE DEDENT elif ( Y > X ) : NEW_LINE INDENT print ( " Y " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE m = 1 ; NEW_LINE findWinner ( n , m ) ; NEW_LINE DEDENT |
Check if Pascal 's Triangle is possible with a complete layer by using numbers upto N | Python3 program for the above approach ; Function to check if Pascaltriangle can be made by N integers ; Find X ; If x is integer ; Given number N ; Function call | import math NEW_LINE def checkPascaltriangle ( N ) : NEW_LINE INDENT x = ( math . sqrt ( 8 * N + 1 ) - 1 ) / 2 NEW_LINE if ( math . ceil ( x ) - x == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT N = 10 NEW_LINE checkPascaltriangle ( N ) NEW_LINE |
Count subarrays having sum of elements at even and odd positions equal | Function to count subarrays in which sum of elements at even and odd positions are equal ; Initialize variables ; Iterate over the array ; Check if position is even then add to sum hen add it to sum ; else subtract it to sum ; Increment the count if the sum equals 0 ; Print the count of subarrays ; Driver Code ; Given array arr [ ] ; Size of the array ; Function call | def countSubarrays ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT if ( ( j - i ) % 2 == 0 ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT sum -= arr [ j ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE countSubarrays ( arr , n ) NEW_LINE DEDENT |
Find position of non | Function to find the count of placing non - attacking rooks on the N x N chessboard ; Count of the Non - attacking rooks ; Printing lexographically smallest configuration ; Driver Code ; Function call | def findCountRooks ( row , col , n , k ) : NEW_LINE INDENT res = n - k NEW_LINE print ( res ) NEW_LINE ri = 0 NEW_LINE ci = 0 NEW_LINE while ( res > 0 ) : NEW_LINE INDENT while ( ri < k and row [ ri ] == 1 ) : NEW_LINE INDENT ri += 1 NEW_LINE DEDENT while ( ci < k and col [ ci ] == 1 ) : NEW_LINE INDENT ci += 1 NEW_LINE DEDENT print ( ( ri + 1 ) , " " , ( ci + 1 ) ) NEW_LINE ri += 1 NEW_LINE ci += 1 NEW_LINE res -= 1 NEW_LINE DEDENT DEDENT n = 4 NEW_LINE k = 2 NEW_LINE row = [ 1 , 2 ] NEW_LINE col = [ 4 , 2 ] NEW_LINE findCountRooks ( row , col , n , k ) NEW_LINE |
Check if a large number is divisible by a number which is a power of 2 | Python3 program for the above approach ; Function to check divisibility ; Calculate the number of digits in num ; Check if the length of the string is less than the powerOf2 then return false ; Check if the powerOf2 is 0 that means the given number is 1 and as every number is divisible by 1 so return true ; Find the number which is formed by the last n digits of the string where n = powerOf2 ; Check if the number formed is divisible by input num or not ; Driver Code ; Given number ; Function Call | from math import log2 NEW_LINE def checkIfDivisible ( string , num ) : NEW_LINE INDENT powerOf2 = int ( log2 ( num ) ) ; NEW_LINE if ( len ( string ) < powerOf2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( powerOf2 == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT number = 0 ; NEW_LINE length = len ( string ) ; NEW_LINE for i in range ( length - powerOf2 , length ) : NEW_LINE INDENT number += ( ( ord ( string [ i ] ) - ord ( '0' ) ) * ( 10 ** ( powerOf2 - 1 ) ) ) ; NEW_LINE powerOf2 -= 1 ; NEW_LINE DEDENT if ( number % num ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "213467756564" ; NEW_LINE num = 4 ; NEW_LINE if ( checkIfDivisible ( string , num ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Check if given permutation of 1 to N can be counted in clockwise or anticlockwise direction | Python3 program to check clockwise or counterclockwise order in an array ; Comparing the first and last value of array ; If the count is greater than 1 then it can 't be represented in required order ; Driver code | def check_order ( arr ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT if ( abs ( arr [ i + 1 ] - arr [ i ] ) > 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( abs ( arr [ 0 ] - arr [ len ( arr ) - 1 ] ) > 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( cnt > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 5 , 1 ] NEW_LINE if ( check_order ( arr ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Largest number M less than N such that XOR of M and N is even | Function to find the maximum possible value of M ; Edge case ; M = N - 2 is maximum possible value ; Driver code | def getM ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return n - 2 ; NEW_LINE DEDENT DEDENT n = 10 NEW_LINE print ( getM ( n ) ) NEW_LINE |
Maximize profit in buying and selling stocks with Rest condition | Python3 program for the above problem ; If there is only one day for buying and selling no profit can be made ; Array to store Maxprofit by resting on given day ; Array to store Maxprofit by buying or resting on the given day ; Array to store Maxprofit by selling on given day ; Initially there will 0 profit ; Buying on 1 st day results in negative profit ; zero profit since selling before buying isn 't possible ; max of profit on ( i - 1 ) th day by resting and profit on ( i - 1 ) th day by selling . ; max of profit by resting on ith day and buying on ith day . ; max of profit by selling on ith day ; maxprofit ; Driver Code | def maxProfit ( prices , n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT rest = [ 0 ] * n NEW_LINE hold = [ 0 ] * n NEW_LINE sold = [ 0 ] * n NEW_LINE rest [ 0 ] = 0 NEW_LINE hold [ 0 ] = - prices [ 0 ] NEW_LINE sold [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT rest [ i ] = max ( rest [ i - 1 ] , sold [ i - 1 ] ) NEW_LINE hold [ i ] = max ( hold [ i - 1 ] , rest [ i - 1 ] - prices [ i ] ) NEW_LINE sold [ i ] = hold [ i - 1 ] + prices [ i ] NEW_LINE DEDENT return max ( rest [ n - 1 ] , sold [ n - 1 ] ) NEW_LINE DEDENT price = [ 2 , 4 , 5 , 0 , 2 ] NEW_LINE n = len ( price ) NEW_LINE print ( maxProfit ( price , n ) ) NEW_LINE |
Count of subarrays of size K having at least one pair with absolute difference divisible by K | Function to return the required number of subarrays ; Return number of possible subarrays of length K ; Driver Code | def findSubarrays ( arr , N , K ) : NEW_LINE INDENT return N - K + 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 2 , 17 , 18 ] ; NEW_LINE K = 4 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( findSubarrays ( arr , N , K ) ) ; NEW_LINE DEDENT |
Maximum length of subarray such that all elements are equal in the subarray | Function to find the longest subarray with same element ; Check if the elements are same then we can increment the length ; Reinitialize j ; Compare the maximum length e with j ; Return max length ; Given list arr [ ] ; Function call | def longest_subarray ( arr , d ) : NEW_LINE INDENT ( i , j , e ) = ( 0 , 1 , 0 ) NEW_LINE for i in range ( d - 1 ) : NEW_LINE INDENT if arr [ i ] == arr [ i + 1 ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j = 1 NEW_LINE DEDENT if e < j : NEW_LINE INDENT e = j NEW_LINE DEDENT DEDENT return e NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( longest_subarray ( arr , N ) ) NEW_LINE |
Print all Strong numbers less than or equal to N | Store the factorial of all the digits from [ 0 , 9 ] ; Function to return true if number is strong or not ; Converting N to String so that can easily access all it 's digit ; sum will store summation of factorial of all digits of a number N ; Returns true of N is strong number ; Function to print all strong number till N ; Iterating from 1 to N ; Checking if a number is strong then print it ; Driver Code ; Given number ; Function call | factorial = [ 1 , 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880 ] NEW_LINE def isStrong ( N ) : NEW_LINE INDENT num = str ( N ) NEW_LINE sum = 0 NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT sum += factorial [ ord ( num [ i ] ) - ord ( '0' ) ] NEW_LINE DEDENT if sum == N : NEW_LINE return True NEW_LINE else : NEW_LINE return False NEW_LINE DEDENT def printStrongNumbers ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( isStrong ( i ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 1000 NEW_LINE printStrongNumbers ( N ) NEW_LINE DEDENT |
Count of pairs in a given range with sum of their product and sum equal to their concatenated number | Function for counting pairs ; Count possible values of Y ; Driver Code | def countPairs ( A , B ) : NEW_LINE INDENT countY = 0 NEW_LINE countX = ( B - A ) + 1 NEW_LINE next_val = 9 NEW_LINE while ( next_val <= B ) : NEW_LINE INDENT if ( next_val >= A ) : NEW_LINE INDENT countY += 1 NEW_LINE DEDENT next_val = next_val * 10 + 9 NEW_LINE DEDENT return ( countX * countY ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 1 NEW_LINE B = 16 NEW_LINE print ( countPairs ( A , B ) ) NEW_LINE DEDENT |
Minimum sprinklers required to water a rectangular park | Function to find the minimum number sprinklers required to water the park . ; General requirements of sprinklers ; if M is odd then add one additional sprinklers ; Driver code | def solve ( N , M ) : NEW_LINE INDENT ans = int ( ( N ) * int ( M / 2 ) ) NEW_LINE if ( M % 2 == 1 ) : NEW_LINE INDENT ans += int ( ( N + 1 ) / 2 ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT N = 5 NEW_LINE M = 3 NEW_LINE solve ( N , M ) NEW_LINE |
Queries to find frequencies of a string within specified substrings | Python3 Program to find frequency of a string K in a substring [ L , R ] in S ; Store the frequency of string for each index ; Compute and store frequencies for every index ; Driver Code | max_len = 100005 NEW_LINE cnt = [ 0 ] * max_len NEW_LINE def precompute ( s , K ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT cnt [ i + 1 ] = cnt [ i ] NEW_LINE if s [ i : len ( K ) + i ] == K : NEW_LINE INDENT cnt [ i + 1 ] += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ABCABCABABC " NEW_LINE K = " ABC " NEW_LINE precompute ( s , K ) NEW_LINE Q = [ [ 1 , 6 ] , [ 5 , 11 ] ] NEW_LINE for it in Q : NEW_LINE INDENT print ( cnt [ it [ 1 ] - 1 ] - cnt [ it [ 0 ] - 1 ] ) NEW_LINE DEDENT DEDENT |
XOR of elements in a given range with updates using Fenwick Tree | Returns XOR of arr [ 0. . index ] . This function assumes that the array is preprocessed and partial XORs of array elements are stored in BITree [ ] . ; Traverse ancestors of BITree [ index ] ; XOR current element of BIT to ans ; Update index to that of the parent node in getXor ( ) view by subtracting LSB ( Least Significant Bit ) ; Updates the Binary Index Tree by replacing all ancestors of index by their respective XOR with val ; Traverse all ancestors and XOR with ' val ' . ; XOR ' val ' to current node of BIT ; Update index to that of the parent node in updateBit ( ) view by adding LSB ( Least Significant Bit ) ; Constructs and returns a Binary Indexed Tree for the given array ; Create and initialize the Binary Indexed Tree ; Store the actual values in BITree [ ] using update ( ) ; Driver Code ; Create the Binary Indexed Tree ; Solve each query in Q ; Update the values of all ancestors of idx | def getXOR ( BITree , index ) : NEW_LINE INDENT ans = 0 NEW_LINE index += 1 NEW_LINE while ( index > 0 ) : NEW_LINE INDENT ans ^= BITree [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def updateBIT ( BITree , n , index , val ) : NEW_LINE INDENT index = index + 1 NEW_LINE while ( index <= n ) : NEW_LINE INDENT BITree [ index ] ^= val NEW_LINE index += index & ( - index ) NEW_LINE DEDENT DEDENT def constructBITree ( arr , n ) : NEW_LINE INDENT BITree = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT updateBIT ( BITree , n , i , arr [ i ] ) NEW_LINE DEDENT return BITree NEW_LINE DEDENT def rangeXor ( BITree , l , r ) : NEW_LINE INDENT return ( getXOR ( BITree , r ) ^ getXOR ( BITree , l - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 2 , 1 , 1 , 3 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( A ) NEW_LINE q = [ [ 1 , 0 , 9 ] , [ 2 , 3 , 6 ] , [ 2 , 5 , 5 ] , [ 2 , 8 , 1 ] , [ 1 , 0 , 9 ] ] NEW_LINE BITree = constructBITree ( A , n ) NEW_LINE for i in range ( len ( q ) ) : NEW_LINE INDENT id = q [ i ] [ 0 ] NEW_LINE if ( id == 1 ) : NEW_LINE INDENT L = q [ i ] [ 1 ] NEW_LINE R = q [ i ] [ 2 ] NEW_LINE print ( " XOR β of β elements β in β " " given β range β is β " , rangeXor ( BITree , L , R ) ) NEW_LINE DEDENT else : NEW_LINE INDENT idx = q [ i ] [ 1 ] NEW_LINE val = q [ i ] [ 2 ] NEW_LINE A [ idx ] ^= val NEW_LINE updateBIT ( BITree , n , idx , val ) NEW_LINE DEDENT DEDENT DEDENT |
Count of Double Prime numbers in a given range L to R | Array to make Sieve where arr [ i ] = 0 indicates non prime and arr [ i ] = 1 indicates prime ; Array to find double prime ; Function to find the number double prime numbers in range ; Assume all numbers as prime ; Check if the number is prime ; Check for multiples of i ; Make all multiples of ith prime as non - prime ; Check if number at ith position is prime then increment count ; Indicates count of numbers from 1 to i that are also prime and hence double prime ; If number is not a double prime ; Finding cumulative sum ; Driver code | arr = [ 0 ] * 1000001 NEW_LINE dp = [ 0 ] * 1000001 NEW_LINE def count ( ) : NEW_LINE INDENT maxN = 1000000 NEW_LINE for i in range ( 0 , maxN ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT arr [ 0 ] = 0 NEW_LINE arr [ 1 ] = 0 NEW_LINE i = 2 NEW_LINE while ( i * i <= maxN ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT for j in range ( 2 * i , maxN + 1 , i ) : NEW_LINE INDENT arr [ j ] = 0 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 0 , maxN + 1 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( arr [ cnt ] == 1 ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( 0 , maxN + 1 ) : NEW_LINE INDENT dp [ i ] += dp [ i - 1 ] NEW_LINE DEDENT DEDENT L = 4 NEW_LINE R = 12 NEW_LINE count ( ) NEW_LINE print ( dp [ R ] - dp [ L - 1 ] ) NEW_LINE |
Count of ungrouped characters after dividing a string into K groups of distinct characters | Python3 code to implement the above approach ; Create array where index represents alphabets ; Fill count of every alphabet to corresponding array index ; Count for every element how much is exceeding from no . of groups then sum them ; Print answer ; Driver code | def findUngroupedElement ( s , k ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE b = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT p = s [ i ] NEW_LINE b [ ord ( p ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT sum = 0 ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( b [ i ] > k ) : NEW_LINE INDENT sum += b [ i ] - k NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT s = " stayinghomesaveslife " NEW_LINE k = 1 NEW_LINE findUngroupedElement ( s , k ) NEW_LINE |
Generate an array of given size with equal count and sum of odd and even numbers | Function to find the array such that the array contains the same count of even and odd elements with equal sum of even and odd elements ; Length of array which is not divisible by 4 is unable to form such array ; Loop to find the resulted array containing the same count of even and odd elements ; Find the total sum of even elements ; Find the total sum of odd elements ; Find the difference between the total sum of even and odd elements ; The difference will be added in the last odd element ; Driver Code | def findSolution ( N ) : NEW_LINE INDENT if ( N % 4 != 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = 0 NEW_LINE sum_odd = 0 NEW_LINE sum_even = 0 NEW_LINE result = [ 0 ] * N NEW_LINE for i in range ( 0 , N , 2 ) : NEW_LINE INDENT temp += 2 NEW_LINE result [ i + 1 ] = temp NEW_LINE sum_even += result [ i + 1 ] NEW_LINE result [ i ] = temp - 1 NEW_LINE sum_odd += result [ i ] NEW_LINE DEDENT diff = sum_even - sum_odd NEW_LINE result [ N - 2 ] += diff NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( result [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 8 ; NEW_LINE findSolution ( N ) NEW_LINE |
Number of ways to place two queens on a N * N chess | Python3 implementation to find the number of ways to place two queens on the N * N chess board ; Function to find number of valid positions for two queens in the N * N chess board ; Driver code ; Function call | import math NEW_LINE def possiblePositions ( n ) : NEW_LINE INDENT term1 = pow ( n , 4 ) ; NEW_LINE term2 = pow ( n , 3 ) ; NEW_LINE term3 = pow ( n , 2 ) ; NEW_LINE term4 = n / 3 ; NEW_LINE ans = ( ( math . ceil ( term1 ) ) / 2 - ( math . ceil ( 5 * term2 ) ) / 3 + ( math . ceil ( 3 * term3 ) ) / 2 - term4 ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE ans = possiblePositions ( n ) NEW_LINE print ( int ( ans ) ) NEW_LINE DEDENT |
Group all co | Function to group the mutually co - prime numbers into one group ; Loop for the numbers less than the 4 ; Integers 1 , 2 and 3 can be grouped into one group ; Consecutive even and odd numbers ; Driver Code ; Function Call | def mutually_coprime ( n ) : NEW_LINE INDENT if ( n <= 3 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( j , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 1 , 2 , 3 ) NEW_LINE for j in range ( 4 , n , 2 ) : NEW_LINE INDENT print ( j , ( j + 1 ) ) NEW_LINE DEDENT if ( n % 2 == 0 ) : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 9 NEW_LINE mutually_coprime ( n ) NEW_LINE DEDENT |
Maximum sum subset having equal number of positive and negative elements | Function to find maximum sum subset with equal number of positive and negative elements ; Loop to store the positive and negative elements in two different array ; Sort both the array ; Pointers starting from the highest elements ; Find pairs having sum greater than zero ; Driver code | def findMaxSum ( arr , n ) : NEW_LINE INDENT a = [ ] NEW_LINE b = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT a . append ( arr [ i ] ) NEW_LINE DEDENT elif ( arr [ i ] < 0 ) : NEW_LINE INDENT b . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE p = len ( a ) - 1 NEW_LINE q = len ( b ) - 1 NEW_LINE s = 0 NEW_LINE while ( p >= 0 and q >= 0 ) : NEW_LINE INDENT if ( a [ p ] + b [ q ] > 0 ) : NEW_LINE INDENT s = s + a [ p ] + b [ q ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT p = p - 1 NEW_LINE q = q - 1 NEW_LINE DEDENT return s NEW_LINE DEDENT arr1 = [ 1 , - 2 , 3 , 4 , - 5 , 8 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( findMaxSum ( arr1 , n1 ) ) NEW_LINE |
Print the nodes with a prime degree in given Prufer sequence of a Tree | Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to print the nodes with prime degree in the tree whose Prufer sequence is given ; Hash - table to mark the degree of every node ; Initially let all the degrees be 1 ; Increase the count of the degree ; Print the nodes with prime degree ; Driver Code | def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= p_size ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def PrimeDegreeNodes ( prufer , n ) : NEW_LINE INDENT nodes = n + 2 NEW_LINE prime = [ True ] * ( nodes + 1 ) NEW_LINE SieveOfEratosthenes ( prime , nodes + 1 ) NEW_LINE degree = [ 0 ] * ( n + 2 + 1 ) ; NEW_LINE for i in range ( 1 , nodes + 1 ) : NEW_LINE INDENT degree [ i ] = 1 ; NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT degree [ prufer [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 1 , nodes + 1 ) : NEW_LINE INDENT if prime [ degree [ i ] ] : NEW_LINE INDENT print ( i , end = ' β ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 4 , 1 , 3 , 4 ] NEW_LINE n = len ( a ) NEW_LINE PrimeDegreeNodes ( a , n ) NEW_LINE DEDENT |
Find K 'th smallest number such that A + B = A | B | Function to find k 'th smallest number such that A + B = A | B ; res will store final answer ; Skip when j ' th β position β β has β 1 β in β binary β representation β β as β in β res , β j ' th position will be 0. ; j 'th bit is set ; If i ' th β bit β of β k β is β 1 β β and β i ' th bit of j is 0 then set i 'th bit in res. ; Proceed to next bit ; Driver Code | def kthSmallest ( a , k ) : NEW_LINE INDENT res = 0 NEW_LINE j = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT while ( j < 32 and ( a & ( 1 << j ) ) ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( k & ( 1 << i ) ) : NEW_LINE INDENT res |= ( 1 << j ) NEW_LINE DEDENT j += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT a = 5 NEW_LINE k = 3 NEW_LINE print ( kthSmallest ( a , k ) ) NEW_LINE |
Nodes with prime degree in an undirected Graph | Python3 implementation of the above approach ; To store Prime Numbers ; Function to find the prime numbers till 10 ^ 5 ; Traverse all multiple of i and make it false ; Function to print the nodes having prime degree ; To store Adjacency List of a Graph ; Make Adjacency List ; To precompute prime numbers till 10 ^ 5 ; Traverse each vertex ; Find size of Adjacency List ; If length of Adj [ i ] is Prime then print it ; Driver code ; Vertices and Edges ; Edges ; Function Call | n = 10005 ; NEW_LINE Prime = [ True for i in range ( n + 1 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT i = 2 NEW_LINE Prime [ 0 ] = Prime [ 1 ] = False ; NEW_LINE while i * i <= 10005 : NEW_LINE INDENT if ( Prime [ i ] ) : NEW_LINE INDENT for j in range ( 2 * i , 10005 ) : NEW_LINE INDENT Prime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def primeDegreeNodes ( N , M , edges ) : NEW_LINE INDENT Adj = [ [ ] for i in range ( N + 1 ) ] ; NEW_LINE for i in range ( M ) : NEW_LINE INDENT x = edges [ i ] [ 0 ] ; NEW_LINE y = edges [ i ] [ 1 ] ; NEW_LINE Adj [ x ] . append ( y ) ; NEW_LINE Adj [ y ] . append ( x ) ; NEW_LINE DEDENT SieveOfEratosthenes ( ) ; NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT x = len ( Adj [ i ] ) ; NEW_LINE if ( Prime [ x ] ) : NEW_LINE INDENT print ( i , end = ' β ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE M = 6 NEW_LINE edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] , [ 2 , 3 ] , [ 2 , 4 ] , [ 3 , 4 ] ] ; NEW_LINE primeDegreeNodes ( N , M , edges ) ; NEW_LINE DEDENT |
Number of ways to color N | Python3 program for the above approach ; Recursive function to count the ways ; Base case ; Initialise answer to 0 ; Color each uncolored block according to the given condition ; If any block is uncolored ; Check if adjacent blocks are colored or not ; Color the block ; recursively iterate for next uncolored block ; Uncolored for the next recursive call ; Return the final count ; Function to count the ways to color block ; Mark which blocks are colored in each recursive step ; Function call to count the ways ; Driver Code ; Number of blocks ; Number of colored blocks ; Function call | mod = 1000000007 NEW_LINE def countWays ( colored , count , n ) : NEW_LINE INDENT if ( count == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( colored [ i ] == 0 ) : NEW_LINE INDENT if ( colored [ i - 1 ] == 1 or colored [ i + 1 ] == 1 ) : NEW_LINE INDENT colored [ i ] = 1 NEW_LINE answer = ( ( answer + countWays ( colored , count + 1 , n ) ) % mod ) NEW_LINE colored [ i ] = 0 NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT def waysToColor ( arr , n , k ) : NEW_LINE INDENT colored = [ 0 ] * ( n + 2 ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT colored [ arr [ i ] ] = 1 NEW_LINE DEDENT return countWays ( colored , k , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE K = 3 NEW_LINE arr = [ 1 , 2 , 6 ] NEW_LINE print ( waysToColor ( arr , N , K ) ) NEW_LINE DEDENT |
Shortest Palindromic Substring | Function return the shortest palindromic substring ; Finding the smallest character present in the string ; Driver code | def ShortestPalindrome ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = s [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ans = min ( ans , s [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE print ( ShortestPalindrome ( s ) ) NEW_LINE |
Maximum length Subsequence with alternating sign and maximum Sum | Function to find the subsequence with alternating sign having maximum size and maximum sum . ; Find whether each element is positive or negative ; Find the required subsequence ; Find the maximum element in the specified range ; print the result ; Driver code ; array declaration ; size of array | def findSubsequence ( arr , n ) : NEW_LINE INDENT sign = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT sign [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sign [ i ] = - 1 NEW_LINE DEDENT DEDENT k = 0 NEW_LINE result = [ 0 ] * n NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT cur = arr [ i ] NEW_LINE j = i NEW_LINE while ( j < n and sign [ i ] == sign [ j ] ) : NEW_LINE INDENT cur = max ( cur , arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT result [ k ] = cur NEW_LINE k += 1 NEW_LINE i = j - 1 NEW_LINE i += 1 NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT print ( result [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 4 , 9 , 4 , 11 , - 5 , - 17 , 9 , - 3 , - 5 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE findSubsequence ( arr , n ) NEW_LINE DEDENT |
Longest Palindrome in a String formed by concatenating its prefix and suffix | Function to check whether the string is a palindrome ; Reverse the string to compare with the original string ; Check if both are same ; Function to find the longest palindrome in a string formed by concatenating its prefix and suffix ; Length of the string ; Finding the length upto which the suffix and prefix forms a palindrome together ; Check whether the string has prefix and suffix substrings which are palindromes . ; Removing the suffix and prefix substrings which already forms a palindrome and storing them in separate strings ; Check all prefix substrings in the remaining string str ; Check if the prefix substring is a palindrome ; If the prefix substring is a palindrome then check if it is of maximum length so far ; Check all the suffix substrings in the remaining string str ; Check if the suffix substring is a palindrome ; If the suffix substring is a palindrome then check if it is of maximum length so far ; Combining all the thee parts of the answer ; Driver code | def isPalindrome ( r ) : NEW_LINE INDENT p = r NEW_LINE p = " " . join ( reversed ( p ) ) NEW_LINE return ( r == p ) NEW_LINE DEDENT def PrefixSuffixPalindrome ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE length = 0 NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if ( st [ i ] != st [ n - i - 1 ] ) : NEW_LINE INDENT length = i NEW_LINE break NEW_LINE DEDENT DEDENT prefix = " " NEW_LINE suffix = " " NEW_LINE midPal = " " NEW_LINE prefix = st [ : length ] NEW_LINE suffix = st [ n - length : ] NEW_LINE st = st [ length : n - 2 * length + length ] NEW_LINE for i in range ( 1 , len ( st ) + 1 ) : NEW_LINE INDENT y = st [ 0 : i ] NEW_LINE if ( isPalindrome ( y ) ) : NEW_LINE INDENT if ( len ( midPal ) < len ( y ) ) : NEW_LINE INDENT midPal = y NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , len ( st ) + 1 ) : NEW_LINE INDENT y = st [ len ( st ) - i ] NEW_LINE if ( isPalindrome ( y ) ) : NEW_LINE INDENT if ( len ( midPal ) < len ( y ) ) : NEW_LINE INDENT midPal = y NEW_LINE DEDENT DEDENT DEDENT answer = prefix + midPal + suffix NEW_LINE return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " abcdfdcecba " ; NEW_LINE print ( PrefixSuffixPalindrome ( st ) ) NEW_LINE DEDENT |
Minimize the maximum difference between adjacent elements in an array | Python3 implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Initialising the minimum difference ; Traversing over subsets in iterative manner ; Number of elements to be taken in the subset ON bits of i represent elements not to be removed ; If the removed set is of size k ; Creating the new array after removing elements ; Maximum difference of adjacent elements of remaining array ; Driver Code | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) NEW_LINE def minimumAdjacentDifference ( a , n , k ) : NEW_LINE INDENT minDiff = INT_MAX ; NEW_LINE for i in range ( 1 << n ) : NEW_LINE INDENT cnt = bin ( i ) . count ( '1' ) ; NEW_LINE if ( cnt == n - k ) : NEW_LINE INDENT temp = [ ] ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( i & ( 1 << j ) ) != 0 ) : NEW_LINE INDENT temp . append ( a [ j ] ) ; NEW_LINE DEDENT DEDENT maxDiff = INT_MIN ; NEW_LINE for j in range ( len ( temp ) - 1 ) : NEW_LINE INDENT maxDiff = max ( maxDiff , temp [ j + 1 ] - temp [ j ] ) ; NEW_LINE DEDENT minDiff = min ( minDiff , maxDiff ) ; NEW_LINE DEDENT DEDENT return minDiff ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE k = 2 ; NEW_LINE a = [ 3 , 7 , 8 , 10 , 14 ] ; NEW_LINE print ( minimumAdjacentDifference ( a , n , k ) ) ; NEW_LINE DEDENT |
Minimize the maximum difference between adjacent elements in an array | Python3 implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Initialising the minimum difference ; Iterating over all subarrays of size n - k ; Maximum difference after removing elements ; Minimum Adjacent Difference ; Driver Code | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) ; NEW_LINE def minimumAdjacentDifference ( a , n , k ) : NEW_LINE INDENT minDiff = INT_MAX ; NEW_LINE for i in range ( k + 1 ) : NEW_LINE INDENT maxDiff = INT_MIN ; NEW_LINE for j in range ( n - k - 1 ) : NEW_LINE INDENT for p in range ( i , i + j + 1 ) : NEW_LINE INDENT maxDiff = max ( maxDiff , a [ p + 1 ] - a [ p ] ) ; NEW_LINE DEDENT DEDENT minDiff = min ( minDiff , maxDiff ) ; NEW_LINE DEDENT return minDiff ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE k = 2 ; NEW_LINE a = [ 3 , 7 , 8 , 10 , 14 ] ; NEW_LINE print ( minimumAdjacentDifference ( a , n , k ) ) ; NEW_LINE DEDENT |
Minimize the maximum difference between adjacent elements in an array | Python3 implementation to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Function to find the minimum different in the subarrays of size K in the array ; Create a Double Ended Queue , Qi that will store indexes of array elements , queue will store indexes of useful elements in every window ; Process first k ( or first window ) elements of array ; For every element , the previous smaller elements are useless so remove them from Qi ; Add new element at rear of queue ; Process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; The element at the front of the queue is the largest element of previous window ; Remove the elements which are out of this window ; Remove all elements smaller than the currently being added element ( remove useless elements ) ; Add current element at the rear of Qi ; Compare the maximum element of last window ; Function to find the minimum of the maximum difference of the adjacent elements after removing K elements from the array ; Create the difference array ; Find minimum of all maximum of subarray sizes n - k - 1 ; Driver code | import sys NEW_LINE def findKMin ( arr , n , k ) : NEW_LINE INDENT Qi = [ ] NEW_LINE i = 0 NEW_LINE for j in range ( k ) : NEW_LINE INDENT while ( ( len ( Qi ) != 0 ) and arr [ i ] >= arr [ Qi [ - 1 ] ] ) : NEW_LINE Qi . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT minDiff = sys . maxsize ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT minDiff = min ( minDiff , arr [ Qi [ 0 ] ] ) NEW_LINE while ( ( len ( Qi ) != 0 ) and Qi [ 0 ] <= i - k ) : NEW_LINE INDENT Qi . pop ( 0 ) NEW_LINE DEDENT while ( ( len ( Qi ) != 0 ) and arr [ i ] >= arr [ Qi [ - 1 ] ] ) : NEW_LINE INDENT Qi . pop ( ) NEW_LINE DEDENT Qi . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT minDiff = min ( minDiff , arr [ Qi [ 0 ] ] ) NEW_LINE return minDiff NEW_LINE DEDENT def minimumAdjacentDifference ( a , n , k ) : NEW_LINE INDENT diff = [ 0 for i in range ( n - 1 ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT diff [ i ] = a [ i + 1 ] - a [ i ] NEW_LINE DEDENT answer = findKMin ( diff , n - 1 , n - k - 1 ) NEW_LINE return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE a = [ 3 , 7 , 8 , 10 , 14 ] NEW_LINE print ( minimumAdjacentDifference ( a , n , k ) ) NEW_LINE DEDENT |
Minimum elements inserted in a sorted array to form an Arithmetic progression | Function to find the greatest common divisor of two numbers ; Function to find the minimum the minimum number of elements required to be inserted into array ; Difference array of consecutive elements of the array ; GCD of the difference array ; Loop to calculate the minimum number of elements required ; Driver Code ; Function calling | def gcdFunc ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcdFunc ( b , a % b ) NEW_LINE DEDENT def findMinimumElements ( a , n ) : NEW_LINE INDENT b = [ 0 ] * ( n - 1 ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT b [ i - 1 ] = a [ i ] - a [ i - 1 ] NEW_LINE DEDENT gcd = b [ 0 ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT gcd = gcdFunc ( gcd , b [ i ] ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans += ( b [ i ] // gcd ) - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr1 = [ 1 , 6 , 8 , 10 , 14 , 16 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( findMinimumElements ( arr1 , n1 ) ) NEW_LINE |
Check if a Sequence is a concatenation of two permutations | Function to Check if a given sequence is a concatenation of two permutations or not ; Computing the sum of all the elements in the array ; Computing the prefix sum for all the elements in the array ; Iterating through the i from lengths 1 to n - 1 ; Sum of first i + 1 elements ; Sum of remaining n - i - 1 elements ; Lengths of the 2 permutations ; Checking if the sums satisfy the formula or not ; Driver code | def checkPermutation ( arr , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT prefix = [ 0 ] * ( n + 1 ) ; NEW_LINE prefix [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT lsum = prefix [ i ] ; NEW_LINE rsum = sum - prefix [ i ] ; NEW_LINE l_len = i + 1 NEW_LINE r_len = n - i - 1 ; NEW_LINE if ( ( ( 2 * lsum ) == ( l_len * ( l_len + 1 ) ) ) and ( ( 2 * rsum ) == ( r_len * ( r_len + 1 ) ) ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 4 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkPermutation ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Find a N | Function that prthe answer ; if n == 1 then it is not possible ; loop to n - 1 times ; print as last digit of the number ; Driver code ; Function call | def findTheNumber ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( " Impossible " ) NEW_LINE return NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT print ( "5" , end = " " ) NEW_LINE DEDENT print ( "4" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE findTheNumber ( n ) NEW_LINE DEDENT |
Queries to check whether bitwise AND of a subarray is even or odd | Python implementation of the approach ; Function to precompute the count of even and odd numbers ; If the current element is odd then put 1 at odd [ i ] ; If the current element is even then put 1 at even [ i ] ; Taking the prefix sums of these two arrays so we can get the count of even and odd numbers in a range [ L , R ] in O ( 1 ) ; Function that returns True if the bitwise AND of the subarray a [ L ... R ] is odd ; cnt will store the count of odd numbers in the range [ L , R ] ; Check if all the numbers in the range are odd or not ; Function to perform the queries ; Perform queries ; Driver code ; Queries | MAXN = 1000005 ; NEW_LINE even = [ 0 ] * MAXN ; NEW_LINE odd = [ 0 ] * MAXN ; NEW_LINE def precompute ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT odd [ i ] = 1 ; NEW_LINE DEDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even [ i ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT even [ i ] = even [ i ] + even [ i - 1 ] ; NEW_LINE odd [ i ] = odd [ i ] + odd [ i - 1 ] ; NEW_LINE DEDENT DEDENT def isOdd ( L , R ) : NEW_LINE INDENT cnt = odd [ R ] ; NEW_LINE if ( L > 0 ) : NEW_LINE INDENT cnt -= odd [ L - 1 ] ; NEW_LINE DEDENT if ( cnt == R - L + 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def performQueries ( a , n , q , m ) : NEW_LINE INDENT precompute ( a , n ) ; NEW_LINE for i in range ( m ) : NEW_LINE INDENT L = q [ i ] [ 0 ] ; NEW_LINE R = q [ i ] [ 1 ] ; NEW_LINE if ( isOdd ( L , R ) ) : NEW_LINE INDENT print ( " Odd " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Even " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 1 , 5 , 7 , 6 , 8 , 9 ] ; NEW_LINE n = len ( a ) ; NEW_LINE q = [ [ 0 , 2 ] , [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 6 ] ] ; NEW_LINE m = len ( q ) ; NEW_LINE performQueries ( a , n , q , m ) ; NEW_LINE DEDENT |
Find distinct integers for a triplet with given product | Python3 implementation of the approach ; Function to find the required triplets ; To store the factors ; Find factors in sqrt ( x ) time ; Choose a factor ; Choose another factor ; These conditions need to be met for a valid triplet ; Print the valid triplet ; Triplet found ; Triplet not found ; Driver code | from math import sqrt NEW_LINE def findTriplets ( x ) : NEW_LINE INDENT fact = [ ] ; NEW_LINE factors = set ( ) ; NEW_LINE for i in range ( 2 , int ( sqrt ( x ) ) ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT fact . append ( i ) ; NEW_LINE if ( x / i != i ) : NEW_LINE INDENT fact . append ( x // i ) ; NEW_LINE DEDENT factors . add ( i ) ; NEW_LINE factors . add ( x // i ) ; NEW_LINE DEDENT DEDENT found = False ; NEW_LINE k = len ( fact ) ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT a = fact [ i ] ; NEW_LINE for j in range ( k ) : NEW_LINE INDENT b = fact [ j ] ; NEW_LINE if ( ( a != b ) and ( x % ( a * b ) == 0 ) and ( x / ( a * b ) != a ) and ( x / ( a * b ) != b ) and ( x / ( a * b ) != 1 ) ) : NEW_LINE INDENT print ( a , b , x // ( a * b ) ) ; NEW_LINE found = True ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( found ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( not found ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 105 ; NEW_LINE findTriplets ( x ) ; NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.