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 sto...
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 ...
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 ; C...
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 IN...
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 poi...
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 = ( pt...
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 rot...
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 (...
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_cou...
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 INDEN...
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 . app...
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...
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 m...
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 == ...
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 )...
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 ) ) // ...
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...
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 ...
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...
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 =...
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 ...
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...
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...
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 IND...
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 t...
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 ] == ...
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 t...
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 (...
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 ] ...
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_LIN...
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 -> da...
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...
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...
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 IN...
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_LI...
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 ...
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...
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...
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 " ) ) N...
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 ; Cha...
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...
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 ne...
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...
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 o...
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_re...
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 . ; Poi...
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...
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 i...
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 ...
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 el...
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...
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 ; Fun...
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 = ...
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 c...
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 ) ...
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...
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 alrea...
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 INDEN...
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 ...
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_L...
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 nod...
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 ...
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 giv...
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 D...
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 N...
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 = " - >...
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 a...
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 == ...
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 ; ...
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 == ...
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 wh...
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 retu...
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 ; I...
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 = f...
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 node...
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...
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 t...
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 g...
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 prim...
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 (...
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 - Proce...
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...
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...
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 ( ...
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 valu...
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 ) N...
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 ; i...
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...
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 th...
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...
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 O...
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 findLev...
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 ...
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 ...
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...
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...
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 ) N...
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 ( maximumSu...
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 a...
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 stoogeso...
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 sinc...
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 ...
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 ...
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 ) : NE...
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_LIN...
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 numbe...
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 ( st...
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 ) ...
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 ...
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 ]...
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_LI...
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 stron...
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...
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 __n...
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__ == " _ _...
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...
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 whil...
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 multiple...
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 ) : ...
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 s...
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 ...
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 resulte...
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 su...
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_LIN...
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_L...
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 ha...
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 ( ...
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 ...
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 ...
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 ▁...
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...
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 L...
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 ] = F...
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 f...
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...
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 ; Drive...
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 : ...
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 ; Leng...
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 ...
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 ...
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 =...
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 ...
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 r...
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 , ...
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 ...
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 arr...
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 ...
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 fi...
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 f...
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 findTheN...
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 arr...
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 DED...
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 ; T...
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_LIN...