text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Check linked list with a loop is palindrome or not | C ++ program to check if a linked list with loop is palindrome or not . ; Link list node ; Function to find loop starting node . loop_node -- > Pointer to one of the loop nodes head -- > Pointer to the start node of the linked list ; Count the number of nodes in loop ; Fix one pointer to head ; And the other pointer to k nodes after head ; Move both pointers at the same pace , they will meet at loop starting node ; This function detects and find loop starting node in the list ; Start traversing list and detect loop ; If slow_p and fast_p meet then find the loop starting node ; Return starting node of loop ; Utility function to check if a linked list with loop is palindrome with given starting point . ; Traverse linked list until last node is equal to loop_start and store the elements till start in a stack ; Traverse linked list until last node is equal to loop_start second time ; Compare data of node with the top of stack If equal then continue ; Else return false ; Return true if linked list is palindrome ; Function to find if linked list is palindrome or not ; Find the loop starting node ; Check if linked list is palindrome ; Driver program to test above function ; Create a loop for testing | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * getLoopstart ( Node * loop_node , Node * head ) { Node * ptr1 = loop_node ; Node * ptr2 = loop_node ; unsigned int k = 1 , i ; while ( ptr1 -> next != ptr2 ) { ptr1 = ptr1 -> next ; k ++ ; } ptr1 = head ; ptr2 = head ; for ( i = 0 ; i < k ; i ++ ) ptr2 = ptr2 -> next ; while ( ptr2 != ptr1 ) { ptr1 = ptr1 -> next ; ptr2 = ptr2 -> next ; } return ptr1 ; } Node * detectAndgetLoopstarting ( Node * head ) { Node * slow_p = head , * fast_p = head , * loop_start ; while ( slow_p && fast_p && fast_p -> next ) { slow_p = slow_p -> next ; fast_p = fast_p -> next -> next ; if ( slow_p == fast_p ) { loop_start = getLoopstart ( slow_p , head ) ; break ; } } return loop_start ; } bool isPalindromeUtil ( Node * head , Node * loop_start ) { Node * ptr = head ; stack < int > s ; int count = 0 ; while ( ptr != loop_start count != 1 ) { s . push ( ptr -> data ) ; if ( ptr == loop_start ) count = 1 ; ptr = ptr -> next ; } ptr = head ; count = 0 ; while ( ptr != loop_start count != 1 ) { if ( ptr -> data == s . top ( ) ) s . pop ( ) ; else return false ; if ( ptr == loop_start ) count = 1 ; ptr = ptr -> next ; } return true ; } bool isPalindrome ( Node * head ) { Node * loop_start = detectAndgetLoopstarting ( head ) ; return isPalindromeUtil ( head , loop_start ) ; } Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> next = NULL ; return temp ; } int main ( ) { Node * head = newNode ( 50 ) ; head -> next = newNode ( 20 ) ; head -> next -> next = newNode ( 15 ) ; head -> next -> next -> next = newNode ( 20 ) ; head -> next -> next -> next -> next = newNode ( 50 ) ; head -> next -> next -> next -> next -> next = head -> next -> next ; isPalindrome ( head ) ? cout << " Palindrome " : cout << " Not Palindrome " return 0 ; } |
Length of longest palindrome list in a linked list using O ( 1 ) extra space | C ++ program to find longest palindrome sublist in a list in O ( 1 ) time . ; structure of the linked list ; function for counting the common elements ; loop to count coomon in the list starting from node a and b ; increment the count for same values ; Returns length of the longest palindrome sublist in given list ; loop till the end of the linked list ; The sublist from head to current reversed . ; check for odd length palindrome by finding longest common list elements beginning from prev and from next ( We exclude curr ) ; check for even length palindrome by finding longest common list elements beginning from curr and from next ; update prev and curr for next iteration ; Utility function to create a new list node ; Driver program to test above functions ; Let us create a linked lists to test the functions Created list is a : 2 -> 4 -> 3 -> 4 -> 2 -> 15 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; int countCommon ( Node * a , Node * b ) { int count = 0 ; for ( ; a && b ; a = a -> next , b = b -> next ) if ( a -> data == b -> data ) ++ count ; else break ; return count ; } int maxPalindrome ( Node * head ) { int result = 0 ; Node * prev = NULL , * curr = head ; while ( curr ) { Node * next = curr -> next ; curr -> next = prev ; result = max ( result , 2 * countCommon ( prev , next ) + 1 ) ; result = max ( result , 2 * countCommon ( curr , next ) ) ; prev = curr ; curr = next ; } return result ; } Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> next = NULL ; return temp ; } int main ( ) { Node * head = newNode ( 2 ) ; head -> next = newNode ( 4 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 2 ) ; head -> next -> next -> next -> next -> next = newNode ( 15 ) ; cout << maxPalindrome ( head ) << endl ; return 0 ; } |
Implementing Iterator pattern of a single Linked List | ; creating a list ; elements to be added at the end . in the above created list . ; elements of list are retrieved through iterator . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { vector < int > list ; list . push_back ( 1 ) ; list . push_back ( 2 ) ; list . push_back ( 3 ) ; for ( vector < int > :: iterator it = list . begin ( ) ; it != list . end ( ) ; ++ it ) cout << * it << " β " ; return 0 ; } |
Move all occurrences of an element to end in a linked list | C ++ program to move all occurrences of a given key to end . ; A Linked list Node ; A urility function to create a new node . ; Utility function to print the elements in Linked list ; Moves all occurrences of given key to end of linked list . ; Keeps track of locations where key is present . ; Traverse list ; If current pointer is not same as pointer to a key location , then we must have found a key in linked list . We swap data of pCrawl and pKey and move pKey to next position . ; Find next position where key is present ; Moving to next Node ; Driver code | #include <bits/stdc++.h> NEW_LINE struct Node { int data ; struct Node * next ; } ; struct Node * newNode ( int x ) { Node * temp = new Node ; temp -> data = x ; temp -> next = NULL ; } void printList ( Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } printf ( " STRNEWLINE " ) ; } void moveToEnd ( Node * head , int key ) { struct Node * pKey = head ; struct Node * pCrawl = head ; while ( pCrawl != NULL ) { if ( pCrawl != pKey && pCrawl -> data != key ) { pKey -> data = pCrawl -> data ; pCrawl -> data = key ; pKey = pKey -> next ; } if ( pKey -> data != key ) pKey = pKey -> next ; pCrawl = pCrawl -> next ; } } int main ( ) { Node * head = newNode ( 10 ) ; head -> next = newNode ( 20 ) ; head -> next -> next = newNode ( 10 ) ; head -> next -> next -> next = newNode ( 30 ) ; head -> next -> next -> next -> next = newNode ( 40 ) ; head -> next -> next -> next -> next -> next = newNode ( 10 ) ; head -> next -> next -> next -> next -> next -> next = newNode ( 60 ) ; printf ( " Before β moveToEnd ( ) , β the β Linked β list β is STRNEWLINE " ) ; printList ( head ) ; int key = 10 ; moveToEnd ( head , key ) ; printf ( " After moveToEnd ( ) , the Linked list is " printList ( head ) ; return 0 ; } |
Move all occurrences of an element to end in a linked list | C ++ code to remove key element to end of linked list ; A Linked list Node ; Function to remove key to end ; Node to keep pointing to tail ; Node to point to last of linked list ; Node prev2 to point to previous when head . data != key ; loop to perform operations to remove key to end ; Function to display linked list ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; struct Node * newNode ( int x ) { Node * temp = new Node ; temp -> data = x ; temp -> next = NULL ; } Node * keyToEnd ( Node * head , int key ) { Node * tail = head ; if ( head == NULL ) { return NULL ; } while ( tail -> next != NULL ) { tail = tail -> next ; } Node * last = tail ; Node * current = head ; Node * prev = NULL ; Node * prev2 = NULL ; while ( current != tail ) { if ( current -> data == key && prev2 == NULL ) { prev = current ; current = current -> next ; head = current ; last -> next = prev ; last = last -> next ; last -> next = NULL ; prev = NULL ; } else { if ( current -> data == key && prev2 != NULL ) { prev = current ; current = current -> next ; prev2 -> next = current ; last -> next = prev ; last = last -> next ; last -> next = NULL ; } else if ( current != tail ) { prev2 = current ; current = current -> next ; } } } return head ; } void printList ( Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d β " , temp -> data ) ; temp = temp -> next ; } printf ( " STRNEWLINE " ) ; } int main ( ) { Node * root = newNode ( 5 ) ; root -> next = newNode ( 2 ) ; root -> next -> next = newNode ( 2 ) ; root -> next -> next -> next = newNode ( 7 ) ; root -> next -> next -> next -> next = newNode ( 2 ) ; root -> next -> next -> next -> next -> next = newNode ( 2 ) ; root -> next -> next -> next -> next -> next -> next = newNode ( 2 ) ; int key = 2 ; cout << " Linked β List β before β operations β : " ; printList ( root ) ; cout << " Linked List after operations : " root = keyToEnd ( root , key ) ; printList ( root ) ; return 0 ; } |
Remove every k | C ++ program to delete every k - th Node of a singly linked list . ; Linked list Node ; To remove complete list ( Needed forcase when k is 1 ) ; Deletes every k - th node and returns head of modified list . ; If linked list is empty ; Initialize ptr and prev before starting traversal . ; Traverse list and delete every k - th node ; increment Node count ; check if count is equal to k if yes , then delete current Node ; put the next of current Node in the next of previous Node ; set count = 0 to reach further k - th Node ; update prev if count is not 0 ; Function to print linked list ; Utility function to create a new node . ; Driver program to test count function ; Start with the empty list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void freeList ( Node * node ) { while ( node != NULL ) { Node * next = node -> next ; delete ( node ) ; node = next ; } } Node * deleteKthNode ( struct Node * head , int k ) { if ( head == NULL ) return NULL ; if ( k == 1 ) { freeList ( head ) ; return NULL ; } struct Node * ptr = head , * prev = NULL ; int count = 0 ; while ( ptr != NULL ) { count ++ ; if ( k == count ) { delete ( prev -> next ) ; prev -> next = ptr -> next ; count = 0 ; } if ( count != 0 ) prev = ptr ; ptr = prev -> next ; } return head ; } void displayList ( struct Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { cout << temp -> data << " β " ; temp = temp -> next ; } } struct Node * newNode ( int x ) { Node * temp = new Node ; temp -> data = x ; temp -> next = NULL ; return temp ; } int main ( ) { struct Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; head -> next -> next -> next -> next -> next = newNode ( 6 ) ; head -> next -> next -> next -> next -> next -> next = newNode ( 7 ) ; head -> next -> next -> next -> next -> next -> next -> next = newNode ( 8 ) ; int k = 3 ; head = deleteKthNode ( head , k ) ; displayList ( head ) ; return 0 ; } |
Check whether the length of given linked list is Even or Odd | C ++ program to check length of a given linklist ; Defining structure ; Function to check the length of linklist ; Push function ; Allocating node ; Info into node ; Next of new node to head ; head points to new node ; Driver code ; Adding elements to Linked List ; Checking for length of linklist | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; int LinkedListLength ( Node * head ) { while ( head && head -> next ) { head = head -> next -> next ; } if ( ! head ) return 0 ; return 1 ; } void push ( Node * * head , int info ) { Node * node = new Node ( ) ; node -> data = info ; node -> next = ( * head ) ; ( * head ) = node ; } int main ( void ) { Node * head = NULL ; push ( & head , 4 ) ; push ( & head , 5 ) ; push ( & head , 7 ) ; push ( & head , 2 ) ; push ( & head , 9 ) ; push ( & head , 6 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 0 ) ; push ( & head , 5 ) ; push ( & head , 5 ) ; int check = LinkedListLength ( head ) ; if ( check == 0 ) { cout << " Even STRNEWLINE " ; } else { cout << " Odd STRNEWLINE " ; } return 0 ; } |
Find the sum of last n nodes of the given Linked List | C ++ implementation to find the sum of last ' n ' nodes of the Linked List ; A Linked list node ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to point to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; traverses the list from left to right ; push the node ' s β data β onto β the β stack β ' st ' ; move to next node ; pop ' n ' nodes from ' st ' and add them ; required sum ; Driver program to test above ; create linked list 10 -> 6 -> 8 -> 4 -> 12 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int sumOfLastN_NodesUtil ( struct Node * head , int n ) { if ( n <= 0 ) return 0 ; stack < int > st ; int sum = 0 ; while ( head != NULL ) { st . push ( head -> data ) ; head = head -> next ; } while ( n -- ) { sum += st . top ( ) ; st . pop ( ) ; } return sum ; } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 6 ) ; push ( & head , 10 ) ; int n = 2 ; cout << " Sum β of β last β " << n << " β nodes β = β " << sumOfLastN_NodesUtil ( head , n ) ; return 0 ; } |
Find the sum of last n nodes of the given Linked List | C ++ implementation to find the sum of last ' n ' nodes of the Linked List ; A Linked list node ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to point to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; reverse the linked list ; traverse the 1 st ' n ' nodes of the reversed linked list and add them ; accumulate node ' s β data β to β ' sum ' ; move to next node ; reverse back the linked list ; required sum ; Driver program to test above ; create linked list 10 -> 6 -> 8 -> 4 -> 12 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void reverseList ( struct Node * * head_ref ) { struct Node * current , * prev , * next ; current = * head_ref ; prev = NULL ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } * head_ref = prev ; } int sumOfLastN_NodesUtil ( struct Node * head , int n ) { if ( n <= 0 ) return 0 ; reverseList ( & head ) ; int sum = 0 ; struct Node * current = head ; while ( current != NULL && n -- ) { sum += current -> data ; current = current -> next ; } reverseList ( & head ) ; return sum ; } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 6 ) ; push ( & head , 10 ) ; int n = 2 ; cout << " Sum β of β last β " << n << " β nodes β = β " << sumOfLastN_NodesUtil ( head , n ) ; return 0 ; } |
Find the sum of last n nodes of the given Linked List | C ++ implementation to find the sum of last ' n ' nodes of the Linked List ; A Linked list node ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to point to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; calculate the length of the linked list ; count of first ( len - n ) nodes ; just traverse the 1 st ' c ' nodes ; move to next node ; now traverse the last ' n ' nodes and add them ; accumulate node 's data to sum ; move to next node ; required sum ; Driver program to test above ; create linked list 10 -> 6 -> 8 -> 4 -> 12 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int sumOfLastN_NodesUtil ( struct Node * head , int n ) { if ( n <= 0 ) return 0 ; int sum = 0 , len = 0 ; struct Node * temp = head ; while ( temp != NULL ) { len ++ ; temp = temp -> next ; } int c = len - n ; temp = head ; while ( temp != NULL && c -- ) temp = temp -> next ; while ( temp != NULL ) { sum += temp -> data ; temp = temp -> next ; } return sum ; } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 6 ) ; push ( & head , 10 ) ; int n = 2 ; cout << " Sum β of β last β " << n << " β nodes β = β " << sumOfLastN_NodesUtil ( head , n ) ; return 0 ; } |
Merge two sorted linked lists | ; point to the last result pointer ; tricky : advance to point to the next " . next " field | Node * SortedMerge ( Node * a , Node * b ) { Node * result = NULL ; Node * * lastPtrRef = & result ; while ( 1 ) { if ( a == NULL ) { * lastPtrRef = b ; break ; } else if ( b == NULL ) { * lastPtrRef = a ; break ; } if ( a -> data <= b -> data ) { MoveNode ( lastPtrRef , & a ) ; } else { MoveNode ( lastPtrRef , & b ) ; } lastPtrRef = & ( ( * lastPtrRef ) -> next ) ; } return ( result ) ; } |
In | C ++ Program to merge two sorted linked lists without using any extra space and without changing links of first list ; Structure for a linked list node ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to merge two sorted linked lists LL1 and LL2 without using any extra space . ; run till either one of a or b runs out ; for each element of LL1 , compare it with first element of LL2 . ; swap the two elements involved if LL1 has a greater element ; To keep LL2 sorted , place first element of LL2 at its correct place ; find mismatch by traversing the second linked list once ; correct the pointers ; move LL1 pointer to next element ; Code to print the linked link ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void mergeLists ( struct Node * a , struct Node * & b ) { while ( a && b ) { if ( a -> data > b -> data ) { swap ( a -> data , b -> data ) ; struct Node * temp = b ; if ( b -> next && b -> data > b -> next -> data ) { b = b -> next ; struct Node * ptr = b , * prev = NULL ; while ( ptr && ptr -> data < temp -> data ) { prev = ptr ; ptr = ptr -> next ; } prev -> next = temp ; temp -> next = ptr ; } } a = a -> next ; } } void printList ( struct Node * head ) { while ( head ) { cout << head -> data << " - > " ; head = head -> next ; } cout << " NULL " << endl ; } int main ( ) { struct Node * a = NULL ; push ( & a , 10 ) ; push ( & a , 8 ) ; push ( & a , 7 ) ; push ( & a , 4 ) ; push ( & a , 2 ) ; struct Node * b = NULL ; push ( & b , 12 ) ; push ( & b , 3 ) ; push ( & b , 1 ) ; mergeLists ( a , b ) ; cout << " First β List : β " ; printList ( a ) ; cout << " Second β List : β " ; printList ( b ) ; return 0 ; } |
Delete middle of linked list | C ++ program to delete middle of a linked list ; Link list Node ; count of nodes ; Deletes middle node and returns head of the modified list ; Base cases ; Find the count of nodes ; Find the middle node ; Delete the middle node ; Delete the middle node ; A utility function to print a given linked list ; Utility function to create a new node . ; Driver program to test above function ; Start with the empty list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; int countOfNodes ( struct Node * head ) { int count = 0 ; while ( head != NULL ) { head = head -> next ; count ++ ; } return count ; } struct Node * deleteMid ( struct Node * head ) { if ( head == NULL ) return NULL ; if ( head -> next == NULL ) { delete head ; return NULL ; } struct Node * copyHead = head ; int count = countOfNodes ( head ) ; int mid = count / 2 ; while ( mid -- > 1 ) { head = head -> next ; } head -> next = head -> next -> next ; return copyHead ; } void printList ( struct Node * ptr ) { while ( ptr != NULL ) { cout << ptr -> data << " - > " ; ptr = ptr -> next ; } cout << " NULL STRNEWLINE " ; } Node * newNode ( int data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> next = NULL ; return temp ; } int main ( ) { struct Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; cout << " Given β Linked β List STRNEWLINE " ; printList ( head ) ; head = deleteMid ( head ) ; cout << " Linked β List β after β deletion β of β middle STRNEWLINE " ; printList ( head ) ; return 0 ; } |
Merge K sorted linked lists | Set 1 | C ++ program to merge k sorted arrays of size n each ; A Linked List node ; Function to print nodes in a given linked list ; The main function that takes an array of lists arr [ 0. . last ] and generates the sorted output ; Traverse form second list to last ; head of both the lists , 0 and ith list . ; Break if list ended ; Smaller than first element ; Traverse the first list ; Smaller than next element ; go to next node ; if last node ; Utility function to create a new node . ; Driver program to test above functions ; Number of linked lists ; Number of elements in each list ; an array of pointers storing the head nodes of the linked lists ; Merge all lists | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void printList ( Node * node ) { while ( node != NULL ) { printf ( " % d β " , node -> data ) ; node = node -> next ; } } Node * mergeKLists ( Node * arr [ ] , int last ) { for ( int i = 1 ; i <= last ; i ++ ) { while ( true ) { Node * head_0 = arr [ 0 ] , * head_i = arr [ i ] ; if ( head_i == NULL ) break ; if ( head_0 -> data >= head_i -> data ) { arr [ i ] = head_i -> next ; head_i -> next = head_0 ; arr [ 0 ] = head_i ; } else while ( head_0 -> next != NULL ) { if ( head_0 -> next -> data >= head_i -> data ) { arr [ i ] = head_i -> next ; head_i -> next = head_0 -> next ; head_0 -> next = head_i ; break ; } head_0 = head_0 -> next ; if ( head_0 -> next == NULL ) { arr [ i ] = head_i -> next ; head_i -> next = NULL ; head_0 -> next = head_i ; head_0 -> next -> next = NULL ; break ; } } } } return arr [ 0 ] ; } Node * newNode ( int data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> next = NULL ; return temp ; } int main ( ) { int k = 3 ; int n = 4 ; Node * arr [ k ] ; arr [ 0 ] = newNode ( 1 ) ; arr [ 0 ] -> next = newNode ( 3 ) ; arr [ 0 ] -> next -> next = newNode ( 5 ) ; arr [ 0 ] -> next -> next -> next = newNode ( 7 ) ; arr [ 1 ] = newNode ( 2 ) ; arr [ 1 ] -> next = newNode ( 4 ) ; arr [ 1 ] -> next -> next = newNode ( 6 ) ; arr [ 1 ] -> next -> next -> next = newNode ( 8 ) ; arr [ 2 ] = newNode ( 0 ) ; arr [ 2 ] -> next = newNode ( 9 ) ; arr [ 2 ] -> next -> next = newNode ( 10 ) ; arr [ 2 ] -> next -> next -> next = newNode ( 11 ) ; Node * head = mergeKLists ( arr , k - 1 ) ; printList ( head ) ; return 0 ; } |
Merge two sorted lists ( in | C program to merge two sorted linked lists in - place . ; Function to create newNode in a linkedlist ; A utility function to print linked list ; Merges two given lists in - place . This function mainly compares head nodes and calls mergeUtil ( ) ; start with the linked list whose head data is the least ; Driver program ; 1 -> 3 -> 5 LinkedList created ; 0 -> 2 -> 4 LinkedList created | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * newNode ( int key ) { struct Node * temp = new Node ; temp -> data = key ; temp -> next = NULL ; return temp ; } void printList ( Node * node ) { while ( node != NULL ) { printf ( " % d β " , node -> data ) ; node = node -> next ; } } Node * merge ( Node * h1 , Node * h2 ) { if ( ! h1 ) return h2 ; if ( ! h2 ) return h1 ; if ( h1 -> data < h2 -> data ) { h1 -> next = merge ( h1 -> next , h2 ) ; return h1 ; } else { h2 -> next = merge ( h1 , h2 -> next ) ; return h2 ; } } int main ( ) { Node * head1 = newNode ( 1 ) ; head1 -> next = newNode ( 3 ) ; head1 -> next -> next = newNode ( 5 ) ; Node * head2 = newNode ( 0 ) ; head2 -> next = newNode ( 2 ) ; head2 -> next -> next = newNode ( 4 ) ; Node * mergedhead = merge ( head1 , head2 ) ; printList ( mergedhead ) ; return 0 ; } |
Merge two sorted lists ( in | C ++ program to merge two sorted linked lists in - place . ; Linked List node ; Function to create newNode in a linkedlist ; A utility function to print linked list ; Merges two lists with headers as h1 and h2 . It assumes that h1 ' s β data β is β smaller β than β or β equal β to β h2' s data . ; if only one node in first list simply point its head to second list ; Initialize current and next pointers of both lists ; if curr2 lies in between curr1 and next1 then do curr1 -> curr2 -> next1 ; now let curr1 and curr2 to point to their immediate next pointers ; if more nodes in first list ; else point the last node of first list to the remaining nodes of second list ; Merges two given lists in - place . This function mainly compares head nodes and calls mergeUtil ( ) ; start with the linked list whose head data is the least ; Driver program ; 1 -> 3 -> 5 LinkedList created ; 0 -> 2 -> 4 LinkedList created | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; struct Node * newNode ( int key ) { struct Node * temp = new Node ; temp -> data = key ; temp -> next = NULL ; return temp ; } void printList ( struct Node * node ) { while ( node != NULL ) { printf ( " % d β " , node -> data ) ; node = node -> next ; } } struct Node * mergeUtil ( struct Node * h1 , struct Node * h2 ) { if ( ! h1 -> next ) { h1 -> next = h2 ; return h1 ; } struct Node * curr1 = h1 , * next1 = h1 -> next ; struct Node * curr2 = h2 , * next2 = h2 -> next ; while ( next1 && curr2 ) { if ( ( curr2 -> data ) >= ( curr1 -> data ) && ( curr2 -> data ) <= ( next1 -> data ) ) { next2 = curr2 -> next ; curr1 -> next = curr2 ; curr2 -> next = next1 ; curr1 = curr2 ; curr2 = next2 ; } else { if ( next1 -> next ) { next1 = next1 -> next ; curr1 = curr1 -> next ; } else { next1 -> next = curr2 ; return h1 ; } } } return h1 ; } struct Node * merge ( struct Node * h1 , struct Node * h2 ) { if ( ! h1 ) return h2 ; if ( ! h2 ) return h1 ; if ( h1 -> data < h2 -> data ) return mergeUtil ( h1 , h2 ) ; else return mergeUtil ( h2 , h1 ) ; } int main ( ) { struct Node * head1 = newNode ( 1 ) ; head1 -> next = newNode ( 3 ) ; head1 -> next -> next = newNode ( 5 ) ; struct Node * head2 = newNode ( 0 ) ; head2 -> next = newNode ( 2 ) ; head2 -> next -> next = newNode ( 4 ) ; struct Node * mergedhead = merge ( head1 , head2 ) ; printList ( mergedhead ) ; return 0 ; } |
Recursive selection sort for singly linked list | Swapping node links | C ++ implementation of recursive selection sort for singly linked list | Swapping node links ; A Linked list node ; function to swap nodes ' currX ' and ' currY ' in a linked list without swapping data ; make ' currY ' as new head ; adjust links ; Swap next pointers ; function to sort the linked list using recursive selection sort technique ; if there is only a single node ; ' min ' - pointer to store the node having minimum data value ; ' beforeMin ' - pointer to store node previous to ' min ' node ; traverse the list till the last node ; if true , then update ' min ' and ' beforeMin ' ; if ' min ' and ' head ' are not same , swap the head node with the ' min ' node ; recursively sort the remaining list ; function to sort the given linked list ; if list is empty ; sort the list using recursive selection sort technique ; function to insert a node at the beginning of the linked list ; allocate node ; put in the data ; link the old list to the new node ; move the head to point to the new node ; function to print the linked list ; Driver program to test above ; create linked list 10 -> 12 -> 8 -> 4 -> 6 ; sort the linked list | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void swapNodes ( struct Node * * head_ref , struct Node * currX , struct Node * currY , struct Node * prevY ) { * head_ref = currY ; prevY -> next = currX ; struct Node * temp = currY -> next ; currY -> next = currX -> next ; currX -> next = temp ; } struct Node * recurSelectionSort ( struct Node * head ) { if ( head -> next == NULL ) return head ; struct Node * min = head ; struct Node * beforeMin = NULL ; struct Node * ptr ; for ( ptr = head ; ptr -> next != NULL ; ptr = ptr -> next ) { if ( ptr -> next -> data < min -> data ) { min = ptr -> next ; beforeMin = ptr ; } } if ( min != head ) swapNodes ( & head , head , min , beforeMin ) ; head -> next = recurSelectionSort ( head -> next ) ; return head ; } void sort ( struct Node * * head_ref ) { if ( ( * head_ref ) == NULL ) return ; * head_ref = recurSelectionSort ( * head_ref ) ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * head ) { while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 6 ) ; push ( & head , 4 ) ; push ( & head , 8 ) ; push ( & head , 12 ) ; push ( & head , 10 ) ; cout << " Linked β list β before β sorting : n " ; printList ( head ) ; sort ( & head ) ; cout << " Linked list after sorting : n " ; printList ( head ) ; return 0 ; } |
Insert a node after the n | C ++ implementation to insert a node after the n - th node from the end ; structure of a node ; function to get a new node ; allocate memory for the node ; put in the data ; function to insert a node after the nth node from the end ; if list is empty ; get a new node for the value ' x ' ; find length of the list , i . e , the number of nodes in the list ; traverse up to the nth node from the end ; insert the ' newNode ' by making the necessary adjustment in the links ; function to print the list ; Driver program to test above ; Creating list 1 -> 3 -> 4 -> 5 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> next = NULL ; return newNode ; } void insertAfterNthNode ( Node * head , int n , int x ) { if ( head == NULL ) return ; Node * newNode = getNode ( x ) ; Node * ptr = head ; int len = 0 , i ; while ( ptr != NULL ) { len ++ ; ptr = ptr -> next ; } ptr = head ; for ( i = 1 ; i <= ( len - n ) ; i ++ ) ptr = ptr -> next ; newNode -> next = ptr -> next ; ptr -> next = newNode ; } void printList ( Node * head ) { while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { Node * head = getNode ( 1 ) ; head -> next = getNode ( 3 ) ; head -> next -> next = getNode ( 4 ) ; head -> next -> next -> next = getNode ( 5 ) ; int n = 4 , x = 2 ; cout << " Original β Linked β List : β " ; printList ( head ) ; insertAfterNthNode ( head , n , x ) ; cout << " Linked List After Insertion : " printList ( head ) ; return 0 ; } |
Insert a node after the n | C ++ implementation to insert a node after the nth node from the end ; structure of a node ; function to get a new node ; allocate memory for the node ; put in the data ; function to insert a node after the nth node from the end ; if list is empty ; get a new node for the value ' x ' ; Initializing the slow and fast pointers ; move ' fast _ ptr ' to point to the nth node from the beginning ; iterate until ' fast _ ptr ' points to the last node ; move both the pointers to the respective next nodes ; insert the ' newNode ' by making the necessary adjustment in the links ; function to print the list ; Driver program to test above ; Creating list 1 -> 3 -> 4 -> 5 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; Node * getNode ( int data ) { Node * newNode = ( Node * ) malloc ( sizeof ( Node ) ) ; newNode -> data = data ; newNode -> next = NULL ; return newNode ; } void insertAfterNthNode ( Node * head , int n , int x ) { if ( head == NULL ) return ; Node * newNode = getNode ( x ) ; Node * slow_ptr = head ; Node * fast_ptr = head ; for ( int i = 1 ; i <= n - 1 ; i ++ ) fast_ptr = fast_ptr -> next ; while ( fast_ptr -> next != NULL ) { slow_ptr = slow_ptr -> next ; fast_ptr = fast_ptr -> next ; } newNode -> next = slow_ptr -> next ; slow_ptr -> next = newNode ; } void printList ( Node * head ) { while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } } int main ( ) { Node * head = getNode ( 1 ) ; head -> next = getNode ( 3 ) ; head -> next -> next = getNode ( 4 ) ; head -> next -> next -> next = getNode ( 5 ) ; int n = 4 , x = 2 ; cout << " Original β Linked β List : β " ; printList ( head ) ; insertAfterNthNode ( head , n , x ) ; cout << " Linked List After Insertion : " printList ( head ) ; return 0 ; } |
Make middle node head in a linked list | C ++ program to make middle node as head of linked list . ; Link list node ; Function to get the middle and set at beginning of the linked list ; To traverse list nodes one by one ; To traverse list nodes by skipping one . ; To keep track of previous of middle ; for previous node of middle node ; move one node each time ; move two node each time ; set middle node at head ; To insert a node at the beginning of linked list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; A function to print a given linked list ; Driver code ; Create a list of 5 nodes | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void setMiddleHead ( Node * * head ) { if ( * head == NULL ) return ; Node * one_node = ( * head ) ; Node * two_node = ( * head ) ; Node * prev = NULL ; while ( two_node != NULL && two_node -> next != NULL ) { prev = one_node ; two_node = two_node -> next -> next ; one_node = one_node -> next ; } prev -> next = prev -> next -> next ; one_node -> next = ( * head ) ; ( * head ) = one_node ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * ptr ) { while ( ptr != NULL ) { cout << ptr -> data << " β " ; ptr = ptr -> next ; } cout << endl ; } int main ( ) { Node * head = NULL ; int i ; for ( i = 5 ; i > 0 ; i -- ) push ( & head , i ) ; cout << " β list β before : β " ; printList ( head ) ; setMiddleHead ( & head ) ; cout << " β list β After : β " ; printList ( head ) ; return 0 ; } |
Sorted merge of two sorted doubly circular linked lists | C ++ implementation for Sorted merge of two sorted doubly circular linked list ; A utility function to insert a new node at the beginning of doubly circular linked list ; allocate space ; put in the data ; if list is empty ; pointer points to last Node ; setting up previous and next of new node ; update next and previous pointers of head_ref and last . ; update head_ref pointer ; function for Sorted merge of two sorted doubly linked list ; If first list is empty ; If second list is empty ; Pick the smaller value and adjust the links ; function for Sorted merge of two sorted doubly circular linked list ; if 1 st list is empty ; if 2 nd list is empty ; get pointer to the node which will be the last node of the final list ; store NULL to the ' next ' link of the last nodes of the two lists ; sorted merge of head1 and head2 ; ' prev ' of 1 st node pointing the last node ' next ' of last node pointing to 1 st node ; function to print the list ; Driver program to test above ; list 1 : ; list 2 : | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next , * prev ; } ; void insert ( Node * * head_ref , int data ) { Node * new_node = new Node ; new_node -> data = data ; if ( * head_ref == NULL ) { new_node -> next = new_node ; new_node -> prev = new_node ; } else { Node * last = ( * head_ref ) -> prev ; new_node -> next = * head_ref ; new_node -> prev = last ; last -> next = ( * head_ref ) -> prev = new_node ; } * head_ref = new_node ; } Node * merge ( Node * first , Node * second ) { if ( ! first ) return second ; if ( ! second ) return first ; if ( first -> data < second -> data ) { first -> next = merge ( first -> next , second ) ; first -> next -> prev = first ; first -> prev = NULL ; return first ; } else { second -> next = merge ( first , second -> next ) ; second -> next -> prev = second ; second -> prev = NULL ; return second ; } } Node * mergeUtil ( Node * head1 , Node * head2 ) { if ( ! head1 ) return head2 ; if ( ! head2 ) return head1 ; Node * last_node ; if ( head1 -> prev -> data < head2 -> prev -> data ) last_node = head2 -> prev ; else last_node = head1 -> prev ; head1 -> prev -> next = head2 -> prev -> next = NULL ; Node * finalHead = merge ( head1 , head2 ) ; finalHead -> prev = last_node ; last_node -> next = finalHead ; return finalHead ; } void printList ( Node * head ) { Node * temp = head ; while ( temp -> next != head ) { cout << temp -> data << " β " ; temp = temp -> next ; } cout << temp -> data << " β " ; } int main ( ) { Node * head1 = NULL , * head2 = NULL ; insert ( & head1 , 8 ) ; insert ( & head1 , 5 ) ; insert ( & head1 , 3 ) ; insert ( & head1 , 1 ) ; insert ( & head2 , 11 ) ; insert ( & head2 , 9 ) ; insert ( & head2 , 7 ) ; insert ( & head2 , 2 ) ; Node * newHead = mergeUtil ( head1 , head2 ) ; cout << " Final β Sorted β List : β " ; printList ( newHead ) ; return 0 ; } |
Reverse a Doubly Linked List | Set 4 ( Swapping Data ) | Cpp Program to Reverse a List using Data Swapping ; Insert a new node at the head of the list ; Function to reverse the list ; Traverse the list and set right pointer to end of list ; Swap data of left and right pointer and move them towards each other until they meet or cross each other ; Swap data of left and right pointer ; Advance left pointer ; Advance right pointer ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * prev , * next ; } ; Node * newNode ( int val ) { Node * temp = new Node ; temp -> data = val ; temp -> prev = temp -> next = nullptr ; return temp ; } void printList ( Node * head ) { while ( head -> next != nullptr ) { cout << head -> data << " β < - - > β " ; head = head -> next ; } cout << head -> data << endl ; } void insert ( Node * * head , int val ) { Node * temp = newNode ( val ) ; temp -> next = * head ; ( * head ) -> prev = temp ; ( * head ) = temp ; } void reverseList ( Node * * head ) { Node * left = * head , * right = * head ; while ( right -> next != nullptr ) right = right -> next ; while ( left != right && left -> prev != right ) { swap ( left -> data , right -> data ) ; left = left -> next ; right = right -> prev ; } } int main ( ) { Node * head = newNode ( 5 ) ; insert ( & head , 4 ) ; insert ( & head , 3 ) ; insert ( & head , 2 ) ; insert ( & head , 1 ) ; printList ( head ) ; cout << " List β After β Reversing " << endl ; reverseList ( & head ) ; printList ( head ) ; return 0 ; } |
Check if a doubly linked list of characters is palindrome or not | C ++ program to check if doubly linked list is palindrome or not ; Structure of node ; Given a reference ( pointer to pointer ) to the head of a list and an int , inserts a new node on the front of the list . ; Function to check if list is palindrome or not ; Find rightmost node ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char data ; struct Node * next ; struct Node * prev ; } ; void push ( struct Node * * head_ref , char new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; new_node -> prev = NULL ; if ( ( * head_ref ) != NULL ) ( * head_ref ) -> prev = new_node ; ( * head_ref ) = new_node ; } bool isPalindrome ( struct Node * left ) { if ( left == NULL ) return true ; struct Node * right = left ; while ( right -> next != NULL ) right = right -> next ; while ( left != right ) { if ( left -> data != right -> data ) return false ; left = left -> next ; right = right -> prev ; } return true ; } int main ( ) { struct Node * head = NULL ; push ( & head , ' l ' ) ; push ( & head , ' e ' ) ; push ( & head , ' v ' ) ; push ( & head , ' e ' ) ; push ( & head , ' l ' ) ; if ( isPalindrome ( head ) ) printf ( " It β is β Palindrome " ) ; else printf ( " Not β Palindrome " ) ; return 0 ; } |
XOR Linked List Γ’ β¬β A Memory Efficient Doubly Linked List | Set 2 | C ++ Implementation of Memory efficient Doubly Linked List ; Node structure of a memory efficient doubly linked list ; XOR of next and previous node ; returns XORed value of the node addresses ; Insert a node at the beginning of the XORed linked list and makes the newly inserted node as head ; Allocate memory for new node ; Since new node is being inserted at the beginning , npx of new node will always be XOR of current head and NULL ; If linked list is not empty , then npx of current head node will be XOR of new node and node next to current head ; * ( head_ref ) -> npx is XOR of NULL and next . So if we do XOR of it with NULL , we get next ; Change head ; prints contents of doubly linked list in forward direction ; print current node ; get address of next node : curr -> npx is next ^ prev , so curr -> npx ^ prev will be next ^ prev ^ prev which is next ; update prev and curr for next iteration ; Driver code ; Create following Doubly Linked List head -- > 40 < -- > 30 < -- > 20 < -- > 10 ; print the created list | #include <bits/stdc++.h> NEW_LINE #include <cinttypes> NEW_LINE using namespace std ; class Node { public : int data ; Node * npx ; } ; Node * XOR ( Node * a , Node * b ) { return reinterpret_cast < Node * > ( reinterpret_cast < uintptr_t > ( a ) ^ reinterpret_cast < uintptr_t > ( b ) ) ; } void insert ( Node * * head_ref , int data ) { Node * new_node = new Node ( ) ; new_node -> data = data ; new_node -> npx = * head_ref ; if ( * head_ref != NULL ) { ( * head_ref ) -> npx = XOR ( new_node , ( * head_ref ) -> npx ) ; } * head_ref = new_node ; } void printList ( Node * head ) { Node * curr = head ; Node * prev = NULL ; Node * next ; cout << " Following β are β the β nodes β of β Linked β List : β STRNEWLINE " ; while ( curr != NULL ) { cout << curr -> data << " β " ; next = XOR ( prev , curr -> npx ) ; prev = curr ; curr = next ; } } int main ( ) { Node * head = NULL ; insert ( & head , 10 ) ; insert ( & head , 20 ) ; insert ( & head , 30 ) ; insert ( & head , 40 ) ; printList ( head ) ; return ( 0 ) ; } |
Print nodes between two given level numbers of a binary tree | A C ++ program to print Nodes level by level berween given two levels . ; A binary tree Node has key , pointer to left and right children ; Given a binary tree , print nodes from level number ' low ' to level number ' high ' ; Marker node to indicate end of level ; Initialize level number ; Enqueue the only first level node and marker node for end of level ; Simple level order traversal loop ; Remove the front item from queue ; Check if end of level is reached ; print a new line and increment level number ; Check if marker node was last node in queue or level number is beyond the given upper limit ; Enqueue the marker for end of next level ; If this is marker , then we don 't need print it and enqueue its children ; If level is equal to or greater than given lower level , print it ; Enqueue children of non - marker node ; Helper function that allocates a new Node with the given key and NULL left and right pointers . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; void printLevels ( Node * root , int low , int high ) { queue < Node * > Q ; Node * marker = new Node ; int level = 1 ; Q . push ( root ) ; Q . push ( marker ) ; while ( Q . empty ( ) == false ) { Node * n = Q . front ( ) ; Q . pop ( ) ; if ( n == marker ) { cout << endl ; level ++ ; if ( Q . empty ( ) == true level > high ) break ; Q . push ( marker ) ; continue ; } if ( level >= low ) cout << n -> key << " β " ; if ( n -> left != NULL ) Q . push ( n -> left ) ; if ( n -> right != NULL ) Q . push ( n -> right ) ; } } Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } int main ( ) { struct Node * root = newNode ( 20 ) ; root -> left = newNode ( 8 ) ; root -> right = newNode ( 22 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> left = newNode ( 10 ) ; root -> left -> right -> right = newNode ( 14 ) ; cout << " Level β Order β traversal β between β given β two β levels β is " ; printLevels ( root , 2 , 3 ) ; return 0 ; } |
Print nodes at k distance from root | ; A binary tree node has data , pointer to left child and a pointer to right child ; Driver code ; Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8 | #include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; void printKDistant ( node * root , int k ) { if ( root == NULL k < 0 ) return ; if ( k == 0 ) { cout << root -> data << " β " ; return ; } printKDistant ( root -> left , k - 1 ) ; printKDistant ( root -> right , k - 1 ) ; } int main ( ) { node * root = new node ( 1 ) ; root -> left = new node ( 2 ) ; root -> right = new node ( 3 ) ; root -> left -> left = new node ( 4 ) ; root -> left -> right = new node ( 5 ) ; root -> right -> left = new node ( 8 ) ; printKDistant ( root , 2 ) ; return 0 ; } |
Print nodes at k distance from root | Iterative | CPP program to print all nodes of level k iterative approach ; Node of binary tree ; Function to add a new node ; Function to print nodes of given level ; extra NULL is pushed to keep track of all the nodes to be pushed before level is incremented by 1 ; print when level is equal to k ; break the loop if level exceeds the given level number ; Driver code ; create a binary tree | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * newnode = new Node ( ) ; newnode -> data = data ; newnode -> left = newnode -> right = NULL ; } bool printKDistant ( Node * root , int klevel ) { queue < Node * > q ; int level = 1 ; bool flag = false ; q . push ( root ) ; q . push ( NULL ) ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) ; if ( level == klevel && temp != NULL ) { flag = true ; cout << temp -> data << " β " ; } q . pop ( ) ; if ( temp == NULL ) { if ( q . front ( ) ) q . push ( NULL ) ; level += 1 ; if ( level > klevel ) break ; } else { if ( temp -> left ) q . push ( temp -> left ) ; if ( temp -> right ) q . push ( temp -> right ) ; } } cout << endl ; return flag ; } int main ( ) { Node * root = newNode ( 20 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 30 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 15 ) ; root -> left -> right -> left = newNode ( 12 ) ; root -> right -> left = newNode ( 25 ) ; root -> right -> right = newNode ( 40 ) ; cout << " data β at β level β 1 β : β " ; int ret = printKDistant ( root , 1 ) ; if ( ret == false ) cout << " Number β exceeds β total β number β of β levels STRNEWLINE " ; cout << " data β at β level β 2 β : β " ; ret = printKDistant ( root , 2 ) ; if ( ret == false ) cout << " Number β exceeds β total β number β of β levels STRNEWLINE " ; cout << " data β at β level β 3 β : β " ; ret = printKDistant ( root , 3 ) ; if ( ret == false ) cout << " Number β exceeds β total β number β of β levels STRNEWLINE " ; cout << " data β at β level β 6 β : β " ; ret = printKDistant ( root , 6 ) ; if ( ret == false ) cout << " Number β exceeds β total β number β of β levels STRNEWLINE " ; return 0 ; } |
Print all leaf nodes of a Binary Tree from left to right | C ++ program to print leaf nodes from left to right ; A Binary Tree Node ; function to print leaf nodes from left to right ; if node is null , return ; if node is leaf node , print its data ; if left child exists , check for leaf recursively ; if right child exists , check for leaf recursively ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; print leaf nodes of the given tree | #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; void printLeafNodes ( Node * root ) { if ( ! root ) return ; if ( ! root -> left && ! root -> right ) { cout << root -> data << " β " ; return ; } if ( root -> left ) printLeafNodes ( root -> left ) ; if ( root -> right ) printLeafNodes ( root -> right ) ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> left -> left = newNode ( 6 ) ; root -> right -> left -> right = newNode ( 7 ) ; root -> right -> right -> left = newNode ( 9 ) ; root -> right -> right -> right = newNode ( 10 ) ; printLeafNodes ( root ) ; return 0 ; } |
Print all nodes at distance k from a given node | ; A binary Tree node ; Recursive function to print all the nodes at distance k in the tree ( or subtree ) rooted with given root . See ; Base Case ; If we reach a k distant node , print it ; Recur for left and right subtrees ; Prints all nodes at distance k from a given target node . The k distant nodes may be upward or downward . This function Returns distance of root from target node , it returns - 1 if target node is not present in tree rooted with root . ; Base Case 1 : If tree is empty , return - 1 ; If target is same as root . Use the downward function to print all nodes at distance k in subtree rooted with target or root ; Recur for left subtree ; Check if target node was found in left subtree ; If root is at distance k from target , print root Note that dl is Distance of root 's left child from target ; Else go to right subtree and print all k - dl - 2 distant nodes Note that the right child is 2 edges away from left child ; Add 1 to the distance and return value for parent calls ; MIRROR OF ABOVE CODE FOR RIGHT SUBTREE Note that we reach here only when node was not found in left subtree ; If target was neither present in left nor in right subtree ; A utility function to create a new binary tree node ; Driver program to test above functions ; Let us construct the tree shown in above diagram | #include <iostream> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; void printkdistanceNodeDown ( node * root , int k ) { if ( root == NULL k < 0 ) return ; if ( k == 0 ) { cout << root -> data << endl ; return ; } printkdistanceNodeDown ( root -> left , k - 1 ) ; printkdistanceNodeDown ( root -> right , k - 1 ) ; } int printkdistanceNode ( node * root , node * target , int k ) { if ( root == NULL ) return -1 ; if ( root == target ) { printkdistanceNodeDown ( root , k ) ; return 0 ; } int dl = printkdistanceNode ( root -> left , target , k ) ; if ( dl != -1 ) { if ( dl + 1 == k ) cout << root -> data << endl ; else printkdistanceNodeDown ( root -> right , k - dl - 2 ) ; return 1 + dl ; } int dr = printkdistanceNode ( root -> right , target , k ) ; if ( dr != -1 ) { if ( dr + 1 == k ) cout << root -> data << endl ; else printkdistanceNodeDown ( root -> left , k - dr - 2 ) ; return 1 + dr ; } return -1 ; } node * newnode ( int data ) { node * temp = new node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { node * root = newnode ( 20 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 22 ) ; root -> left -> left = newnode ( 4 ) ; root -> left -> right = newnode ( 12 ) ; root -> left -> right -> left = newnode ( 10 ) ; root -> left -> right -> right = newnode ( 14 ) ; node * target = root -> left -> right ; printkdistanceNode ( root , target , 2 ) ; return 0 ; } |
Print all nodes that don 't have sibling | Program to find singles in a given binary tree ; A Binary Tree Node ; Function to print all non - root nodes that don 't have a sibling ; Base case ; If this is an internal node , recur for left and right subtrees ; If left child is NULL and right is not , print right child and recur for right child ; If right child is NULL and left is not , print left child and recur for left child ; Driver program to test above functions ; Let us create binary tree given in the above example | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { struct node * left , * right ; int key ; } ; node * newNode ( int key ) { node * temp = new node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return temp ; } void printSingles ( struct node * root ) { if ( root == NULL ) return ; if ( root -> left != NULL && root -> right != NULL ) { printSingles ( root -> left ) ; printSingles ( root -> right ) ; } else if ( root -> right != NULL ) { cout << root -> right -> key << " β " ; printSingles ( root -> right ) ; } else if ( root -> left != NULL ) { cout << root -> left -> key << " β " ; printSingles ( root -> left ) ; } } int main ( ) { node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> left -> left = newNode ( 6 ) ; printSingles ( root ) ; return 0 ; } |
Print all nodes that are at distance k from a leaf node | Program to print all nodes which are at distance k from a leaf ; utility that allocates a new Node with the given key ; This function prints all nodes that are distance k from a leaf node path [ ] -- > Store ancestors of a node visited [ ] -- > Stores true if a node is printed as output . A node may be k distance away from many leaves , we want to print it once ; Base case ; append this Node to the path array ; it 's a leaf, so print the ancestor at distance k only if the ancestor is not already printed ; If not leaf node , recur for left and right subtrees ; Given a binary tree and a number k , print all nodes that are k distant from a leaf ; Driver code ; Let us create binary tree given in the above example | #include <iostream> NEW_LINE using namespace std ; #define MAX_HEIGHT 10000 NEW_LINE struct Node { int key ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * node = new Node ; node -> key = key ; node -> left = node -> right = NULL ; return ( node ) ; } void kDistantFromLeafUtil ( Node * node , int path [ ] , bool visited [ ] , int pathLen , int k ) { if ( node == NULL ) return ; path [ pathLen ] = node -> key ; visited [ pathLen ] = false ; pathLen ++ ; if ( node -> left == NULL && node -> right == NULL && pathLen - k - 1 >= 0 && visited [ pathLen - k - 1 ] == false ) { cout << path [ pathLen - k - 1 ] << " β " ; visited [ pathLen - k - 1 ] = true ; return ; } kDistantFromLeafUtil ( node -> left , path , visited , pathLen , k ) ; kDistantFromLeafUtil ( node -> right , path , visited , pathLen , k ) ; } void printKDistantfromLeaf ( Node * node , int k ) { int path [ MAX_HEIGHT ] ; bool visited [ MAX_HEIGHT ] = { false } ; kDistantFromLeafUtil ( node , path , visited , 0 , k ) ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; cout << " Nodes β at β distance β 2 β are : β " ; printKDistantfromLeaf ( root , 2 ) ; return 0 ; } |
Print all nodes that are at distance k from a leaf node | C ++ program to print all nodes at a distance k from leaf ; A binary tree node ; Given a binary tree and a number k , print all nodes that are k distant from a leaf ; leaf node ; parent of left leaf ; parent of right leaf ; Driver code ; Let us construct the tree shown in above diagram | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> left = temp -> right = NULL ; return temp ; } int printKDistantfromLeaf ( struct Node * node , int k ) { if ( node == NULL ) return -1 ; int lk = printKDistantfromLeaf ( node -> left , k ) ; int rk = printKDistantfromLeaf ( node -> right , k ) ; bool isLeaf = lk == -1 && lk == rk ; if ( lk == 0 || rk == 0 || ( isLeaf && k == 0 ) ) cout << ( " β " ) << ( node -> data ) ; if ( isLeaf && k > 0 ) return k - 1 ; if ( lk > 0 && lk < k ) return lk - 1 ; if ( rk > 0 && rk < k ) return rk - 1 ; return -2 ; } int main ( ) { Node * root = NULL ; root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; cout << ( " β Nodes β at β distance β 2 β are β : " ) << endl ; printKDistantfromLeaf ( root , 2 ) ; } |
Print leftmost and rightmost nodes of a Binary Tree | C / C ++ program to print corner node at each level of binary tree ; A binary tree node has key , pointer to left child and a pointer to right child ; Function to print corner node at each level ; If the root is null then simply return ; star node is for keeping track of levels ; pushing root node and star node ; Do level order traversal using a single queue ; n denotes the size of the current level in the queue ; If it is leftmost corner value or rightmost corner value then print it ; push the left and right children of the temp node ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void printCorner ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { int n = q . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( i == 0 i == n - 1 ) cout << temp -> key << " β " ; if ( temp -> left ) q . push ( temp -> left ) ; if ( temp -> right ) q . push ( temp -> right ) ; } } } int main ( ) { Node * root = newNode ( 15 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 20 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( 12 ) ; root -> right -> left = newNode ( 16 ) ; root -> right -> right = newNode ( 25 ) ; printCorner ( root ) ; return 0 ; } |
Print Binary Tree in 2 | C ++ Program to print binary tree in 2D ; A binary tree node ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Function to print binary tree in 2D It does reverse inorder traversal ; Base case ; Increase distance between levels ; Process right child first ; Print current node after space count ; Process left child ; Wrapper over print2DUtil ( ) ; Pass initial space count as 0 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define COUNT 10 NEW_LINE class Node { public : int data ; Node * left , * right ; Node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; void print2DUtil ( Node * root , int space ) { if ( root == NULL ) return ; space += COUNT ; print2DUtil ( root -> right , space ) ; cout << endl ; for ( int i = COUNT ; i < space ; i ++ ) cout << " β " ; cout << root -> data << " STRNEWLINE " ; print2DUtil ( root -> left , space ) ; } void print2D ( Node * root ) { print2DUtil ( root , 0 ) ; } int main ( ) { Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; root -> right -> left = new Node ( 6 ) ; root -> right -> right = new Node ( 7 ) ; root -> left -> left -> left = new Node ( 8 ) ; root -> left -> left -> right = new Node ( 9 ) ; root -> left -> right -> left = new Node ( 10 ) ; root -> left -> right -> right = new Node ( 11 ) ; root -> right -> left -> left = new Node ( 12 ) ; root -> right -> left -> right = new Node ( 13 ) ; root -> right -> right -> left = new Node ( 14 ) ; root -> right -> right -> right = new Node ( 15 ) ; print2D ( root ) ; return 0 ; } |
Print Left View of a Binary Tree | C ++ program to print left view of Binary Tree ; A utility function to create a new Binary Tree Node ; Recursive function to print left view of a binary tree . ; Base Case ; If this is the first Node of its level ; Recur for left subtree first , then right subtree ; A wrapper over leftViewUtil ( ) ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int item ) { struct Node * temp = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } void leftViewUtil ( struct Node * root , int level , int * max_level ) { if ( root == NULL ) return ; if ( * max_level < level ) { cout << root -> data << " β " ; * max_level = level ; } leftViewUtil ( root -> left , level + 1 , max_level ) ; leftViewUtil ( root -> right , level + 1 , max_level ) ; } void leftView ( struct Node * root ) { int max_level = 0 ; leftViewUtil ( root , 1 , & max_level ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 7 ) ; root -> left -> right = newNode ( 8 ) ; root -> right -> right = newNode ( 15 ) ; root -> right -> left = newNode ( 12 ) ; root -> right -> right -> left = newNode ( 14 ) ; leftView ( root ) ; return 0 ; } |
Print Left View of a Binary Tree | C ++ program to print left view of Binary Tree ; A Binary Tree Node ; Utility function to create a new tree node ; function to print left view of binary tree ; number of nodes at current level ; Traverse all nodes of current level ; Print the left most element at the level ; Add left node to queue ; Add right node to queue ; Driver code ; Let 's construct the tree as shown in example | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void printLeftView ( Node * root ) { if ( ! root ) return ; queue < Node * > q ; q . push ( root ) ; while ( ! q . empty ( ) ) { int n = q . size ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { Node * temp = q . front ( ) ; q . pop ( ) ; if ( i == 1 ) cout << temp -> data << " β " ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } } } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 7 ) ; root -> left -> right = newNode ( 8 ) ; root -> right -> right = newNode ( 15 ) ; root -> right -> left = newNode ( 12 ) ; root -> right -> right -> left = newNode ( 14 ) ; printLeftView ( root ) ; } |
Reduce the given Array of [ 1 , N ] by rotating left or right based on given conditions | C ++ program for the above approach ; Function to find the last element left after performing N - 1 queries of type X ; Stores the next power of 2 ; Iterate until nextPower is at most N ; If X is equal to 1 ; Stores the power of 2 less than or equal to N ; Return the final value ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int rotate ( int arr [ ] , int N , int X ) { long long int nextPower = 1 ; while ( nextPower <= N ) nextPower *= 2 ; if ( X == 1 ) return nextPower - N ; long long int prevPower = nextPower / 2 ; return 2 * ( N - prevPower ) + 1 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int X = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << rotate ( arr , N , X ) ; return 0 ; } |
Check whether Matrix T is a result of one or more 90 Β° rotations of Matrix mat | C ++ program for the above approach ; Function to check whether another matrix can be created by rotating mat one or more times by 90 degrees ; If the dimensions of both the arrays don 't match ; Return false ; Map to store all rows , columns and their reversed versions ; Iterate in the range [ 0 , M - 1 ] ; Increment the frequency of the i 'th row by 1 ; Reverse the i 'th row ; Increment the frequency of the i 'th row by 1 ; Iterate in the range [ 0 , N - 1 ] ; Stores the i 'th column ; Iterate in the range [ 0 , M - 1 ] ; Increment the frequency of the i 'th column by 1 ; Reverse the i 'th column ; Increment the frequency of the i 'th column by 1 ; Iterate in the range [ 0 , M - 1 ] ; If frequency of the i 'th row is more in T[][] than in the mat[][]. ; Decrement the frequency of the i 'th row by 1 ; Iterate in the range [ 0 , N - 1 ] ; Stores the ith column ; Iterate in the range [ 0 , M - 1 ] ; If frequency of the i 'th column is more in T[][] than in mat[][]. ; Decrement the frequency of the i 'th column by 1 ; Return " Yes " ; Driver code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findRotation ( vector < vector < int > > & mat , vector < vector < int > > & T ) { if ( T . size ( ) != mat . size ( ) || T [ 0 ] . size ( ) != mat [ 0 ] . size ( ) ) { return " No " ; } map < vector < int > , int > m ; for ( int i = 0 ; i < mat . size ( ) ; i ++ ) { m [ mat [ i ] ] += 1 ; reverse ( mat [ i ] . begin ( ) , mat [ i ] . end ( ) ) ; m [ mat [ i ] ] += 1 ; } for ( int i = 0 ; i < mat [ 0 ] . size ( ) ; i ++ ) { vector < int > r = { } ; for ( int j = 0 ; j < mat . size ( ) ; j ++ ) { r . push_back ( mat [ j ] [ i ] ) ; } m [ r ] += 1 ; reverse ( r . begin ( ) , r . end ( ) ) ; m [ r ] += 1 ; } for ( int i = 0 ; i < T . size ( ) ; i ++ ) { if ( m [ T [ i ] ] <= 0 ) { return " No " ; } m [ T [ i ] ] -= 1 ; } for ( int i = 0 ; i < T [ 0 ] . size ( ) ; i ++ ) { vector < int > r = { } ; for ( int j = 0 ; j < T . size ( ) ; j ++ ) { r . push_back ( T [ j ] [ i ] ) ; } if ( m [ r ] <= 0 ) { return " No " ; } m [ r ] -= 1 ; } return " Yes " ; } int main ( ) { vector < vector < int > > mat = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; vector < vector < int > > T = { { 3 , 6 , 9 } , { 2 , 5 , 8 } , { 1 , 4 , 7 } } ; cout << findRotation ( mat , T ) ; return 0 ; } |
Maximum number of 0 s placed consecutively at the start and end in any rotation of a Binary String | C ++ program for the above approach ; Function to find the maximum sum of consecutive 0 s present at the start and end of a string present in any of the rotations of the given string ; Check if all the characters in the string are 0 ; Iterate over characters of the string ; If the frequency of '1' is 0 ; Print n as the result ; Concatenate the string with itself ; Stores the required result ; Generate all rotations of the string ; Store the number of consecutive 0 s at the start and end of the string ; Count 0 s present at the start ; Count 0 s present at the end ; Calculate the sum ; Update the overall maximum sum ; Print the result ; Driver Code ; Given string ; Store the size of the string | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaximumZeros ( string str , int n ) { int c0 = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( str [ i ] == '0' ) c0 ++ ; } if ( c0 == n ) { cout << n ; return ; } string s = str + str ; int mx = 0 ; for ( int i = 0 ; i < n ; ++ i ) { int cs = 0 ; int ce = 0 ; for ( int j = i ; j < i + n ; ++ j ) { if ( s [ j ] == '0' ) cs ++ ; else break ; } for ( int j = i + n - 1 ; j >= i ; -- j ) { if ( s [ j ] == '0' ) ce ++ ; else break ; } int val = cs + ce ; mx = max ( val , mx ) ; } cout << mx ; } int main ( ) { string s = "1001" ; int n = s . size ( ) ; findMaximumZeros ( s , n ) ; return 0 ; } |
Maximum number of 0 s placed consecutively at the start and end in any rotation of a Binary String | C ++ program for the above approach ; Function to find the maximum sum of consecutive 0 s present at the start and end of any rotation of the string str ; Stores the count of 0 s ; If the frequency of '1' is 0 ; Print n as the result ; Stores the required sum ; Find the maximum consecutive length of 0 s present in the string ; Update the overall maximum sum ; Find the number of 0 s present at the start and end of the string ; Update the count of 0 s at the start ; Update the count of 0 s at the end ; Update the maximum sum ; Print the result ; Driver Code ; Given string ; Store the size of the string | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaximumZeros ( string str , int n ) { int c0 = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( str [ i ] == '0' ) c0 ++ ; } if ( c0 == n ) { cout << n ; return ; } int mx = 0 ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '0' ) cnt ++ ; else { mx = max ( mx , cnt ) ; cnt = 0 ; } } mx = max ( mx , cnt ) ; int start = 0 , end = n - 1 ; cnt = 0 ; while ( str [ start ] != '1' && start < n ) { cnt ++ ; start ++ ; } while ( str [ end ] != '1' && end >= 0 ) { cnt ++ ; end -- ; } mx = max ( mx , cnt ) ; cout << mx ; } int main ( ) { string s = "1001" ; int n = s . size ( ) ; findMaximumZeros ( s , n ) ; return 0 ; } |
Modify a matrix by rotating ith row exactly i times in clockwise direction | C ++ program for the above approach ; Function to rotate every i - th row of the matrix i times ; Traverse the matrix row - wise ; Reverse the current row ; Reverse the first i elements ; Reverse the last ( N - i ) elements ; Increment count ; Print final matrix ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void rotateMatrix ( vector < vector < int > > & mat ) { int i = 0 ; for ( auto & it : mat ) { reverse ( it . begin ( ) , it . end ( ) ) ; reverse ( it . begin ( ) , it . begin ( ) + i ) ; reverse ( it . begin ( ) + i , it . end ( ) ) ; i ++ ; } for ( auto rows : mat ) { for ( auto cols : rows ) { cout << cols << " β " ; } cout << " STRNEWLINE " ; } } int main ( ) { vector < vector < int > > mat = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; rotateMatrix ( mat ) ; return 0 ; } |
Modify a string by performing given shift operations | C ++ implementataion of above approach ; Function to find the string obtained after performing given shift operations ; If shift [ i ] [ 0 ] = 0 , then left shift Otherwise , right shift ; Stores length of the string ; Effective shift calculation ; Stores modified string ; Right rotation ; Left rotation ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void stringShift ( string s , vector < vector < int > > & shift ) { int val = 0 ; for ( int i = 0 ; i < shift . size ( ) ; ++ i ) val += shift [ i ] [ 0 ] == 0 ? - shift [ i ] [ 1 ] : shift [ i ] [ 1 ] ; int len = s . length ( ) ; val = val % len ; string result = " " ; if ( val > 0 ) result = s . substr ( len - val , val ) + s . substr ( 0 , len - val ) ; else result = s . substr ( - val , len + val ) + s . substr ( 0 , - val ) ; cout << result ; } int main ( ) { string s = " abc " ; vector < vector < int > > shift = { { 0 , 1 } , { 1 , 2 } } ; stringShift ( s , shift ) ; return 0 ; } |
Modify given array to a non | C ++ program for the above approach ; Function to check if a non - decreasing array can be obtained by rotating the original array ; Stores copy of original array ; Sort the given vector ; Traverse the array ; Rotate the array by 1 ; If array is sorted ; If it is not possible to sort the array ; Driver Code ; Given array ; Size of the array ; Function call to check if it is possible to make array non - decreasing by rotating | #include <bits/stdc++.h> NEW_LINE using namespace std ; void rotateArray ( vector < int > & arr , int N ) { vector < int > v = arr ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 1 ; i <= N ; ++ i ) { rotate ( arr . begin ( ) , arr . begin ( ) + 1 , arr . end ( ) ) ; if ( arr == v ) { cout << " YES " << endl ; return ; } } cout << " NO " << endl ; } int main ( ) { vector < int > arr = { 3 , 4 , 5 , 1 , 2 } ; int N = arr . size ( ) ; rotateArray ( arr , N ) ; } |
Maximum value possible by rotating digits of a given number | C ++ program for the above approach ; Function to find the maximum value possible by rotations of digits of N ; Store the required result ; Store the number of digits ; Iterate over the range [ 1 , len - 1 ] ; Store the unit 's digit ; Store the remaining number ; Find the next rotation ; If the current rotation is greater than the overall answer , then update answer ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findLargestRotation ( int num ) { int ans = num ; int len = floor ( log10 ( num ) + 1 ) ; int x = pow ( 10 , len - 1 ) ; for ( int i = 1 ; i < len ; i ++ ) { int lastDigit = num % 10 ; num = num / 10 ; num += ( lastDigit * x ) ; if ( num > ans ) { ans = num ; } } cout << ans ; } int main ( ) { int N = 657 ; findLargestRotation ( N ) ; return 0 ; } |
Rotate digits of a given number by K | C ++ program to implement the above approach ; Function to find the count of digits in N ; Stores count of digits in N ; Calculate the count of digits in N ; Update digit ; Update N ; Function to rotate the digits of N by K ; Stores count of digits in N ; Update K so that only need to handle left rotation ; Stores first K digits of N ; Remove first K digits of N ; Stores count of digits in left_no ; Append left_no to the right of digits of N ; Driver code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfDigit ( int N ) { int digit = 0 ; while ( N > 0 ) { digit ++ ; N /= 10 ; } return digit ; } void rotateNumberByK ( int N , int K ) { int X = numberOfDigit ( N ) ; K = ( ( K % X ) + X ) % X ; int left_no = N / ( int ) ( pow ( 10 , X - K ) ) ; N = N % ( int ) ( pow ( 10 , X - K ) ) ; int left_digit = numberOfDigit ( left_no ) ; N = ( N * ( int ) ( pow ( 10 , left_digit ) ) ) + left_no ; cout << N ; } int main ( ) { int N = 12345 , K = 7 ; rotateNumberByK ( N , K ) ; return 0 ; } |
Count rotations required to sort given array in non | C ++ program for the above approach ; Function to count minimum anti - clockwise rotations required to sort the array in non - increasing order ; Stores count of arr [ i + 1 ] > arr [ i ] ; Store last index of arr [ i + 1 ] > arr [ i ] ; Traverse the given array ; If the adjacent elements are in increasing order ; Increment count ; Update index ; Print the result according to the following conditions ; Otherwise , it is not possible to sort the array ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minMovesToSort ( int arr [ ] , int N ) { int count = 0 ; int index ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) { count ++ ; index = i ; } } if ( count == 0 ) { cout << "0" ; } else if ( count == N - 1 ) { cout << N - 1 ; } else if ( count == 1 && arr [ 0 ] <= arr [ N - 1 ] ) { cout << index + 1 ; } else { cout << " - 1" ; } } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minMovesToSort ( arr , N ) ; return 0 ; } |
Maximize sum of diagonal of a matrix by rotating all rows or all columns | C ++ program to implement the above approach ; Function to find maximum sum of diagonal elements of matrix by rotating either rows or columns ; Stores maximum diagonal sum of elements of matrix by rotating rows or columns ; Rotate all the columns by an integer in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Rotate all the rows by an integer in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE int findMaximumDiagonalSumOMatrixf ( int A [ ] [ N ] ) { int maxDiagonalSum = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { int curr = 0 ; for ( int j = 0 ; j < N ; j ++ ) { curr += A [ j ] [ ( i + j ) % N ] ; } maxDiagonalSum = max ( maxDiagonalSum , curr ) ; } for ( int i = 0 ; i < N ; i ++ ) { int curr = 0 ; for ( int j = 0 ; j < N ; j ++ ) { curr += A [ ( i + j ) % N ] [ j ] ; } maxDiagonalSum = max ( maxDiagonalSum , curr ) ; } return maxDiagonalSum ; } int main ( ) { int mat [ N ] [ N ] = { { 1 , 1 , 2 } , { 2 , 1 , 2 } , { 1 , 2 , 2 } } ; cout << findMaximumDiagonalSumOMatrixf ( mat ) ; return 0 ; } |
Generate a matrix having sum of secondary diagonal equal to a perfect square | C ++ program for the above approach ; Function to print the matrix whose sum of element in secondary diagonal is a perfect square ; Iterate for next N - 1 rows ; Print the current row after the left shift ; Driver Code ; Given N ; Fill the array with elements ranging from 1 to N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void diagonalSumPerfectSquare ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { cout << ( arr [ ( j + i ) % 7 ] ) << " β " ; } cout << endl ; } } int main ( ) { int N = 7 ; int arr [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { arr [ i ] = i + 1 ; } diagonalSumPerfectSquare ( arr , N ) ; } |
Queries to find maximum sum contiguous subarrays of given length in a rotating array | C ++ program for the above approach ; Function to calculate the maximum sum of length k ; Calculating the max sum for the first k elements ; Find subarray with maximum sum ; Update the sum ; Return maximum sum ; Function to calculate gcd of the two numbers n1 and n2 ; Base Case ; Recursively find the GCD ; Function to rotate the array by Y ; For handling k >= N ; Dividing the array into number of sets ; Rotate the array by Y ; Update arr [ j ] ; Return the rotated array ; Function that performs the queries on the given array ; Traverse each query ; If query of type X = 1 ; Print the array ; If query of type X = 2 ; Driver Code ; Given array arr [ ] ; Given Queries ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int MaxSum ( vector < int > arr , int n , int k ) { int i , max_sum = 0 , sum = 0 ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } max_sum = sum ; while ( i < n ) { sum = sum - arr [ i - k ] + arr [ i ] ; if ( max_sum < sum ) { max_sum = sum ; } i ++ ; } return max_sum ; } int gcd ( int n1 , int n2 ) { if ( n2 == 0 ) { return n1 ; } else { return gcd ( n2 , n1 % n2 ) ; } } vector < int > RotateArr ( vector < int > arr , int n , int d ) { int i = 0 , j = 0 ; d = d % n ; int no_of_sets = gcd ( d , n ) ; for ( i = 0 ; i < no_of_sets ; i ++ ) { int temp = arr [ i ] ; j = i ; while ( true ) { int k = j + d ; if ( k >= n ) k = k - n ; if ( k == i ) break ; arr [ j ] = arr [ k ] ; j = k ; } arr [ j ] = temp ; } return arr ; } void performQuery ( vector < int > & arr , int Q [ ] [ 2 ] , int q ) { int N = ( int ) arr . size ( ) ; for ( int i = 0 ; i < q ; i ++ ) { if ( Q [ i ] [ 0 ] == 1 ) { arr = RotateArr ( arr , N , Q [ i ] [ 1 ] ) ; for ( auto t : arr ) { cout << t << " β " ; } cout << " STRNEWLINE " ; } else { cout << MaxSum ( arr , N , Q [ i ] [ 1 ] ) << " STRNEWLINE " ; } } } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 4 , 5 } ; int q = 5 ; int Q [ ] [ 2 ] = { { 1 , 2 } , { 2 , 3 } , { 1 , 3 } , { 1 , 1 } , { 2 , 4 } } ; performQuery ( arr , Q , q ) ; return 0 ; } |
Minimize characters to be changed to make the left and right rotation of a string same | C ++ Program of the above approach ; Function to find the minimum characters to be removed from the string ; Initialize answer by N ; If length is even ; Frequency array for odd and even indices ; Store the frequency of the characters at even and odd indices ; Stores the most occuring frequency for even and odd indices ; Update the answer ; If length is odd ; Stores the frequency of the characters of the string ; Stores the most occuring character in the string ; Update the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimumRemoval ( string str ) { int n = str . length ( ) ; int ans = n ; if ( n % 2 == 0 ) { vector < int > freqEven ( 128 ) ; vector < int > freqOdd ( 128 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { freqEven [ str [ i ] ] ++ ; } else { freqOdd [ str [ i ] ] ++ ; } } int evenMax = 0 , oddMax = 0 ; for ( char chr = ' a ' ; chr <= ' z ' ; chr ++ ) { evenMax = max ( evenMax , freqEven [ chr ] ) ; oddMax = max ( oddMax , freqOdd [ chr ] ) ; } ans = ans - evenMax - oddMax ; } else { vector < int > freq ( 128 ) ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str [ i ] ] ++ ; } int strMax = 0 ; for ( char chr = ' a ' ; chr <= ' z ' ; chr ++ ) { strMax = max ( strMax , freq [ chr ] ) ; } ans = ans - strMax ; } return ans ; } int main ( ) { string str = " geeksgeeks " ; cout << getMinimumRemoval ( str ) ; } |
Longest subsequence of a number having same left and right rotation | C ++ Program to implement the above approach ; Function to find the longest subsequence having equal left and right rotation ; Length of the string ; Iterate for all possible combinations of a two - digit numbers ; Check for alternate occurrence of current combination ; Increment the current value ; Increment the current value ; If alternating sequence is obtained of odd length ; Reduce to even length ; Update answer to store the maximum ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findAltSubSeq ( string s ) { int n = s . size ( ) , ans = INT_MIN ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { int cur = 0 , f = 0 ; for ( int k = 0 ; k < n ; k ++ ) { if ( f == 0 and s [ k ] - '0' == i ) { f = 1 ; cur ++ ; } else if ( f == 1 and s [ k ] - '0' == j ) { f = 0 ; cur ++ ; } } if ( i != j and cur % 2 == 1 ) cur -- ; ans = max ( cur , ans ) ; } } return ans ; } int main ( ) { string s = "100210601" ; cout << findAltSubSeq ( s ) ; return 0 ; } |
Rotate matrix by 45 degrees | C ++ program for the above approach ; Function to rotate matrix by 45 degree ; Counter Variable ; Iterate [ 0 , m ] ; Iterate [ 0 , n ] ; Diagonal Elements Condition ; Appending the Diagonal Elements ; Printing reversed Diagonal Elements ; Driver code ; Dimensions of Matrix ; Given matrix ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void matrix ( int n , int m , vector < vector < int > > li ) { int ctr = 0 ; while ( ctr < 2 * n - 1 ) { for ( int i = 0 ; i < abs ( n - ctr - 1 ) ; i ++ ) { cout << " β " ; } vector < int > lst ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i + j == ctr ) { lst . push_back ( li [ i ] [ j ] ) ; } } } for ( int i = lst . size ( ) - 1 ; i >= 0 ; i -- ) { cout << lst [ i ] << " β " ; } cout << endl ; ctr += 1 ; } } int main ( ) { int n = 8 ; int m = n ; vector < vector < int > > li { { 4 , 5 , 6 , 9 , 8 , 7 , 1 , 4 } , { 1 , 5 , 9 , 7 , 5 , 3 , 1 , 6 } , { 7 , 5 , 3 , 1 , 5 , 9 , 8 , 0 } , { 6 , 5 , 4 , 7 , 8 , 9 , 3 , 7 } , { 3 , 5 , 6 , 4 , 8 , 9 , 2 , 1 } , { 3 , 1 , 6 , 4 , 7 , 9 , 5 , 0 } , { 8 , 0 , 7 , 2 , 3 , 1 , 0 , 8 } , { 7 , 5 , 3 , 1 , 5 , 9 , 8 , 5 } } ; matrix ( n , m , li ) ; return 0 ; } |
Count of Array elements greater than all elements on its left and at least K elements on its right | C ++ Program to implement the above appraoch ; Structure of an AVL Tree Node ; Size of the tree rooted with this node ; Utility function to get maximum of two integers ; Utility function to get height of the tree rooted with N ; Utility function to find size of the tree rooted with N ; Utility function to get maximum of two integers ; Helper function to allocates a new node with the given key ; Utility function to right rotate subtree rooted with y ; Perform rotation ; Update heights ; Update sizes ; Return new root ; Utility function to left rotate subtree rooted with x ; Perform rotation ; Update heights ; Update sizes ; Return new root ; Function to obtain Balance factor of node N ; Function to insert a new key to the tree rooted with node ; Perform the normal BST rotation ; Update count of smaller elements ; Update height and size of the ancestor ; Get the balance factor of the ancestor ; Left Left Case ; Right Right Case ; Left Right Case ; Right Left Case ; Function to generate an array which contains count of smaller elements on the right ; Insert all elements in the AVL Tree and get the count of smaller elements ; Function to find the number of elements which are greater than all elements on its left and K elements on its right ; Stores the count of smaller elements on its right ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int key ; struct node * left ; struct node * right ; int height ; int size ; } ; int max ( int a , int b ) ; int height ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> height ; } int size ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> size ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } struct node * newNode ( int key ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> key = key ; node -> left = NULL ; node -> right = NULL ; node -> height = 1 ; node -> size = 1 ; return ( node ) ; } struct node * rightRotate ( struct node * y ) { struct node * x = y -> left ; struct node * T2 = x -> right ; x -> right = y ; y -> left = T2 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> size = size ( y -> left ) + size ( y -> right ) + 1 ; x -> size = size ( x -> left ) + size ( x -> right ) + 1 ; return x ; } struct node * leftRotate ( struct node * x ) { struct node * y = x -> right ; struct node * T2 = y -> left ; y -> left = x ; x -> right = T2 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> size = size ( x -> left ) + size ( x -> right ) + 1 ; y -> size = size ( y -> left ) + size ( y -> right ) + 1 ; return y ; } int getBalance ( struct node * N ) { if ( N == NULL ) return 0 ; return height ( N -> left ) - height ( N -> right ) ; } struct node * insert ( struct node * node , int key , int * count ) { if ( node == NULL ) return ( newNode ( key ) ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key , count ) ; else { node -> right = insert ( node -> right , key , count ) ; * count = * count + size ( node -> left ) + 1 ; } node -> height = max ( height ( node -> left ) , height ( node -> right ) ) + 1 ; node -> size = size ( node -> left ) + size ( node -> right ) + 1 ; int balance = getBalance ( node ) ; if ( balance > 1 && key < node -> left -> key ) return rightRotate ( node ) ; if ( balance < -1 && key > node -> right -> key ) return leftRotate ( node ) ; if ( balance > 1 && key > node -> left -> key ) { node -> left = leftRotate ( node -> left ) ; return rightRotate ( node ) ; } if ( balance < -1 && key < node -> right -> key ) { node -> right = rightRotate ( node -> right ) ; return leftRotate ( node ) ; } return node ; } void constructLowerArray ( int arr [ ] , int countSmaller [ ] , int n ) { int i , j ; struct node * root = NULL ; for ( i = 0 ; i < n ; i ++ ) countSmaller [ i ] = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { root = insert ( root , arr [ i ] , & countSmaller [ i ] ) ; } } int countElements ( int A [ ] , int n , int K ) { int count = 0 ; int * countSmaller = ( int * ) malloc ( sizeof ( int ) * n ) ; constructLowerArray ( A , countSmaller , n ) ; int maxi = INT_MIN ; for ( int i = 0 ; i <= ( n - K - 1 ) ; i ++ ) { if ( A [ i ] > maxi && countSmaller [ i ] >= K ) { count ++ ; maxi = A [ i ] ; } } return count ; } int main ( ) { int A [ ] = { 2 , 5 , 1 , 7 , 3 , 4 , 0 } ; int n = sizeof ( A ) / sizeof ( int ) ; int K = 3 ; cout << countElements ( A , n , K ) ; return 0 ; } |
Mth element after K Right Rotations of an Array | C ++ program to implement the above approach ; Function to return Mth element of array after k right rotations ; The array comes to original state after N rotations ; If K is greater or equal to M ; Mth element after k right rotations is ( N - K ) + ( M - 1 ) th element of the array ; Otherwise ; ( M - K - 1 ) th element of the array ; Return the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstElement ( int a [ ] , int N , int K , int M ) { K %= N ; int index ; if ( K >= M ) index = ( N - K ) + ( M - 1 ) ; else index = ( M - K - 1 ) ; int result = a [ index ] ; return result ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int K = 3 , M = 2 ; cout << getFirstElement ( a , N , K , M ) ; return 0 ; } |
Find the Mth element of the Array after K left rotations | C ++ program for the above approach ; Function to return Mth element of array after k left rotations ; The array comes to original state after N rotations ; Mth element after k left rotations is ( K + M - 1 ) % N th element of the original array ; Return the result ; Driver Code ; Array initialization ; Size of the array ; Given K rotation and Mth element to be found after K rotation ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstElement ( int a [ ] , int N , int K , int M ) { K %= N ; int index = ( K + M - 1 ) % N ; int result = a [ index ] ; return result ; } int main ( ) { int a [ ] = { 3 , 4 , 5 , 23 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int K = 2 , M = 1 ; cout << getFirstElement ( a , N , K , M ) ; return 0 ; } |
Rotate all odd numbers right and all even numbers left in an Array of 1 to N | C ++ program to implement the above approach ; function to left rotate ; function to right rotate ; Function to rotate the array ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void left_rotate ( int arr [ ] ) { int last = arr [ 1 ] ; for ( int i = 3 ; i < 6 ; i = i + 2 ) { arr [ i - 2 ] = arr [ i ] ; } arr [ 6 - 1 ] = last ; } void right_rotate ( int arr [ ] ) { int start = arr [ 6 - 2 ] ; for ( int i = 6 - 4 ; i >= 0 ; i = i - 2 ) { arr [ i + 2 ] = arr [ i ] ; } arr [ 0 ] = start ; } void rotate ( int arr [ ] ) { left_rotate ( arr ) ; right_rotate ( arr ) ; for ( int i = 0 ; i < 6 ; i ++ ) { cout << ( arr [ i ] ) << " β " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; rotate ( arr ) ; } |
Maximize count of corresponding same elements in given permutations using cyclic rotations | C ++ program for the above approach ; Function to maximize the matching pairs between two permutation using left and right rotation ; Left array store distance of element from left side and right array store distance of element from right side ; Map to store index of elements ; idx1 is index of element in first permutation idx2 is index of element in second permutation ; If element if present on same index on both permutations then distance is zero ; Calculate distance from left and right side ; Calculate distance from left and right side ; Maps to store frequencies of elements present in left and right arrays ; Find maximum frequency ; Return the result ; Driver Code ; Given permutations P1 and P2 ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumMatchingPairs ( int perm1 [ ] , int perm2 [ ] , int n ) { int left [ n ] , right [ n ] ; map < int , int > mp1 , mp2 ; for ( int i = 0 ; i < n ; i ++ ) { mp1 [ perm1 [ i ] ] = i ; } for ( int j = 0 ; j < n ; j ++ ) { mp2 [ perm2 [ j ] ] = j ; } for ( int i = 0 ; i < n ; i ++ ) { int idx2 = mp2 [ perm1 [ i ] ] ; int idx1 = i ; if ( idx1 == idx2 ) { left [ i ] = 0 ; right [ i ] = 0 ; } else if ( idx1 < idx2 ) { left [ i ] = ( n - ( idx2 - idx1 ) ) ; right [ i ] = ( idx2 - idx1 ) ; } else { left [ i ] = ( idx1 - idx2 ) ; right [ i ] = ( n - ( idx1 - idx2 ) ) ; } } map < int , int > freq1 , freq2 ; for ( int i = 0 ; i < n ; i ++ ) { freq1 [ left [ i ] ] ++ ; freq2 [ right [ i ] ] ++ ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = max ( ans , max ( freq1 [ left [ i ] ] , freq2 [ right [ i ] ] ) ) ; } return ans ; } int main ( ) { int P1 [ ] = { 5 , 4 , 3 , 2 , 1 } ; int P2 [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( P1 ) / sizeof ( P1 [ 0 ] ) ; cout << maximumMatchingPairs ( P1 , P2 , n ) ; return 0 ; } |
Count of rotations required to generate a sorted array | C ++ program to find the count of rotations ; Function to return the count of rotations ; Find the smallest element ; Return its index ; If array is not rotated at all ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotation ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] ) { return i ; } } return 0 ; } int main ( ) { int arr1 [ ] = { 4 , 5 , 1 , 2 , 3 } ; int n = sizeof ( arr1 ) / sizeof ( int ) ; cout << countRotation ( arr1 , n ) ; } |
Count of rotations required to generate a sorted array | C ++ program to implement the above approach ; Function to return the count of rotations ; If array is not rotated ; Check if current element is greater than the next element ; The next element is the smallest ; Check if current element is smaller than it 's previous element ; Current element is the smallest ; Check if current element is greater than lower bound ; The sequence is increasing so far Search for smallest element on the right subarray ; Smallest element lies on the left subarray ; Search for the smallest element on both subarrays ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotation ( int arr [ ] , int low , int high ) { if ( low > high ) { return 0 ; } int mid = low + ( high - low ) / 2 ; if ( mid < high && arr [ mid ] > arr [ mid + 1 ] ) { return mid + 1 ; } if ( mid > low && arr [ mid ] < arr [ mid - 1 ] ) { return mid ; } if ( arr [ mid ] > arr [ low ] ) { return countRotation ( arr , mid + 1 , high ) ; } if ( arr [ mid ] < arr [ high ] ) { return countRotation ( arr , low , mid - 1 ) ; } else { int rightIndex = countRotation ( arr , mid + 1 , high ) ; int leftIndex = countRotation ( arr , low , mid - 1 ) ; if ( rightIndex == 0 ) { return leftIndex ; } return rightIndex ; } } int main ( ) { int arr1 [ ] = { 4 , 5 , 1 , 2 , 3 } ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << countRotation ( arr1 , 0 , N - 1 ) ; return 0 ; } |
Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings | C ++ Program to count the minimum number of circular rotations required to obtain a given numeric strings avoiding a set of blocked strings ; If the starting string needs to be avoided ; If the final string needs to be avoided ; Variable to store count of rotations ; BFS Approach ; Store the current size of the queue ; Traverse the string ; Increase the current character ; Circular rotation ; If target is reached ; If the string formed is not one to be avoided ; Add it to the list of strings to be avoided to prevent visiting already visited states ; Decrease the current value by 1 and repeat the similar checkings ; Restore the original character ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCircularRotations ( string target , vector < string > & blocked , int N ) { string start = " " ; for ( int i = 0 ; i < N ; i ++ ) { start += '0' ; } unordered_set < string > avoid ; for ( int i = 0 ; i < blocked . size ( ) ; i ++ ) avoid . insert ( blocked [ i ] ) ; if ( avoid . find ( start ) != avoid . end ( ) ) return -1 ; if ( avoid . find ( target ) != avoid . end ( ) ) return -1 ; queue < string > qu ; qu . push ( start ) ; int count = 0 ; while ( ! qu . empty ( ) ) { count ++ ; int size = qu . size ( ) ; for ( int j = 0 ; j < size ; j ++ ) { string st = qu . front ( ) ; qu . pop ( ) ; for ( int i = 0 ; i < N ; i ++ ) { char ch = st [ i ] ; st [ i ] ++ ; if ( st [ i ] > '9' ) st [ i ] = '0' ; if ( st == target ) return count ; if ( avoid . find ( st ) == avoid . end ( ) ) qu . push ( st ) ; avoid . insert ( st ) ; st [ i ] = ch - 1 ; if ( st [ i ] < '0' ) st [ i ] = '9' ; if ( st == target ) return count ; if ( avoid . find ( st ) == avoid . end ( ) ) qu . push ( st ) ; avoid . insert ( st ) ; st [ i ] = ch ; } } } return -1 ; } int main ( ) { int N = 4 ; string target = "7531" ; vector < string > blocked = { "1543" , "7434" , "7300" , "7321" , "2427" } ; cout << minCircularRotations ( target , blocked , N ) << endl ; return 0 ; } |
Range sum queries for anticlockwise rotations of Array by K indices | C ++ Program to calculate range sum queries for anticlockwise rotations of array by K ; Function to execute the queries ; Construct a new array of size 2 * N to store prefix sum of every index ; Copy elements to the new array ; Calculate the prefix sum for every index ; Set start pointer as 0 ; Query to perform anticlockwise rotation ; Query to answer range sum ; If pointing to 1 st index ; Display the sum upto start + R ; Subtract sum upto start + L - 1 from sum upto start + R ; Driver code ; Number of query ; Store all the queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; void rotatedSumQuery ( int arr [ ] , int n , vector < vector < int > > & query , int Q ) { int prefix [ 2 * n ] ; for ( int i = 0 ; i < n ; i ++ ) { prefix [ i ] = arr [ i ] ; prefix [ i + n ] = arr [ i ] ; } for ( int i = 1 ; i < 2 * n ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; int start = 0 ; for ( int q = 0 ; q < Q ; q ++ ) { if ( query [ q ] [ 0 ] == 1 ) { int k = query [ q ] [ 1 ] ; start = ( start + k ) % n ; } else if ( query [ q ] [ 0 ] == 2 ) { int L , R ; L = query [ q ] [ 1 ] ; R = query [ q ] [ 2 ] ; if ( start + L == 0 ) cout << prefix [ start + R ] << endl ; else cout << prefix [ start + R ] - prefix [ start + L - 1 ] << endl ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int Q = 5 ; vector < vector < int > > query = { { 2 , 1 , 3 } , { 1 , 3 } , { 2 , 0 , 3 } , { 1 , 4 } , { 2 , 3 , 5 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rotatedSumQuery ( arr , n , query , Q ) ; return 0 ; } |
Check if a string can be formed from another string by at most X circular clockwise shifts | C ++ implementation to check that a given string can be converted to another string by circular clockwise shift of each character by atmost X times ; Function to check that all characters of s1 can be converted to s2 by circular clockwise shift atmost X times ; Check for all characters of the strings whether the difference between their ascii values is less than X or not ; If both the characters are same ; Calculate the difference between the ASCII values of the characters ; If difference exceeds X ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isConversionPossible ( string s1 , string s2 , int x ) { int diff , n ; n = s1 . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s1 [ i ] == s2 [ i ] ) continue ; diff = ( int ( s2 [ i ] - s1 [ i ] ) + 26 ) % 26 ; if ( diff > x ) { cout << " NO " << endl ; return ; } } cout << " YES " << endl ; } int main ( ) { string s1 = " you " ; string s2 = " ara " ; int x = 6 ; isConversionPossible ( s1 , s2 , x ) ; return 0 ; } |
Count rotations which are divisible by 10 | C ++ implementation to find the count of rotations which are divisible by 10 ; Function to return the count of all the rotations which are divisible by 10. ; Loop to iterate through the number ; If the last digit is 0 , then increment the count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotation ( int n ) { int count = 0 ; do { int digit = n % 10 ; if ( digit == 0 ) count ++ ; n = n / 10 ; } while ( n != 0 ) ; return count ; } int main ( ) { int n = 10203 ; cout << countRotation ( n ) ; } |
Clockwise rotation of Linked List | C ++ implementation of the approach ; Link list node ; A utility function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; A utility function to print linked list ; Function that rotates the given linked list clockwise by k and returns the updated head pointer ; If the linked list is empty ; len is used to store length of the linked list tmp will point to the last node after this loop ; If k is greater than the size of the linked list ; Subtract from length to convert it into left rotation ; If no rotation needed then return the head node ; current will either point to kth or NULL after this loop ; If current is NULL then k is equal to the count of nodes in the list Don 't change the list in this case ; current points to the kth node ; Change next of last node to previous head ; Change head to ( k + 1 ) th node ; Change next of kth node to NULL ; Return the updated head pointer ; Driver code ; The constructed linked list is : 1 -> 2 -> 3 -> 4 -> 5 ; Rotate the linked list ; Print the rotated linked list | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " β - > β " ; node = node -> next ; } cout << " NULL " ; } Node * rightRotate ( Node * head , int k ) { if ( ! head ) return head ; Node * tmp = head ; int len = 1 ; while ( tmp -> next != NULL ) { tmp = tmp -> next ; len ++ ; } if ( k > len ) k = k % len ; k = len - k ; if ( k == 0 k == len ) return head ; Node * current = head ; int cnt = 1 ; while ( cnt < k && current != NULL ) { current = current -> next ; cnt ++ ; } if ( current == NULL ) return head ; Node * kthnode = current ; tmp -> next = head ; head = kthnode -> next ; kthnode -> next = NULL ; return head ; } int main ( ) { Node * head = NULL ; push ( & head , 5 ) ; push ( & head , 4 ) ; push ( & head , 3 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; int k = 2 ; Node * updated_head = rightRotate ( head , k ) ; printList ( updated_head ) ; return 0 ; } |
Check if it is possible to make array increasing or decreasing by rotating the array | C ++ implementation of the approach ; Function that returns true if the array can be made increasing or decreasing after rotating it in any direction ; If size of the array is less than 3 ; Check if the array is already decreasing ; If the array is already decreasing ; Check if the array is already increasing ; If the array is already increasing ; Find the indices of the minimum and the maximum value ; Check if we can make array increasing ; If the array is increasing upto max index and minimum element is right to maximum ; Check if array increasing again or not ; Check if we can make array decreasing ; If the array is decreasing upto min index and minimum element is left to maximum ; Check if array decreasing again or not ; If it is not possible to make the array increasing or decreasing ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int a [ ] , int n ) { if ( n <= 2 ) return true ; int flag = 0 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( ! ( a [ i ] > a [ i + 1 ] and a [ i + 1 ] > a [ i + 2 ] ) ) { flag = 1 ; break ; } } if ( flag == 0 ) return true ; flag = 0 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( ! ( a [ i ] < a [ i + 1 ] and a [ i + 1 ] < a [ i + 2 ] ) ) { flag = 1 ; break ; } } if ( flag == 0 ) return true ; int val1 = INT_MAX , mini = -1 , val2 = INT_MIN , maxi ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] < val1 ) { mini = i ; val1 = a [ i ] ; } if ( a [ i ] > val2 ) { maxi = i ; val2 = a [ i ] ; } } flag = 1 ; for ( int i = 0 ; i < maxi ; i ++ ) { if ( a [ i ] > a [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 and maxi + 1 == mini ) { flag = 1 ; for ( int i = mini ; i < n - 1 ; i ++ ) { if ( a [ i ] > a [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 ) return true ; } flag = 1 ; for ( int i = 0 ; i < mini ; i ++ ) { if ( a [ i ] < a [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 and maxi - 1 == mini ) { flag = 1 ; for ( int i = maxi ; i < n - 1 ; i ++ ) { if ( a [ i ] < a [ i + 1 ] ) { flag = 0 ; break ; } } if ( flag == 1 ) return true ; } return false ; } int main ( ) { int a [ ] = { 4 , 5 , 6 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( isPossible ( a , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count number of rotated strings which have more number of vowels in the first half than second half | C ++ implementation of the approach ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntRotations ( string s , int n ) { string str = s + s ; int pre [ 2 * n ] = { 0 } ; for ( int i = 0 ; i < 2 * n ; i ++ ) { if ( i != 0 ) pre [ i ] += pre [ i - 1 ] ; if ( str [ i ] == ' a ' str [ i ] == ' e ' str [ i ] == ' i ' str [ i ] == ' o ' str [ i ] == ' u ' ) { pre [ i ] ++ ; } } int ans = 0 ; for ( int i = n - 1 ; i < 2 * n - 1 ; i ++ ) { int r = i , l = i - n ; int x1 = pre [ r ] ; if ( l >= 0 ) x1 -= pre [ l ] ; r = i - n / 2 ; int left = pre [ r ] ; if ( l >= 0 ) left -= pre [ l ] ; int right = x1 - left ; if ( left > right ) { ans ++ ; } } return ans ; } int main ( ) { string s = " abecidft " ; int n = s . length ( ) ; cout << cntRotations ( s , n ) ; return 0 ; } |
Count number of rotated strings which have more number of vowels in the first half than second half | C ++ implementation of the approach ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int cntRotations ( char s [ ] , int n ) { int lh = 0 , rh = 0 , i , ans = 0 ; for ( i = 0 ; i < n / 2 ; ++ i ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { lh ++ ; } for ( i = n / 2 ; i < n ; ++ i ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { rh ++ ; } if ( lh > rh ) ans ++ ; for ( i = 1 ; i < n ; ++ i ) { if ( s [ i - 1 ] == ' a ' s [ i - 1 ] == ' e ' s [ i - 1 ] == ' i ' s [ i - 1 ] == ' o ' s [ i - 1 ] == ' u ' ) { rh ++ ; lh -- ; } if ( s [ ( i - 1 + n / 2 ) % n ] == ' a ' || s [ ( i - 1 + n / 2 ) % n ] == ' e ' || s [ ( i - 1 + n / 2 ) % n ] == ' i ' || s [ ( i - 1 + n / 2 ) % n ] == ' o ' || s [ ( i - 1 + n / 2 ) % n ] == ' u ' ) { rh -- ; lh ++ ; } if ( lh > rh ) ans ++ ; } return ans ; } int main ( ) { char s [ ] = " abecidft " ; int n = strlen ( s ) ; cout << " β " << cntRotations ( s , n ) ; return 0 ; } |
Queries for rotation and Kth character of the given string in constant time | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define size 2 NEW_LINE void performQueries ( string str , int n , int queries [ ] [ size ] , int q ) { int ptr = 0 ; for ( int i = 0 ; i < q ; i ++ ) { if ( queries [ i ] [ 0 ] == 1 ) { ptr = ( ptr + queries [ i ] [ 1 ] ) % n ; } else { int k = queries [ i ] [ 1 ] ; int index = ( ptr + k - 1 ) % n ; cout << str [ index ] << " STRNEWLINE " ; } } } int main ( ) { string str = " abcdefgh " ; int n = str . length ( ) ; int queries [ ] [ size ] = { { 1 , 2 } , { 2 , 2 } , { 1 , 4 } , { 2 , 7 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; performQueries ( str , n , queries , q ) ; return 0 ; } |
Check if a string can be obtained by rotating another string d places | C ++ implementation of the approach ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ReverseArray ( string & arr , int left , int right ) { char temp ; while ( left < right ) { temp = arr [ left ] ; arr [ left ] = arr [ right ] ; arr [ right ] = temp ; left ++ ; right -- ; } } bool RotateAndCheck ( string & str1 , string & str2 , int d ) { if ( str1 . length ( ) != str2 . length ( ) ) return false ; string left_rot_str1 , right_rot_str1 ; bool left_flag = true , right_flag = true ; int str1_size = str1 . size ( ) ; for ( int i = 0 ; i < str1_size ; i ++ ) { left_rot_str1 . push_back ( str1 [ i ] ) ; right_rot_str1 . push_back ( str1 [ i ] ) ; } ReverseArray ( left_rot_str1 , 0 , d - 1 ) ; ReverseArray ( left_rot_str1 , d , str1_size - 1 ) ; ReverseArray ( left_rot_str1 , 0 , str1_size - 1 ) ; ReverseArray ( right_rot_str1 , 0 , str1_size - d - 1 ) ; ReverseArray ( right_rot_str1 , str1_size - d , str1_size - 1 ) ; ReverseArray ( right_rot_str1 , 0 , str1_size - 1 ) ; for ( int i = 0 ; i < str1_size ; i ++ ) { if ( left_rot_str1 [ i ] != str2 [ i ] ) { left_flag = false ; } if ( right_rot_str1 [ i ] != str2 [ i ] ) { right_flag = false ; } } if ( left_flag right_flag ) return true ; return false ; } int main ( ) { string str1 = " abcdefg " ; string str2 = " cdefgab " ; int d = 2 ; d = d % str1 . size ( ) ; if ( RotateAndCheck ( str1 , str2 , d ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Count rotations of N which are Odd and Even | C ++ implementation of the above approach ; Function to count of all rotations which are odd and even ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countOddRotations ( int n ) { int odd_count = 0 , even_count = 0 ; do { int digit = n % 10 ; if ( digit % 2 == 1 ) odd_count ++ ; else even_count ++ ; n = n / 10 ; } while ( n != 0 ) ; cout << " Odd β = β " << odd_count << endl ; cout << " Even β = β " << even_count << endl ; } int main ( ) { int n = 1234 ; countOddRotations ( n ) ; } |
Generate all rotations of a number | C ++ implementation of the approach ; Function to return the count of digits of n ; Function to print the left shift numbers ; Formula to calculate left shift from previous number ; Update the original number ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfDigits ( int n ) { int cnt = 0 ; while ( n > 0 ) { cnt ++ ; n /= 10 ; } return cnt ; } void cal ( int num ) { int digits = numberOfDigits ( num ) ; int powTen = pow ( 10 , digits - 1 ) ; for ( int i = 0 ; i < digits - 1 ; i ++ ) { int firstDigit = num / powTen ; int left = ( ( num * 10 ) + firstDigit ) - ( firstDigit * powTen * 10 ) ; cout << left << " β " ; num = left ; } } int main ( ) { int num = 1445 ; cal ( num ) ; return 0 ; } |
Generating Lyndon words of length n | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int n = 2 ; char S [ ] = { '0' , '1' , '2' } ; int k = 3 ; sort ( S , S + 3 ) ; vector < int > w ; w . push_back ( -1 ) ; while ( w . size ( ) > 0 ) { w [ w . size ( ) - 1 ] ++ ; int m = w . size ( ) ; if ( m == n ) { string str ; for ( int i = 0 ; i < w . size ( ) ; i ++ ) { str += S [ w [ i ] ] ; } cout << str << endl ; } while ( w . size ( ) < n ) { w . push_back ( w [ w . size ( ) - m ] ) ; } while ( w . size ( ) > 0 && w [ w . size ( ) - 1 ] == k - 1 ) { w . pop_back ( ) ; } } return 0 ; } |
Check whether all the rotations of a given number is greater than or equal to the given number or not | CPP 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void CheckKCycles ( int n , string s ) { bool ff = true ; int x = 0 ; for ( int i = 1 ; i < n ; i ++ ) { x = ( s . substr ( i ) + s . substr ( 0 , i ) ) . length ( ) ; if ( x >= s . length ( ) ) { continue ; } ff = false ; break ; } if ( ff ) { cout << ( " Yes " ) ; } else { cout << ( " No " ) ; } } int main ( ) { int n = 3 ; string s = "123" ; CheckKCycles ( n , s ) ; return 0 ; } |
Rotate the sub | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct ListNode { int data ; struct ListNode * next ; } ; void rotateSubList ( ListNode * A , int m , int n , int k ) { int size = n - m + 1 ; if ( k > size ) { k = k % size ; } if ( k == 0 k == size ) { ListNode * head = A ; while ( head != NULL ) { cout << head -> data ; head = head -> next ; } return ; } ListNode * link = NULL ; if ( m == 1 ) { link = A ; } ListNode * c = A ; int count = 0 ; ListNode * end = NULL ; ListNode * pre = NULL ; while ( c != NULL ) { count ++ ; if ( count == m - 1 ) { pre = c ; link = c -> next ; } if ( count == n - k ) { if ( m == 1 ) { end = c ; A = c -> next ; } else { end = c ; pre -> next = c -> next ; } } if ( count == n ) { ListNode * d = c -> next ; c -> next = link ; end -> next = d ; ListNode * head = A ; while ( head != NULL ) { cout << head -> data << " β " ; head = head -> next ; } return ; } c = c -> next ; } } void push ( struct ListNode * * head , int val ) { struct ListNode * new_node = new ListNode ; new_node -> data = val ; new_node -> next = ( * head ) ; ( * head ) = new_node ; } int main ( ) { struct ListNode * head = NULL ; push ( & head , 70 ) ; push ( & head , 60 ) ; push ( & head , 50 ) ; push ( & head , 40 ) ; push ( & head , 30 ) ; push ( & head , 20 ) ; push ( & head , 10 ) ; ListNode * tmp = head ; cout << " Given β List : β " ; while ( tmp != NULL ) { cout << tmp -> data << " β " ; tmp = tmp -> next ; } cout << endl ; int m = 3 , n = 6 , k = 2 ; cout << " After β rotation β of β sublist : β " ; rotateSubList ( head , m , n , k ) ; return 0 ; } |
Generating numbers that are divisor of their right | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool rightRotationDivisor ( int N ) { int lastDigit = N % 10 ; int rightRotation = ( lastDigit * pow ( 10 , int ( log10 ( N ) ) ) ) + floor ( N / 10 ) ; return ( rightRotation % N == 0 ) ; } void generateNumbers ( int m ) { for ( int i = pow ( 10 , ( m - 1 ) ) ; i < pow ( 10 , m ) ; i ++ ) if ( rightRotationDivisor ( i ) ) cout << i << endl ; } int main ( ) { int m = 3 ; generateNumbers ( m ) ; } |
Generating numbers that are divisor of their right | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generateNumbers ( int m ) { vector < int > numbers ; int k_max , x ; for ( int y = 0 ; y < 10 ; y ++ ) { k_max = ( int ) ( pow ( 10 , m - 2 ) * ( 10 * y + 1 ) ) / ( int ) ( pow ( 10 , m - 1 ) + y ) ; for ( int k = 1 ; k <= k_max ; k ++ ) { x = ( int ) ( y * ( pow ( 10 , m - 1 ) - k ) ) / ( 10 * k - 1 ) ; if ( ( int ) ( y * ( pow ( 10 , m - 1 ) - k ) ) % ( 10 * k - 1 ) == 0 ) numbers . push_back ( 10 * x + y ) ; } } sort ( numbers . begin ( ) , numbers . end ( ) ) ; for ( int i = 0 ; i < numbers . size ( ) ; i ++ ) cout << ( numbers [ i ] ) << endl ; } int main ( ) { int m = 3 ; generateNumbers ( m ) ; } |
Check if an array is sorted and rotated | CPP 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 starting element of the array for arrays like [ 3 , 4 , 6 , 1 , 2 , 5 ] - not circular array ; Driver code ; Function Call | #include <climits> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void checkIfSortRotated ( int arr [ ] , int n ) { int minEle = INT_MAX ; int maxEle = INT_MIN ; int minIndex = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < minEle ) { minEle = arr [ i ] ; minIndex = i ; } } int flag1 = 1 ; for ( int i = 1 ; i < minIndex ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] ) { flag1 = 0 ; break ; } } int flag2 = 1 ; for ( int i = minIndex + 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] ) { flag2 = 0 ; break ; } } if ( flag1 && flag2 && ( arr [ n - 1 ] < arr [ 0 ] ) ) cout << " YES " ; else cout << " NO " ; } int main ( ) { int arr [ ] = { 3 , 4 , 5 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkIfSortRotated ( arr , n ) ; return 0 ; } |
Check if an array is sorted and rotated | ; Function to check if an array is Sorted and rotated clockwise ; Your code here Initializing two variables x , y as zero . ; Traversing array 0 to last element . n - 1 is taken as we used i + 1. ; If till now both x , y are greater then 1 means array is not sorted . If both any of x , y is zero means array is not rotated . ; Checking for last element with first . ; Checking for final result . ; If still not true then definetly false . ; Driver Code Starts . ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkRotatedAndSorted ( int arr [ ] , int n ) { int x = 0 , y = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] < arr [ i + 1 ] ) x ++ ; else y ++ ; } if ( x == 1 y == 1 ) { if ( arr [ n - 1 ] < arr [ 0 ] ) x ++ ; else y ++ ; if ( x == 1 y == 1 ) return true ; } return false ; } int main ( ) { int arr [ ] = { 4 , 5 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkRotatedAndSorted ( arr , n ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; } |
Rotate a matrix by 90 degree in clockwise direction without using any extra space | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE void rotate90Clockwise ( int arr [ N ] [ N ] ) { for ( int j = 0 ; j < N ; j ++ ) { for ( int i = N - 1 ; i >= 0 ; i -- ) cout << arr [ i ] [ j ] << " β " ; cout << ' ' ; } } int main ( ) { int arr [ N ] [ N ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; rotate90Clockwise ( arr ) ; return 0 ; } |
Rotate a matrix by 90 degree in clockwise direction without using any extra space | ; rotate function ; First rotation with respect to main diagonal ; Second rotation with respect to middle column ; to print matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE void rotate ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < i ; ++ j ) { int temp = arr [ i ] [ j ] ; arr [ i ] [ j ] = arr [ j ] [ i ] ; arr [ j ] [ i ] = temp ; } } for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N / 2 ; ++ j ) { int temp = arr [ i ] [ j ] ; arr [ i ] [ j ] = arr [ i ] [ N - j - 1 ] ; arr [ i ] [ N - j - 1 ] = temp ; } } } void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) cout << arr [ i ] [ j ] << " β " ; cout << ' ' ; } } int main ( ) { int arr [ N ] [ N ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; rotate ( arr ) ; print ( arr ) ; return 0 ; } |
Rotate a matrix by 90 degree in clockwise direction without using any extra space | ; rotate function ; First rotation with respect to Secondary diagonal ; Second rotation with respect to middle row ; To print matrix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE void rotate ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N - i ; j ++ ) { int temp = arr [ i ] [ j ] ; arr [ i ] [ j ] = arr [ N - 1 - j ] [ N - 1 - i ] ; arr [ N - 1 - j ] [ N - 1 - i ] = temp ; } } for ( int i = 0 ; i < N / 2 ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { int temp = arr [ i ] [ j ] ; arr [ i ] [ j ] = arr [ N - 1 - i ] [ j ] ; arr [ N - 1 - i ] [ j ] = temp ; } } } void print ( int arr [ N ] [ N ] ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) cout << arr [ i ] [ j ] << " β " ; cout << ' ' ; } } int main ( ) { int arr [ N ] [ N ] = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } , { 13 , 14 , 15 , 16 } } ; rotate ( arr ) ; print ( arr ) ; return 0 ; } |
Elements that occurred only once in the array | C ++ implementation of above approach ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void occurredOnce ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; if ( arr [ 0 ] != arr [ 1 ] ) cout << arr [ 0 ] << " β " ; for ( int i = 1 ; i < n - 1 ; i ++ ) if ( arr [ i ] != arr [ i + 1 ] && arr [ i ] != arr [ i - 1 ] ) cout << arr [ i ] << " β " ; if ( arr [ n - 2 ] != arr [ n - 1 ] ) cout << arr [ n - 1 ] << " β " ; } int main ( ) { int arr [ ] = { 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; occurredOnce ( arr , n ) ; return 0 ; } |
Elements that occurred only once in the array | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void occurredOnce ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] ++ ; for ( auto it = mp . begin ( ) ; it != mp . end ( ) ; it ++ ) if ( it -> second == 1 ) cout << it -> first << " β " ; } int main ( ) { int arr [ ] = { 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; occurredOnce ( arr , n ) ; return 0 ; } |
Elements that occurred only once in the array | C ++ implementation to find elements that appeared only once ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void occurredOnce ( int arr [ ] , int n ) { int i = 1 , len = n ; if ( arr [ 0 ] == arr [ len - 1 ] ) { i = 2 ; len -- ; } for ( ; i < n ; i ++ ) if ( arr [ i ] == arr [ i - 1 ] ) i ++ ; else cout << arr [ i - 1 ] << " β " ; if ( arr [ n - 1 ] != arr [ 0 ] && arr [ n - 1 ] != arr [ n - 2 ] ) cout << arr [ n - 1 ] ; } int main ( ) { int arr [ ] = { 7 , 7 , 8 , 8 , 9 , 1 , 1 , 4 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; occurredOnce ( arr , n ) ; return 0 ; } |
Split the array and add the first part to the end | Set 2 | C ++ program to Split the array and add the first part to the end ; 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 program to test above functions ; Function calling | #include <bits/stdc++.h> NEW_LINE using namespace std ; void rvereseArray ( int arr [ ] , int start , int end ) { while ( start < end ) { int temp = arr [ start ] ; arr [ start ] = arr [ end ] ; arr [ end ] = temp ; start ++ ; end -- ; } } void printArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " β " ; } void splitArr ( int arr [ ] , int k , int n ) { rvereseArray ( arr , 0 , n - 1 ) ; rvereseArray ( arr , 0 , n - k - 1 ) ; rvereseArray ( arr , n - k , n - 1 ) ; } int main ( ) { int arr [ ] = { 12 , 10 , 5 , 6 , 52 , 36 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; splitArr ( arr , k , n ) ; printArray ( arr , n ) ; return 0 ; } |
Check if strings are rotations of each other or not | Set 2 | C ++ 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isRotation ( string a , string b ) { int n = a . length ( ) ; int m = b . length ( ) ; if ( n != m ) return false ; int lps [ n ] ; int len = 0 ; int i = 1 ; lps [ 0 ] = 0 ; while ( i < n ) { if ( a [ i ] == b [ len ] ) { lps [ i ] = ++ len ; ++ i ; } else { if ( len == 0 ) { lps [ i ] = 0 ; ++ i ; } else { len = lps [ len - 1 ] ; } } } i = 0 ; for ( int k = lps [ n - 1 ] ; k < m ; ++ k ) { if ( b [ k ] != a [ i ++ ] ) return false ; } return true ; } int main ( ) { string s1 = " ABACD " ; string s2 = " CDABA " ; cout << ( isRotation ( s1 , s2 ) ? "1" : "0" ) ; } |
Count rotations divisible by 8 | C ++ program to count all 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 program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotationsDivBy8 ( string n ) { int len = n . length ( ) ; int count = 0 ; if ( len == 1 ) { int oneDigit = n [ 0 ] - '0' ; if ( oneDigit % 8 == 0 ) return 1 ; return 0 ; } if ( len == 2 ) { int first = ( n [ 0 ] - '0' ) * 10 + ( n [ 1 ] - '0' ) ; int second = ( n [ 1 ] - '0' ) * 10 + ( n [ 0 ] - '0' ) ; if ( first % 8 == 0 ) count ++ ; if ( second % 8 == 0 ) count ++ ; return count ; } int threeDigit ; for ( int i = 0 ; i < ( len - 2 ) ; i ++ ) { threeDigit = ( n [ i ] - '0' ) * 100 + ( n [ i + 1 ] - '0' ) * 10 + ( n [ i + 2 ] - '0' ) ; if ( threeDigit % 8 == 0 ) count ++ ; } threeDigit = ( n [ len - 1 ] - '0' ) * 100 + ( n [ 0 ] - '0' ) * 10 + ( n [ 1 ] - '0' ) ; if ( threeDigit % 8 == 0 ) count ++ ; threeDigit = ( n [ len - 2 ] - '0' ) * 100 + ( n [ len - 1 ] - '0' ) * 10 + ( n [ 0 ] - '0' ) ; if ( threeDigit % 8 == 0 ) count ++ ; return count ; } int main ( ) { string n = "43262488612" ; cout << " Rotations : β " << countRotationsDivBy8 ( n ) ; return 0 ; } |
Minimum move to end operations to make all strings equal | CPP 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 for above function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimunMoves ( string arr [ ] , int n ) { int ans = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { int curr_count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { string tmp = arr [ j ] + arr [ j ] ; int index = tmp . find ( arr [ i ] ) ; if ( index == string :: npos ) return -1 ; curr_count += index ; } ans = min ( curr_count , ans ) ; } return ans ; } int main ( ) { string arr [ ] = { " xzzwo " , " zwoxz " , " zzwox " , " xzzwo " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimunMoves ( arr , n ) ; return 0 ; } |
Count rotations in sorted and rotated linked list | Program for count number of rotations in sorted 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 NULL . ; 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 functions ; Create a node and initialize with NULL ; push ( ) insert node in linked list . 15 -> 18 -> 5 -> 8 -> 11 -> 12 ; Function call countRotation ( ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; int countRotation ( struct Node * head ) { int count = 0 ; int min = head -> data ; while ( head != NULL ) { if ( min > head -> data ) break ; count ++ ; head = head -> next ; } return count ; } void push ( struct Node * * head , int data ) { struct Node * newNode = new Node ; newNode -> data = data ; newNode -> next = ( * head ) ; ( * head ) = newNode ; } void printList ( struct Node * node ) { while ( node != NULL ) { printf ( " % d β " , node -> data ) ; node = node -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 11 ) ; push ( & head , 8 ) ; push ( & head , 5 ) ; push ( & head , 18 ) ; push ( & head , 15 ) ; printList ( head ) ; cout << endl ; cout << " Linked β list β rotated β elements : β " ; cout << countRotation ( head ) << endl ; return 0 ; } |
Rotate Linked List block wise | C ++ program to rotate a 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 -> NULL ; k is block size and d is number of rotations in every block . | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; Node * rotateHelper ( Node * blockHead , Node * blockTail , int d , Node * * tail , int k ) { if ( d == 0 ) return blockHead ; if ( d > 0 ) { Node * temp = blockHead ; for ( int i = 1 ; temp -> next -> next && i < k - 1 ; i ++ ) temp = temp -> next ; blockTail -> next = blockHead ; * tail = temp ; return rotateHelper ( blockTail , temp , d - 1 , tail , k ) ; } if ( d < 0 ) { blockTail -> next = blockHead ; * tail = blockHead ; return rotateHelper ( blockHead -> next , blockHead , d + 1 , tail , k ) ; } } Node * rotateByBlocks ( Node * head , int k , int d ) { if ( ! head ! head -> next ) return head ; if ( d == 0 ) return head ; Node * temp = head , * tail = NULL ; int i ; for ( i = 1 ; temp -> next && i < k ; i ++ ) temp = temp -> next ; Node * nextBlock = temp -> next ; if ( i < k ) head = rotateHelper ( head , temp , d % k , & tail , i ) ; else head = rotateHelper ( head , temp , d % k , & tail , k ) ; tail -> next = rotateByBlocks ( nextBlock , k , d % k ) ; return head ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " β " ; node = node -> next ; } } int main ( ) { Node * head = NULL ; for ( int i = 9 ; i > 0 ; i -= 1 ) push ( & head , i ) ; cout << " Given β linked β list β STRNEWLINE " ; printList ( head ) ; int k = 3 , d = 2 ; head = rotateByBlocks ( head , k , d ) ; cout << " Rotated by blocks Linked list " ; printList ( head ) ; return ( 0 ) ; } |
Check if two numbers are bit rotations of each other or not | C ++ program to check if two numbers are bit rotations of each other . ; 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 to test above function | #include <iostream> NEW_LINE using namespace std ; bool isRotation ( unsigned int x , unsigned int y ) { unsigned long long int x64 = x | ( ( unsigned long long int ) x << 32 ) ; while ( x64 >= y ) { if ( unsigned ( x64 ) == y ) return true ; x64 >>= 1 ; } return false ; } int main ( ) { unsigned int x = 122 ; unsigned int y = 2147483678 ; if ( isRotation ( x , y ) ) cout << " yes " << endl ; else cout << " no " << endl ; return 0 ; } |
Count rotations divisible by 4 | C ++ program to count all rotation 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countRotations ( string n ) { int len = n . length ( ) ; if ( len == 1 ) { int oneDigit = n . at ( 0 ) - '0' ; if ( oneDigit % 4 == 0 ) return 1 ; return 0 ; } int twoDigit , count = 0 ; for ( int i = 0 ; i < ( len - 1 ) ; i ++ ) { twoDigit = ( n . at ( i ) - '0' ) * 10 + ( n . at ( i + 1 ) - '0' ) ; if ( twoDigit % 4 == 0 ) count ++ ; } twoDigit = ( n . at ( len - 1 ) - '0' ) * 10 + ( n . at ( 0 ) - '0' ) ; if ( twoDigit % 4 == 0 ) count ++ ; return count ; } int main ( ) { string n = "4834" ; cout << " Rotations : β " << countRotations ( n ) << endl ; return 0 ; } |
Check if a string can be obtained by rotating another string 2 places | C ++ program to check if a string is two time rotation of another string . ; 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 | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isRotated ( string str1 , string str2 ) { if ( str1 . length ( ) != str2 . length ( ) ) return false ; if ( str1 . length ( ) < 2 ) { return str1 . compare ( str2 ) == 0 ; } string clock_rot = " " ; string anticlock_rot = " " ; int len = str2 . length ( ) ; anticlock_rot = anticlock_rot + str2 . substr ( len - 2 , 2 ) + str2 . substr ( 0 , len - 2 ) ; clock_rot = clock_rot + str2 . substr ( 2 ) + str2 . substr ( 0 , 2 ) ; return ( str1 . compare ( clock_rot ) == 0 || str1 . compare ( anticlock_rot ) == 0 ) ; } int main ( ) { string str1 = " geeks " ; string str2 = " eksge " ; isRotated ( str1 , str2 ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Lexicographically minimum string rotation | Set 1 | A simple C ++ program to find lexicographically minimum rotation of a given string ; This functionr 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 program to test above function | #include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; string minLexRotation ( string str ) { int n = str . length ( ) ; string arr [ n ] ; string concat = str + str ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = concat . substr ( i , n ) ; sort ( arr , arr + n ) ; return arr [ 0 ] ; } int main ( ) { cout << minLexRotation ( " GEEKSFORGEEKS " ) << endl ; cout << minLexRotation ( " GEEKSQUIZ " ) << endl ; cout << minLexRotation ( " BCABDADAB " ) << endl ; } |
Next Greater Element in a Circular Linked List | C ++ program for the above approach ; Node structure of the circular Linked list ; Constructor ; Function to print the elements of a Linked list ; Iterate the linked list ; Print the data ; Function to find the next greater element for each node ; Stores the head of circular Linked list ; Stores the head of the resulting linked list ; Stores the temporary head of the resulting Linked list ; Iterate until head is not equal to H ; Used to iterate over the circular Linked List ; Stores if there exist any next Greater element ; Iterate until head is not equal to curr ; If the current node is smaller ; Update the value of Val ; Update curr ; If res is Null ; Create new Node with value curr -> data ; Assign address of res to tempList ; Update tempList ; Assign address of the next node to tempList ; Update the value of head node ; Print the resulting Linked list ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; Node ( int d ) { data = d ; next = NULL ; } } ; void print ( Node * head ) { Node * temp = head ; while ( temp != NULL ) { cout << temp -> data << " β " ; temp = temp -> next ; } } void NextGreaterElement ( Node * head ) { Node * H = head ; Node * res = NULL ; Node * tempList = NULL ; do { Node * curr = head ; int Val = -1 ; do { if ( head -> data < curr -> data ) { Val = curr -> data ; break ; } curr = curr -> next ; } while ( curr != head ) ; if ( res == NULL ) { res = new Node ( Val ) ; tempList = res ; } else { tempList -> next = new Node ( Val ) ; tempList = tempList -> next ; } head = head -> next ; } while ( head != H ) ; print ( res ) ; } int main ( ) { Node * head = new Node ( 1 ) ; head -> next = new Node ( 5 ) ; head -> next -> next = new Node ( 12 ) ; head -> next -> next -> next = new Node ( 10 ) ; head -> next -> next -> next -> next = new Node ( 0 ) ; head -> next -> next -> next -> next -> next = head ; NextGreaterElement ( head ) ; return 0 ; } |
Types of Linked List | Node of a doubly linked list | class Node { public : int data ; Node * next ; } ; |
Types of Linked List | C ++ program to illustrate creation and traversal of Singly Linked List ; Structure of Node ; Function to print the content of linked list starting from the given node ; Iterate till n reaches NULL ; Print the data ; Driver Code ; Allocate 3 nodes in the heap ; Assign data in first node ; Link first node with second ; Assign data to second node ; Assign data to third node | #include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void printList ( Node * n ) { while ( n != NULL ) { cout << n -> data << " β " ; n = n -> next ; } } int main ( ) { Node * head = NULL ; Node * second = NULL ; Node * third = NULL ; head = new Node ( ) ; second = new Node ( ) ; third = new Node ( ) ; head -> data = 1 ; head -> next = second ; second -> data = 2 ; second -> next = third ; third -> data = 3 ; third -> next = NULL ; printList ( head ) ; return 0 ; } |
Types of Linked List | Node of a doubly linked list | struct Node { int data ; struct Node * next ; struct Node * prev ; } ; |
Types of Linked List | Structure for a node | class Node { public : int data ; Node * next ; } ; |
Types of Linked List | Node of doubly circular linked list | struct Node { int data ; struct Node * next ; struct Node * prev ; } ; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.